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

调用Pinterest API获取access_token时提示'grant_type'为必填项

问题排查:Pinterest API获取access_token提示'grant_type' is a required property
  • 核心问题:直接将PHP数组传给CURLOPT_POSTFIELDS,但请求头指定Content-Type: application/x-www-form-urlencoded时,curl不会自动将数组编码为符合要求的表单格式,导致服务端无法识别grant_type参数。

  • 修复步骤:

    1. 使用http_build_query()函数将数组转换为URL编码的表单字符串:
      $vars = array(            
          "grant_type" => "authorization_code",
          "code" => $_GET["code"],
          "redirect_uri" => REDURL
      );
      $postFields = http_build_query($vars); // 转换为URL编码格式
      
    2. 修改curl的POSTFIELDS参数,传入编码后的字符串:
      curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
      
  • 完整修复后的代码:

$vars = array(            
    "grant_type" => "authorization_code",
    "code" => $_GET["code"],
    "redirect_uri" => REDURL
);
$postFields = http_build_query($vars);

$headers = [
    'Authorization: Basic '.base64_encode("APPID:SECRET"),
    'Content-Type: application/x-www-form-urlencoded'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.pinterest.com/v5/oauth/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

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

print  $result;
  • 补充说明:当给CURLOPT_POSTFIELDS传递数组时,curl会自动将请求头的Content-Type改为multipart/form-data,但Pinterest的token接口仅接受application/x-www-form-urlencoded格式的参数,因此必须手动将数组编码为URL字符串。

内容的提问来源于stack exchange,提问作者m.qayyum

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:00:53