const html = `
查询OpenAI-API密钥信息
查询API密钥信息
| 账户名称 |
|
| 是否绑卡 |
|
| 已消费额度 |
|
| 剩余额度 |
|
| 账户额度 |
|
| 额度上限 |
|
`
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
if (url.pathname === '/api') {
const apiKey = url.searchParams.get('key')
if (!apiKey) {
return new Response('缺少API密钥', { status: 400 })
}
const queryUrl = 'https://api.openai.com/dashboard/billing/subscription'
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64',
'Authorization': `Bearer ${apiKey}`,
'Accept': '*/*',
'Host': 'api.openai.com',
'Connection': 'keep-alive'
}
try {
const response = await fetch(queryUrl, { headers })
const data = await response.json()
const formatDate = (d) =>
`${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d
.getDate()
.toString()
.padStart(2, '0')}`;
const startDate = formatDate(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1));
const endDate = formatDate(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1));
const usageResponse = await fetch(`https://api.openai.com/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`, { headers })
const usageData = await usageResponse.json()
const used = usageData.total_usage ? Math.round(usageData.total_usage) / 100 : 0
const subscription = data.hard_limit_usd ? Math.round(data.hard_limit_usd * 100) / 100 : 0
data.used = used
data.subscription = subscription
const remaining = subscription - used;
data.remaining = remaining;
return new Response(JSON.stringify(data, null, 2), { status: 200 })
} catch (err) {
if (data.error) {
return new Response(JSON.stringify({ error: '出错了' }), { status: 500 })
}
}
}
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
}