You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP调用Azure GPT-4 API遇权限错误,curl调用正常求排查

问题排查与解决

核心问题分析

对比可正常运行的curl命令和出错的PHP脚本,存在两个关键差异导致错误:

  1. 请求体包含多余字段:PHP脚本中添加了'engine' => 'azureGPT4'参数,但Azure OpenAI的聊天补全接口(基于部署的调用方式)不需要在请求体里指定engine——URL路径中的deployments/azureGPT4已经明确了要使用的模型部署,多余的字段会导致请求格式不符合API规范,进而触发误导性的权限错误提示。
  2. 请求头的键名差异:虽然Azure OpenAI同时支持api-key和Ocp-Apim-Subscription-Key作为API密钥的请求头,但为了和curl命令保持一致,建议统一使用api-key头,避免不必要的兼容问题。

修正后的PHP脚本

$api_url = "https://myazure.openai.azure.com/openai/deployments/azureGPT4/chat/completions?api-version=2023-07-01-preview";
$api_key = "myapikey";

// 移除多余的engine字段,和curl请求体保持一致
$request_data = array(
    'messages' => [
        ["role" => "system", "content" => "You are a helpful assistant."],
        ["role" => "user", "content" => "Hello"]
    ]
);

$request_json = json_encode($request_data);

$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_VERBOSE, true); 
curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'api-key: ' . $api_key, // 和curl保持一致使用api-key头
));

$response = curl_exec($ch);

// 可选:添加curl错误排查逻辑
if(curl_errno($ch)){
    echo 'Curl error: ' . curl_error($ch);
} else {
    print_r($response);
}

curl_close($ch);

验证步骤

  1. 将脚本中的myapikey替换为实际有效的Azure OpenAI API密钥。
  2. 确认URL中的部署名称azureGPT4与Azure门户中创建的部署名称完全匹配。
  3. 执行脚本,检查返回结果是否正常。

内容的提问来源于stack exchange,提问作者haz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 14:32:56