通过微信扫码登录网站
微信开放平台文档地址:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Authorized_Interface_Calling_UnionID.html
步骤:
一、在管理中心中创建应用,填写信息并等待审核完成。
二、获取到app中的 AppID 和AppSecret
三、获取微信登录二维码。
将app的AppID 和 想要跳转回的网址拼接到下面:
https://open.weixin.qq.com/connect/qrconnect?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect
其中redirect_uri要经过url编码urlEncode,然后就可以在网页中打开这个链接,可以看到一个二维码。
使用微信扫描这个二维码,就会跳转回redirect_uri地址,并且后面添加参数https://xx.xxxxxxxxxx.cn/?code=081Oir591OoDfL1I0t291OkB591Oir5F&state=STATE
这里的code用来获取用户信息.
四、获取access_token和openid
可以使用第三步获取到的code来获取这两个参数,这两个参数可以获取微信用户的详细信息
https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code=081Oir591OoDfL1I0t291OkB591Oir5F&grant_type=authorization_code
结果如下:
{
"access_token": “......", //接口调用凭证
"expires_in":7200,
"refresh_token":"......",
"openid":"......", // 授权用户唯一标识
"scope":"snsapi_login",
"unionid":"......"
}
一个code只能使用一次,再次调用结果:
{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: LEMBIfyFe-O2AhuA ]"}
五、获取用户详细信息
如果只是标识用户唯一身份那么到第四步就可以了。再想获取用户信息,比如用户名,头像,可以往下获取:
https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}
{
"openid":"......",
"nickname":"......",
"sex":1,
"language":"zh_CN",
"city":"Changchun",
"province":"Jilin",
"country":"CN",
"headimgurl":"......",
"privilege":[],
"unionid":"......"
}