OpenAI API 账单使用情况查询 - 获取并显示近期的使用情况和剩余额度
\u003c?php $apikey = ""; $subscription_url = "https://api.openai.com/v1/dashboard/billing/subscription"; $headers = array( "Authorization: Bearer " . $apikey, "Content-Type: application/json" ); $subscription_response = file_get_contents($subscription_url, false, stream_context_create(array( "http" => array( "header" => implode("\r\n", $headers), "method" => "GET" ) ))); if ($subscription_response !== false) { $subscription_data = json_decode($subscription_response, true); $total = $subscription_data["hard_limit_usd"]; } else { return $subscription_response; }
$start_date = date("Y-m-d", strtotime("-99 days")); $end_date = date("Y-m-d", strtotime("+1 day")); $billing_url = "https://api.openai.com/v1/dashboard/billing/usage?start_date=" . $start_date . "&end_date=" . $end_date . ""; $billing_response = file_get_contents($billing_url, false, stream_context_create(array( "http" => array( "header" => implode("\r\n", $headers), "method" => "GET" ) ))); if ($billing_response !== false) { $billing_data = json_decode($billing_response, true); $total_usage = $billing_data["total_usage"] / 100; $daily_costs = $billing_data["daily_costs"]; $days = min(5, count($daily_costs)); $recent = "最近" . $days . "天使用情况 \n"; for ($i = 0; $i < $days; $i++) { $cur = $daily_costs[count($daily_costs) - $i - 1]; $date = date("Y-m-d", $cur["timestamp"]); $line_items = $cur["line_items"]; $cost = 0; foreach ($line_items as $item) { $cost += $item["cost"]; } $recent .= "\t" . $date . "\t" . ($cost / 100) . " \n"; } } else { return $billing_response; }
return "\n总额:\t" . $total . ":4f \n" . "已用:\t" . $total_usage . ":4f \n" . "剩余:\t" . ($total - $total_usage) . " \n" . "\n" . $recent; ?>
原文地址: https://www.cveoy.top/t/topic/pDTT 著作权归作者所有。请勿转载和采集!