Salesforce OAuth API调用出现unsupported grant type错误求助
问题解决:Salesforce OAuth API "unsupported grant type" 错误
问题根源
你的代码存在Content-Type与POST数据格式不匹配的核心问题:
- 你设置了
Content-Type: application/x-www-form-urlencoded,但实际发送的是JSON格式字符串(通过json_encode($data)生成) - Salesforce的OAuth Token接口在接收
application/x-www-form-urlencoded类型请求时,无法解析JSON格式的参数,因此返回unsupported_grant_type错误 - Postman能正常工作,是因为它选择
x-www-form-urlencoded格式时,会自动将参数转换为key=value&key2=value2的标准格式,而非JSON
修正后的代码
<?php $url = 'https://mycompanynamegoeshere.my.salesforce.com/services/oauth2/token'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); $data = [ 'grant_type' => 'client_credentials', 'client_id' => 'client id goes here', 'client_secret' => 'client secret goes here', ]; // 生成符合x-www-form-urlencoded格式的参数字符串 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded', 'Cache-Control: no-cache', 'Connection: keep-alive', 'Accept: application/json', ), ); // 开启调试选项,方便排查潜在问题 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_VERBOSE, true); $response = curl_exec($ch); if(curl_errno($ch)){ echo 'Curl error: ' . curl_error($ch); } curl_close($ch); echo $response; ?>
关键修改说明
- 移除
json_encode($data),改用http_build_query($data)生成符合application/x-www-form-urlencoded要求的参数格式 - 删除手动设置的
Content-Length头,curl会自动计算并设置正确长度,避免因长度不匹配引发的异常 - 添加
CURLOPT_RETURNTRANSFER和CURLOPT_VERBOSE选项,便于调试curl请求的详细过程,快速定位其他潜在问题
内容的提问来源于stack exchange,提问作者Jay Simple2Call
相关产品推荐
相关产品推荐

