Skip to content

Commit

Permalink
fix: 使API余额查询可用 @luckywangxi #11
Browse files Browse the repository at this point in the history
  • Loading branch information
Kerwin committed Apr 4, 2023
1 parent c549ef3 commit c982b61
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions service/src/chatgpt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { getCacheConfig, getOriginConfig } from '../storage/config'
import { sendResponse } from '../utils'
import { isNotEmptyString } from '../utils/is'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
import type { BalanceResponse, RequestOptions } from './types'
import type { RequestOptions } from './types'

const { HttpsProxyAgent } = httpsProxyAgent

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

async function fetchBalance() {
// 计算起始日期和结束日期
const now = new Date().getTime()
const startDate = new Date(now - 90 * 24 * 60 * 60 * 1000)
const endDate = new Date(now + 24 * 60 * 60 * 1000)

const config = await getCacheConfig()
const OPENAI_API_KEY = config.apiKey
const OPENAI_API_BASE_URL = config.apiBaseUrl
Expand All @@ -137,36 +141,49 @@ async function fetchBalance() {
? OPENAI_API_BASE_URL
: 'https://api.openai.com'

const [startDate, endDate] = formatDate()

// 每月使用量
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`
// 查是否订阅
const urlSubscription = `${API_BASE_URL}/v1/dashboard/billing/subscription`
// 查普通账单
// const urlBalance = `${API_BASE_URL}/dashboard/billing/credit_grants`
// 查使用量
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`

const headers = {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
}

try {
// 获取API限额
let response = await fetch(urlSubscription, { headers })
if (!response.ok) {
console.error('您的账户已被封禁,请登录OpenAI进行查看。')
return
}
const subscriptionData = await response.json()
const totalAmount = subscriptionData.hard_limit_usd

// 获取已使用量
const useResponse = await fetch(urlUsage, { headers })
const usageData = await useResponse.json() as BalanceResponse
const usage = Math.round(usageData.total_usage) / 100
return Promise.resolve(usage ? `$${usage}` : '-')
response = await fetch(urlUsage, { headers })
const usageData = await response.json()
const totalUsage = usageData.total_usage / 100

// 计算剩余额度
const balance = totalAmount - totalUsage

return Promise.resolve(balance.toFixed(3))
}
catch {
return Promise.resolve('-')
}
}

function formatDate(): string[] {
const today = new Date()
const year = today.getFullYear()
const month = today.getMonth() + 1
const lastDay = new Date(year, month, 0)
const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`
const formattedLastDay = `${year}-${month.toString().padStart(2, '0')}-${lastDay.getDate().toString().padStart(2, '0')}`
return [formattedFirstDay, formattedLastDay]
function formatDate(date) {
const year = date.getFullYear()
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')

return `${year}-${month}-${day}`
}

async function chatConfig() {
Expand Down

0 comments on commit c982b61

Please sign in to comment.