Skip to content
This repository has been archived by the owner on Feb 10, 2025. It is now read-only.

fix: 使API余额查询可用 #1152

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 49 additions & 8 deletions service/src/chatgpt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,27 +124,68 @@ async function chatReplyProcess(options: RequestOptions) {
}

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

if (!isNotEmptyString(OPENAI_API_KEY))
return Promise.resolve('-')
const config = await getCacheConfig();
const OPENAI_API_KEY = config.apiKey;
const OPENAI_API_BASE_URL = config.apiBaseUrl;

if (!isNotEmptyString(OPENAI_API_KEY)) {
return Promise.resolve('-');
}

const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
? OPENAI_API_BASE_URL
: 'https://api.openai.com'

// 设置API请求URL和请求头
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 {
const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` }
const response = await axios.get(`${API_BASE_URL}/dashboard/billing/credit_grants`, { headers })
const balance = response.data.total_available ?? 0
// 获取API限额
let response = await fetch(urlSubscription, {headers});
if (!response.ok) {
console.log("您的账户已被封禁,请登录OpenAI进行查看。");
return;
}
const subscriptionData = await response.json();
const totalAmount = subscriptionData.hard_limit_usd;

// 获取已使用量
response = await fetch(urlUsage, {headers});
const usageData = await response.json();
const totalUsage = usageData.total_usage / 100;

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

// 输出余额信息
console.log(`balance: ${balance.toFixed(3)}`);

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

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() {
const balance = await fetchBalance()
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
Expand Down