我的小程序之旅六:微信公众号授权登录(适用于H5小程序)
实现步骤
2 第二步:通过code换取网页授权access_token
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
参考文档
准备材料
一个服务号(已认证),确保网页授权权限已开通
1、点击修改,跳转到公众号设置页,此处需要添加一个域名文件校验
2、通过authorize获取的code
调用https://open.weixin.qq.com/connect/oauth2/authorize
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Document</title> </head> <style> </style> <body> <div id="container"> </div> <script> window.appId = `${appId}`
//注意:此处redirect_uri需要使用encodeURIComponent(该方法浏览器自带)转义 let local = "http://xxx" // 跳转到授权页面 window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + window.appId + "&redirect_uri=" + encodeURIComponent(local) + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; </script> </body> </html>
参数说明:
snsapi_base与snsapi_userinfo属于微信网页授权获取用户信息的两种作用域
snsapi_base只能获取access_token和openID
snsapi_userinfo可以获取更详细的用户资料,比如头像、昵称、性别等,该种形式会唤醒授权页面
3、调用https://api.weixin.qq.com/sns/oauth2/access_token,获取access_token
返回值如下
{"access_token":"accesstoken","refresh_token":"refreshtoken","openid":"openId","scope":"snsapi_userinfo","expires_in":7200}
常见错误码发生情况
{"errcode":40029,"errmsg":"invalid code, rid: 620e3db2-410d5515-117f31ac"}
这种问题一般都发生在code上,要检查code是不是有值并且是不是重复调用了
4、根据accessToken和openId查询用户信息,调用https://api.weixin.qq.com/sns/userinfo?access_token=accessToken&openid=openIdlang=zh_CN
返回值如下
{"country":"","province":"","city":"","openid":"openid","sex":0,"nickname":"sum墨","headimgurl":"https://thirdwx.qlogo.cn/mmopen/vi_32/KqPuMLU8JmRIlicUSvia4PR0vNKWKLFmfR6icibJ2Us7EyZXbZaKBd30qjGYJJSkmdHoib66wiaicQia61R34xC7Jr8EJg/132","language":"","privilege":[]}
本文来自博客园,作者:sum墨,转载请注明原文链接:https://www.cnblogs.com/wlovet/p/15894097.html