调用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参数。修复步骤:
- 使用
http_build_query()函数将数组转换为URL编码的表单字符串:$vars = array( "grant_type" => "authorization_code", "code" => $_GET["code"], "redirect_uri" => REDURL ); $postFields = http_build_query($vars); // 转换为URL编码格式 - 修改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
相关产品推荐
相关产品推荐

