@@ -23,18 +23,62 @@ GeneralPart.propTypes = {
23
23
updateConfig : PropTypes . func . isRequired ,
24
24
}
25
25
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
+
26
75
export function GeneralPart ( { config, updateConfig } ) {
27
76
const { t, i18n } = useTranslation ( )
28
77
const [ balance , setBalance ] = useState ( null )
29
78
30
79
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 ) } ` )
38
82
else openUrl ( 'https://platform.openai.com/account/usage' )
39
83
}
40
84
0 commit comments