UnionID
同一用户、同一微信平台下的不同应用unionid相同
静默授权
1. snsapi_base为scope的网页授权
2. 已进入本公众号的网页授权页snsapi_userinfo
网页授权4步:
1. 用户同意授权,获取code
2. 通过code换取网页授权access_token
3. 刷新access_token(如有需要)
4. scope为snsapi_userinfo时拉取用户信息
第一步,引导用户打开认证的页面
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
appid 公众号的唯一标识
redirect_uri 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
response_type 返回类型,即code
scope 应用授权作用域,
snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
state 重定向后会带上state参数(非必须)
wechat_redirect 无论直接打开还是做页面302重定向时候,必须带此参数
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE(5分钟未被使用自动过期)
secret 公众号的appsecret
grant_type 即authorization_code
第二步,通过code换取网页授权access_token
如果scope为snsapi_token,获取access_token同时获取openid。
获取code后,请求以下链接获取access_token:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
返回数据:
{
“access_token”:“ACCESS_TOKEN”, // 网页授权接口调用凭证
“expires_in”:7200,
“refresh_token”:“REFRESH_TOKEN”, // 用户刷新access_token
“openid”:“OPENID”,
“scope”:“SCOPE”
}
第三步:刷新access_token(如果需要)
获取第二步的refresh_token后,请求以下链接获取access_token:
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
第四步:拉取用户信息(需scope为 snsapi_userinfo)
如果scope为 snsapi_userinfo,通过access_token和openid拉取用户信息
http:GET(请使用https协议)
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
返回数据:
{
“openid”:" OPENID",
“nickname”: NICKNAME,
“sex”:“1”,
“province”:“PROVINCE”,
“city”:“CITY”,
“country”:“COUNTRY”,
“headimgurl”: “http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46”,
“privilege”:[ “PRIVILEGE1” “PRIVILEGE2” ],
“unionid”: “o6_bmasdasdsad6_2sgVt7hMZOPfL”}
检验授权凭证(access_token)是否有效
http:GET(请使用https协议)
https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
相关链接:
1 微信网页开发-网页授权
部分封装方法如下:
const (
redirectOauthURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"
webAppRedirectOauthURL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"
webAccessTokenURL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"
refreshAccessTokenURL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"
userInfoURL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"
checkAccessTokenURL = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s"
accessTokenURL