Skip to content

Commit c982b61

Browse files
author
Kerwin
committed
fix: 使API余额查询可用 @luckywangxi #11
1 parent c549ef3 commit c982b61

File tree

1 file changed

+34
-17
lines changed

1 file changed

+34
-17
lines changed

service/src/chatgpt/index.ts

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { getCacheConfig, getOriginConfig } from '../storage/config'
99
import { sendResponse } from '../utils'
1010
import { isNotEmptyString } from '../utils/is'
1111
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
12-
import type { BalanceResponse, RequestOptions } from './types'
12+
import type { RequestOptions } from './types'
1313

1414
const { HttpsProxyAgent } = httpsProxyAgent
1515

@@ -126,6 +126,10 @@ async function chatReplyProcess(options: RequestOptions) {
126126

127127
async function fetchBalance() {
128128
// 计算起始日期和结束日期
129+
const now = new Date().getTime()
130+
const startDate = new Date(now - 90 * 24 * 60 * 60 * 1000)
131+
const endDate = new Date(now + 24 * 60 * 60 * 1000)
132+
129133
const config = await getCacheConfig()
130134
const OPENAI_API_KEY = config.apiKey
131135
const OPENAI_API_BASE_URL = config.apiBaseUrl
@@ -137,36 +141,49 @@ async function fetchBalance() {
137141
? OPENAI_API_BASE_URL
138142
: 'https://api.openai.com'
139143

140-
const [startDate, endDate] = formatDate()
141-
142-
// 每月使用量
143-
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`
144+
// 查是否订阅
145+
const urlSubscription = `${API_BASE_URL}/v1/dashboard/billing/subscription`
146+
// 查普通账单
147+
// const urlBalance = `${API_BASE_URL}/dashboard/billing/credit_grants`
148+
// 查使用量
149+
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`
144150

145151
const headers = {
146152
'Authorization': `Bearer ${OPENAI_API_KEY}`,
147153
'Content-Type': 'application/json',
148154
}
149155

150156
try {
157+
// 获取API限额
158+
let response = await fetch(urlSubscription, { headers })
159+
if (!response.ok) {
160+
console.error('您的账户已被封禁,请登录OpenAI进行查看。')
161+
return
162+
}
163+
const subscriptionData = await response.json()
164+
const totalAmount = subscriptionData.hard_limit_usd
165+
151166
// 获取已使用量
152-
const useResponse = await fetch(urlUsage, { headers })
153-
const usageData = await useResponse.json() as BalanceResponse
154-
const usage = Math.round(usageData.total_usage) / 100
155-
return Promise.resolve(usage ? `$${usage}` : '-')
167+
response = await fetch(urlUsage, { headers })
168+
const usageData = await response.json()
169+
const totalUsage = usageData.total_usage / 100
170+
171+
// 计算剩余额度
172+
const balance = totalAmount - totalUsage
173+
174+
return Promise.resolve(balance.toFixed(3))
156175
}
157176
catch {
158177
return Promise.resolve('-')
159178
}
160179
}
161180

162-
function formatDate(): string[] {
163-
const today = new Date()
164-
const year = today.getFullYear()
165-
const month = today.getMonth() + 1
166-
const lastDay = new Date(year, month, 0)
167-
const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`
168-
const formattedLastDay = `${year}-${month.toString().padStart(2, '0')}-${lastDay.getDate().toString().padStart(2, '0')}`
169-
return [formattedFirstDay, formattedLastDay]
181+
function formatDate(date) {
182+
const year = date.getFullYear()
183+
const month = (date.getMonth() + 1).toString().padStart(2, '0')
184+
const day = date.getDate().toString().padStart(2, '0')
185+
186+
return `${year}-${month}-${day}`
170187
}
171188

172189
async function chatConfig() {

0 commit comments

Comments
 (0)