一、微信OAuth2.0机制网页授权登录,获取用户基本信息。主要有以下简略步骤:
第一步:用户同意授权,获取code
第二步:通过code换取网页授权access_token
第三步:拉取用户信息(需scope为 snsapi_userinfo)
二、关于Scope 权限的两种
snsapi_base 默认允许授权,无须用户同意
snsapi_userinfo 进入授权页需要用户同意才可进入
三、需要注意的点
设置IP白名单
检查当前公众号是否为服务号
回调地址填写是否正确
回调地址需要url编码 如 https:// 为 http%3A%2F%2F
四.前台
第一步: 请求下方地址,拿到服务器回调的Code
请求地址: 微信公众平台APPID,回调地址与scope类型
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${回调地址}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
1
授权后会获得codehttps://***.cn/?code=***********&state=123#/
五、后台
获取access_token
获取用户基本信息(头像、昵称)
```
$code = $input_data['code']??''; //前台获得的code值:061Wxn0w3uLaXV20ep3w3Qm1nA0Wxn0w
$access_token = WechatWeb::accessToken(); //可获得access_token :42_bb9agZJzvR3jFHIFa4BmfMUWPdH2uagt0F3l4T9jZigTVm8GP_zkvLAxc0yHV79nY85OrdCmmiEARajoLlm3sVkDLPH-aRaRsWcrWcK8W5dtk6G5Jnf9YDnkRchIHY90f9nHbBvCdIqbL_YDRPBbACALJV
//获取access_token的域名: 'https://api.weixin.qq.com/cgi-bin/token?appid={$app_id}&secret={$app_secret}&grant_type=client_credential';
if(empty($access_token)) throw new \Exception('第三方登录方式异常:access_token',0);
$openid = WechatWeb::getOpenid($code); //可通过code获取 获取用户基本信息的access_token和openid
/* 域名: "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$Code}&grant_type=authorization_code";
^ array:5 [
"access_token" => "42_5d_j3Tk5s8LF0rArXu-9CLI8t3LV1o8kGFCq9qo_fU4OyZd7bULGTaKU2VBHWIxsfbjqHS78N7fbgXFh9d2GdQ"
"expires_in" => 7200
"refresh_token" => "42_aahPTh5Dn0lc2De5BoPPlXtovXRX7eoO0gT6EfyQcGaq-vT_iOo4TOll-qpnbeGi_ftI2dpE0FRt262yR-M3FA"
"openid" => "oW2tQ6F2Wnxzp4rJiok5NTFX9c0Y"
"scope" => "snsapi_userinfo"
]
* */
if(empty($openid['openid'])) throw new \Exception('第三方登录方式异常:openid',0);
$auth_info = WechatWeb::actToUserInfo($openid['access_token'],$openid['openid']);
/*
获得的$auth_info 用户信息域名:'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid;
此处的$access_token为网页授权$access_token非普通授权$access_token
^ array:9 [
"openid" => "oW2tQ6F2Wnxzp4rJiok5NTFX9c0Y"
"sex" => 0
"language" => "zh_CN"
"city" => ""
"province" => ""
"country" => ""
"headimgurl" => "https://thirdwx.qlogo.cn/mmopen/vi_32/rAjztjufSYsbZnicA9VxQiao3DvUUMaJlbU0sWvmGq2icxia61zJJ8aTSzFibiaDSRaV53dgXZlsvVRlW2iaIYrJQUG4w/132"
"privilege" => []
]
* */
empty($php_input['name']) && $update_data['name'] = $auth_info['nickname'];
```
深圳 · 龙岗 · 大运软件小镇22栋201
电话:400 182 8580
邮箱:szhulian@qq.com