个人总结最新的通过各类型微信公众号获取微信用户基本资料的方法出炉
/** * 1.获取code跳转:状态,跳转地址,服务号还是订阅号【服务号1,订阅号0】 * @author:http://www.5atl.com */ function wx_get_code($state, $redirecturl, $fuwuhao = 1) { $param['appid'] = config('wxauth')['appid']; // AppID $param['redirect_uri'] = $redirecturl; // 获取code后的跳转地址 $param['response_type'] = 'code'; // 不用修改 if ($fuwuhao === 1) { $param['scope'] = 'snsapi_userinfo'; // 不用修改 } else { $param['scope'] = 'snsapi_base'; // 不用修改 } $param['state'] = $state; // 可在行定义该参数 $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query($param) . '#wechat_redirect'; return $url; } /** * 2.获取网页授权access_token,此access_token非普通的access_token,详情请看微信公众号开发者文档 * @author:http://www.5atl.com */ function wx_get_access_token() { $param['appid'] = config('wxauth')['appid']; // AppID $param['secret'] = config('wxauth')['secret']; // AppSecret $param['code'] = $_GET['code']; $param['grant_type'] = 'authorization_code'; $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query($param); $token = file_get_contents($url); $token = json_decode($token, true); if (! empty($token['errmsg'])) { return false; } // 1. token是否过期 // $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $token['access_token'] . '&openid=' . $token['openid']; // $reback = file_get_contents($url); // $json = json_decode($reback, true); // 2. token过期后重新拿刷新,跟步骤1一样的结果 // if (array_key_exists('errcode', $json) && $json['errcode'] == 40001) { // $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $param['appid'] . '&grant_type=refresh_token&refresh_token=' . $token['reflash']; // $reback = file_get_contents($url); // $content = json_decode($reback, true); // } return $token; } /** * 3. * 服务号通过授权获取用户信息, $content 是数组类型 * @author:http://www.5atl.com */ function wx_get_userinfo($token) { $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $token['access_token'] . '&openid=' . $token['openid'] . '&lang=zh_CN'; $user = file_get_contents($url); $user = json_decode($user, true); return $user; } /** * 3. * 订阅号通过授权获得用户的openid * @author:http://www.5atl.com */ function wx_get_useropenid() { $appid = config('wxauth')['appid']; // AppID $secret = config('wxauth')['secret']; // AppSecret $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $_GET['code'] . '&grant_type=authorization_code'; $json = file_get_contents($url); return $json; }
个人总结最新的通过各类型微信公众号获取微信用户基本资料的方法出炉,测试都通过了。