Skip to content

Commit 8b39926

Browse files
FSparkjosStorer
authored andcommitted
fix: unable to get balance from OpenAI
1 parent 56d2363 commit 8b39926

File tree

1 file changed

+51
-7
lines changed

1 file changed

+51
-7
lines changed

src/popup/sections/GeneralPart.jsx

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,62 @@ GeneralPart.propTypes = {
2323
updateConfig: PropTypes.func.isRequired,
2424
}
2525

26+
function formatDate(date) {
27+
const year = date.getFullYear();
28+
const month = (date.getMonth() + 1).toString().padStart(2, '0');
29+
const day = date.getDate().toString().padStart(2, '0');
30+
31+
return `${year}-${month}-${day}`;
32+
}
33+
34+
async function checkBilling(apiKey, apiUrl) {
35+
const now = new Date();
36+
let startDate = new Date(now - 90 * 24 * 60 * 60 * 1000);
37+
const endDate = new Date(now.getTime() + 24 * 60 * 60 * 1000);
38+
const subDate = new Date(now);
39+
subDate.setDate(1)
40+
41+
const urlSubscription = `${apiUrl}/v1/dashboard/billing/subscription`;
42+
let urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`; // 查使用量
43+
const headers = {
44+
"Authorization": "Bearer " + apiKey,
45+
"Content-Type": "application/json"
46+
};
47+
48+
try {
49+
let response = await fetch(urlSubscription, { headers });
50+
if (!response.ok) {
51+
console.log("Your account has been suspended. Please log in to OpenAI to check.");
52+
return;
53+
}
54+
const subscriptionData = await response.json();
55+
const totalAmount = subscriptionData.hard_limit_usd;
56+
57+
if (totalAmount > 20) {
58+
startDate = subDate;
59+
}
60+
61+
urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`;
62+
63+
response = await fetch(urlUsage, { headers });
64+
const usageData = await response.json();
65+
const totalUsage = usageData.total_usage / 100;
66+
const remaining = totalAmount - totalUsage;
67+
68+
return [totalAmount, totalUsage, remaining];
69+
} catch (error) {
70+
console.error(error);
71+
return [null, null, null];
72+
}
73+
}
74+
2675
export function GeneralPart({ config, updateConfig }) {
2776
const { t, i18n } = useTranslation()
2877
const [balance, setBalance] = useState(null)
2978

3079
const getBalance = async () => {
31-
const response = await fetch(`${config.customOpenAiApiUrl}/dashboard/billing/credit_grants`, {
32-
headers: {
33-
'Content-Type': 'application/json',
34-
Authorization: `Bearer ${config.apiKey}`,
35-
},
36-
})
37-
if (response.ok) setBalance((await response.json()).total_available.toFixed(2))
80+
const billing = await checkBilling(config.apiKey, config.customOpenAiApiUrl)
81+
if (billing[2]) setBalance(`${billing[2].toFixed(2)}`)
3882
else openUrl('https://platform.openai.com/account/usage')
3983
}
4084

0 commit comments

Comments
 (0)