Laravel调用Instagram Basic Display API获取长效access_token返回null
问题原因与修复方案
你的代码有3个直接导致返回null的核心错误,逐一修复即可:
- 接口请求方法错误:
/oauth/access_token接口仅接受POST form格式传参,不支持GET方式把参数拼在URL后传递,Postman默认使用POST请求所以能正常返回,你的代码未指定请求方法,默认发GET,接口无法识别参数直接返回异常 - cURL配置错误:你开启了
CURLOPT_HEADER = 1,该配置会将HTTP响应头和响应体拼接后返回,带响应头的字符串不符合JSON格式,json_decode解析失败直接返回null - 接口与参数不匹配:你当前调用的是「授权码换短效access_token」的接口,并非「短效token换长效token」的接口,且参数中传的是
access_token,该接口要求传用户授权后拿到的code(短效授权码)- 授权码换短效token接口:
https://api.instagram.com/oauth/access_token(POST传参) - 短效token换长效token接口:
https://graph.instagram.com/access_token(GET传参,grant_type固定为ig_exchange_token)
- 授权码换短效token接口:
修复后可直接运行的代码
$client_secret = "###############"; $client_id = "###############"; $redirect_uri = '#########'; $auth_code = "####"; // 用户授权完成后回调带回的authorization_code,不是短效access_token // 第一步:用授权码兑换短效access_token $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.instagram.com/oauth/access_token'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, [ 'client_id' => $client_id, 'client_secret' => $client_secret, 'grant_type' => 'authorization_code', 'redirect_uri' => $redirect_uri, 'code' => $auth_code ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 关闭响应头输出,仅返回响应体内容 curl_setopt($ch, CURLOPT_HEADER, 0); // 本地开发无CA证书时可临时开启,生产环境建议删除该行保留SSL校验 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $shortTokenRes = json_decode(curl_exec($ch), true); curl_close($ch); if (!isset($shortTokenRes['access_token'])) { // 可在此处打印$shortTokenRes排查短效token兑换错误 return null; } $shortAccessToken = $shortTokenRes['access_token']; // 第二步:用短效access_token兑换长效access_token $ch2 = curl_init(); $longTokenUrl = 'https://graph.instagram.com/access_token?' . http_build_query([ 'grant_type' => 'ig_exchange_token', 'client_secret' => $client_secret, 'access_token' => $shortAccessToken ]); curl_setopt($ch2, CURLOPT_URL, $longTokenUrl); curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch2, CURLOPT_HEADER, 0); curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false); $longTokenRes = json_decode(curl_exec($ch2), true); curl_close($ch2); return $longTokenRes;
后续排查方向
如果修复后仍无法拿到正确结果,按顺序排查:
- 先打印
curl_exec($ch)返回的原始字符串,不要直接做json_decode,同时用curl_error($ch)获取curl层面的错误(比如SSL连接失败、超时、重定向异常),先确认是接口返回了错误内容,还是curl本身执行失败 - 确认代码中使用的
redirect_uri和Instagram开发者后台配置的完全一致,协议(http/https)、末尾斜杠、路径任何一处不匹配都会被接口拦截 - 短效授权码有效期仅1小时,且只能使用一次,确认你传入的code未过期、未被重复使用
- 不要混淆
authorization_code和short_access_token,前者是用户授权跳转后带回的参数,仅用于兑换短效token,后者是兑换接口返回的凭证,用于兑换长效token和拉取feed
内容的提问来源于stack exchange,提问作者Priyanka
相关产品推荐
相关产品推荐

