官方文档:
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
注意事项:回调地址是 顶级域名,前不带http,后不带地址;eg:www.baidu.com
直接上代码:
第一步:生成二维码
$redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].'/store/getToken';
$redirect_uri = urlencode($redirect_uri); //该回调需要url编码
$appID = Config::get('custom.wxAppId');
//准备向微信发请求
$url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_login&state=dsjhwx#wechat_redirect";
header("Location:" . $url);
第二步:在回调地址中处理数据
//参数
$appid = Config::get('custom.wxAppId');
$secret = Config::get('custom.wxAppKey');
if (empty($code)){
return $this->format('0', "扫码登录失败", null);
}
//通过code获得 access_token + openid
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$jsonResult =$this->https_request($url);
$resultArray = json_decode($jsonResult, true);
$access_token = $resultArray["access_token"];
$openid = $resultArray["openid"];
dump($openid);
dump($data);
//第三步 获取用户信息
//通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里
$infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid.'&lang=zh_CN';
$infoResult = $this->https_request($infoUrl);
$infoArray = json_decode($infoResult, true);
//这里是用户信息
if($infoArray['unionid'])
{
//这里写业务逻辑
dump($infoArray);
die;
}
die;
打印出来的数据如下: