解决小程序获取openid报错errcode:48001或者其他错误代码方案
原因解析
获取openID,调用的时候发现总是报错尤其是
errcode: 48001, errmsg: "api unauthorized错误,
首先可以肯定和api没有授权的没有多大关系,
微信调用获取openID的url有以下三种
1、$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
2、$url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
3、$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
解决方案
公众号appid获取微信openid
//公众号appid获取微信openid
public static function getOpenidData($wechat_info, $code)
{
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
$weixin_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
$weixin_url_new = $weixin_url . '?appid=' . $wechat_info['appKey'] . '&secret=' . $wechat_info['appSecret'] . '&code=' . $code . '&grant_type=authorization_code';
$weixin_data = file_get_contents($weixin_url_new);
$result = json_decode($weixin_data, true);
return $result;
}
小程序appid获取微信openid
//获取微信信息,session_key 和 openid
public static function getweixindata($appid, $secret, $js_code)
{
$weixin_url = "https://api.weixin.qq.com/sns/jscode2session";
//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
$weixin_url_new = $weixin_url . "?appid=$appid&secret=$secret&js_code=$js_code&grant_type=authorization_code";
$weixin_data = file_get_contents($weixin_url_new);
$result = json_decode($weixin_data, true);
return $result;
}