php$apikey = 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;$subscription_url = httpsapiopenaicomv1dashboardbillingsubscription;$headers = array Authorization Bearer $apikey Content-Type
array(
"header" => implode("\r\n", $headers),
"method" => "GET"
)
)));
if ($subscription_response === false) {
return $subscription_response;
}
$subscription_data = json_decode($subscription_response, true);
$total = $subscription_data["hard_limit_usd"];
// Get billing data
$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) {
return $billing_response;
}
$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";
}
// Return the results
return "\n总额:\t{$total:.4f}\n" .
"已用:\t{$total_usage:.4f}\n" .
"剩余:\t" . ($total - $total_usage) . "\n" .
"\n{$recent}";
?>
上面的代码已经进行了一些优化,主要包括:
1. 将两个API请求的代码分开,使得逻辑更清晰。
2. 将API请求的结果判断改为严格比较,以确保正确处理请求错误。
3. 修复了返回结果中的换行符问题,使输出更整齐。
4. 将浮点数格式化为小数点后四位。
5. 使用更具描述性的变量名,提高代码可读性。
6. 对代码进行了注释,方便理解和维护
原文地址: https://www.cveoy.top/t/topic/hUNJ 著作权归作者所有。请勿转载和采集!