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

PHP调用Google OAuth接口报unsupported_grant_type错误求助

问题根因

当你给PHP cURL的CURLOPT_POSTFIELDS选项传递数组类型的值时,cURL会自动将请求Content-Type覆盖为multipart/form-data,你手动设置的application/x-www-form-urlencoded会失效,同时参数不会按表单urlencoded格式编码,导致接口无法正确解析参数,因此返回grant_type无效的报错。

解决方案

将参数数组通过http_build_query()处理为URL编码后的字符串,再传递给CURLOPT_POSTFIELDS即可,修正后的代码如下:

$data = [
    "client_id" => "id-here",
    "client_secret" => "secret-here",
    "refresh_token" => "refresh-token-here",
    "grant_type" => "refresh_token"
];
$ch = curl_init( 'https://www.googleapis.com/oauth2/v4/token' );
// 显式声明POST请求,避免不同环境的兼容性问题
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/x-www-form-urlencoded'));
// 数组转为urlencoded格式字符串
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($data) );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

$result = curl_exec($ch);
curl_close($ch);

dd($result);

额外排查点

如果修改后仍有报错,可以检查以下两项:

  • 确认refresh_token未过期,且和传入的client_id、client_secret匹配
  • 确认grant_type字段值没有拼写错误,固定为字符串refresh_token

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 12:51:00