Skip to main content

微信授权登录

登录思路

1 第一步:用户同意授权,获取code

2 第二步:通过code换取网页授权access_token

3 第三步:刷新access_token(如果需要)

4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

5 附:检验授权凭证(access_token)是否有效

微信扫码授权登录注意项

【微信公众号必须是服务号,订阅号、测试号没有网页扫码登录的功能】

扫码授权登录与正常的点击网址进入后授权登录对于后端来说没有什么本质上的区别,只是在第一步获取用户 code 的时候一个是扫码、一个是网址

微信授权登录 DEMO

前端方式 获取 code

** 展开查看源码 **
<div>
OVIM LOG
</div>


<script type="text/javascript">

var local = 'http://blog.abc.com/api/user/wxLogin'
var appid = 'wxde820ec8da***'
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`

</script>

后端通过 code 获取用户相关信息

http://blog.abc.com/api/user/wxLogin 接口源码

** 展开查看源码 **
<?php
function getUserInfo($code)
{
$appId = 'wxde820ec8da***';
$appSecret = 'dfb92395aa208ef8ae9aa6***';
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appId . '&secret=' . $appSecret . "&code={$code}&grant_type=authorization_code";
$data = file_get_contents($url);
$arr = json_decode($data, true);
$info = [];
if (!empty($arr) && isset($arr['access_token'])) {
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $arr['access_token'] . "&openid=" . $arr['openid'];
$data = file_get_contents($url);
$info = json_decode($data, true);
}

return $info;
}