- ❌ 2023-07-26 该方法已经失效,
 subscription、usage接口已无法使用,在线查吧。- ❌ 2023-07-21 该方法已经失效,
 subscription接口还能使用(只能查询到apiKey所对应的总额度),但usage接口已无法使用,查不到使用量了。登录账号去官网页面在线查询吧,或者去提取一个sessionKey进行查询,但就没必要了。
前言
使用 apiKey 查询 OpenAI 余额的方法,官方 API 接口使用文档其实并没有介绍关于余额查询的方法,都是网友们自己探索出来的(当然也是 OpenAI 开发了这个接口,只是没有对外公开说明)。在之前,向 credit_grants 接口构建一个 HTTP 请求,就可以得到该 apiKey 所对应账户的余额相关信息,但是现在官方取消了该接口使用,只能使用浏览器登录账号在相关页面进行查询。
以前的办法
import requests
url = 'https://api.openai.com/dashboard/billing/credit_grants'
api_key = "Your_apiKey"
headers = {
    "Authorization": "Bearer " + api_key,
    "Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
print(response.text)
简单来说就是构造一个请求,请求头带着自己的 apiKey  就可以返回余额相关信息,具体返回的信息包括总额度、已使用额度、可用额度。但是现在使用(2023-04-20,至少今天开始不行了),会返回下面的信息:
{
  "error": {
    "message": "Your request to GET /dashboard/billing/credit_grants must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: secret.",
    "type": "server_error",
    "param": null,
    "code": null
  }
}
大概意思就是 OpenAI 对于之前查询余额的接口:credit_grants 进行了限制,只能使用浏览器 token 访问,如果使用 apiKey 则不行,也就是还是只能通过访问此页面进行余额的查询。
现在的办法
/dashboard/billing/credit_grants  被限制,但是 /dashboard/billing/ 下的其他接口还可以使用,具体来说是使用 subscription 和 usage 接口,分别获取总额度 hard_limit_usd 和使用量 total_usage ,然后进行作差进而求出余额。
但是值得注意的是:
/dashboard/billing/subscription构建的请求只能查询到总订阅额度(免费的总额度),准确来说该接口查询到的信息顾名思义是订阅 ChatGPT 相关服务的信息,包括是否为付费用户、总额度、订阅日期等等。所以如果还要知道可用额度还需要借助usage接口来实现;- 如果查询某个过期的账号,也能显示余额,因为 OpenAI 并没有将过期账号的余额进行清零,而是在
/dashboard/billing/subscription接口下使用access_until值来表示该免费账号的有效期限; /dashboard/billing/usage构建的请求需要传达两个参数:start_date和end_date,返回的结果除了有在这段时间内所使用的总额度total_usage,还有start_date和end_date的这段时间里,每一天使用的额度(具体到每一天某时刻使用的额度),此外下面代码中的total_usage / 100的原因是计算单位为美分,这里转换成美元。(“这段时间” 范围不能超过 100 天,否则会报错 " You can only request a maximum of 100 days per request " );- 当然,所有的请求需要你的网络环境能够正常访问 OpenAI 的 api 地址,否则也是会查询不到。
 
使用下面的代码,并在提示处替换自己的 apiKey 即可查询到余额以及账户的免费额度有效期限:
import datetime
import requests
def get_usage(api_key):
    headers = {
        # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
        "Authorization": "Bearer " + api_key,
        "Content-Type": "application/json"
    }
    
    # Get subscription info and total hard limit
    resp_sub = requests.get("https://api.openai.com/v1/dashboard/billing/subscription", headers=headers)
    if not resp_sub.ok:
        return resp_sub.text
    sub_data = resp_sub.json()
    total = sub_data.get("hard_limit_usd")
    now_time = datetime.datetime.now().timestamp()
    access_time = sub_data.get("access_until")
    if access_time > now_time:
        print("\n该账户可用 ✔,有效期至:", datetime.datetime.fromtimestamp(access_time).date())
    else:
        print("\n该账户已过期,不可用 ❌")
    # print(access_time)
    # Get recent usage info
    start_date = (datetime.datetime.now() - datetime.timedelta(days=99)).strftime("%Y-%m-%d")
    end_date = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    resp_billing = requests.get(f"https://api.openai.com/v1/dashboard/billing/usage?start_date={start_date}&end_date={end_date}", headers=headers)
    if not resp_billing.ok:
        return resp_billing.text
    
    billing_data = resp_billing.json()
    total_usage = billing_data.get("total_usage") / 100
    print(f"\n总额度:{total:.4f} $ \n已使用额度:{total_usage:.4f} $ \n剩余额度:{total-total_usage:.4f} $ \n")
                
if __name__ == '__main__':
    apiKey = "Your_apiKey" # 填写 apiKey
    get_usage(apiKey)
效果

不太推荐网上一些搭建好的可自助查询余额的网页,有可能会泄露自己的 apiKey 。