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

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;

?>

关键修改说明

  1. 移除json_encode($data),改用http_build_query($data)生成符合application/x-www-form-urlencoded要求的参数格式
  2. 删除手动设置的Content-Length头,curl会自动计算并设置正确长度,避免因长度不匹配引发的异常
  3. 添加CURLOPT_RETURNTRANSFER和CURLOPT_VERBOSE选项,便于调试curl请求的详细过程,快速定位其他潜在问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:37:11