如何用PHP Curl正确设置请求头调用OAuth API获取Token
用OAuth认证API获取Token的PHP代码问题
问题场景
尝试通过OAuth认证的API获取Token,API文档提供了包含请求头-H和请求参数-d的curl命令,需要适配成PHP代码(请求方式为POST),但自行编写的代码执行后报错。
API文档给出的curl命令
curl -X POST https://api.usa.cloud.com/oauth/token -H 'accept: application/json' -H 'Authorization: Basic dXNlcm5hbWU6N3loVHI1RHNkLWg2YTktODVnZS1nNjc4OTNoNmUwdGQ' -H 'Content-Type: application/x-www-form-urlencoded' -d 'grant_type=client_credentials&scope=api-access'
自行编写的PHP代码
$ch = curl_init('https://myurlapi.com/oauth/token'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'accept: application/json', 'Authorization: Basic ', 'Content-Type: application/x-www-form-urlencoded', 'grant_type=client_credentials&scope=api-access', 'X-Amz-Date:'.$fecha_str, )); $result = curl_exec($ch); curl_close($ch); $data=json_decode($result, true); print_r($data);
执行后返回的错误信息
Array ( [message] => Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization=Basic NWYxQ3YmY2ZZjNl9yd19pZDpAV)
问题分析
代码存在以下明显错误:
- Authorization头不完整:API文档里的
Authorization: Basic后带有完整凭证字符串,你的代码仅写了Authorization: Basic,缺失关键认证凭证 - POST参数放错位置:
grant_type=client_credentials&scope=api-access是POST请求的表单参数,应通过CURLOPT_POSTFIELDS设置,而非放入请求头数组 - 多余请求头:代码添加了API文档未要求的
X-Amz-Date头,可能干扰认证逻辑
修正后的PHP代码
// 替换为正确的API地址 $url = 'https://api.usa.cloud.com/oauth/token'; $ch = curl_init($url); // 设置POST请求 curl_setopt($ch, CURLOPT_POST, true); // 要求返回结果而非直接输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 正确的请求头数组 curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'accept: application/json', // 完整的Authorization头,使用API文档提供的凭证字符串 'Authorization: Basic dXNlcm5hbWU6N3loVHI1RHNkLWg2YTktODVnZS1nNjc4OTNoNmUwdGQ', 'Content-Type: application/x-www-form-urlencoded' )); // 设置POST表单参数 curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials&scope=api-access'); $result = curl_exec($ch); curl_close($ch); $data = json_decode($result, true); print_r($data);
快速解决方案
可以使用在线curl转PHP工具,直接将API文档提供的curl命令转换为正确的PHP代码,避免手动编写时出现参数位置、请求头格式等错误。
内容的提问来源于stack exchange,提问作者Kezman10
相关产品推荐
相关产品推荐

