admin管理员组

文章数量:1567821

微信公众号网页鉴权

  记录一下最近做的项目-微信公众号开发。在微信公众号内访问内嵌的第三方网页,需要用到openid或者其他基本信息比如头像等,就不得不进行鉴权操作。
  首先来看下oauth2的处理流程
   1.得到授权码code
    2.根据code获取accesstoken
    3.根据accesstoken获取openId以及其他信息

参照微信公众号网页授权官方文档
https://mp.weixin.qq/wiki?t=resource/res_main&id=mp1421140842
 首先设置一下我们的授权回调域名

点击设置

绑定我们的域名,我这里是gateway的域名,并且下载mp_xx.txt的文件下载下来并且放到我们的web容器的根目录

关于网页授权回调域名的说明
1、在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
2、授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq,配置以后此域名下面的页面http://www.qq/music.html 、 http://www.qq/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq 、 http://music.qq 、 http://qq无法进行OAuth2.0鉴权

配完之后就可以进行码代码啦
一共分为四个步骤
1.用户同意授权、获取code
2.通过code换取网页授权access_token
3.刷新access_token (如果需要)
4.拉取用户信息(scope为snsapi_userinfo)

1.用户同意授权,获取code

请求地址:
https://open.weixin.qq/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参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect : 必传;无论直接打开还是做页面302重定向时候,必须带此参数

响应参数:
 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。
若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限

async getWXUserinfo() {
			// 跳到授权页面,页面回跳并携带code参数
            const url = `https://open.weixin.qq/connect/oauth2/authorize?appid=${this.wx_appid}&redirect_uri=` + encodeURIComponent(this.wx_redirect_uri) + `&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;

            // 如果url中有code这个参数,表明是从微信服务器那里过来的回调页面
            if (window.location.host === process.env.VUE_APP_WX_HOST && !this.GetQueryString("code")) {
                window.location.href = url;
                return;
            }
			// code传到业务后台,业务后台进行获取token和微信用户基本信息等操作
            // 如果是微信返回的地址,就有code,如果缓存中有openid,就不需要在调获取用户信息的接口
            if (!!this.GetQueryString("code") && this.openId === null) {
                const code = this.GetQueryString("code");
                await Http.Get<any>('/oauth2/accessToken', {code: code}, {
                    gateway: GatewayKey.bizs
                }).then(data => {
                    window.sessionStorage.setItem("openId", "" + JSON.stringify(data.openid));
                }).catch((e) => {
                    return;
                });
            }
        }
2.通过code换取网页授权access_token

请求地址:
https://api.weixin.qq/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
请求参数:
appid: 必传;公众号的唯一标识
secret: 必传;公众号的appsecret
code: 必传;填写第一步获取的code参数
grant_type: 必传;填写为authorization_code
响应参数:
access_token: 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
expires_in: access_token接口调用凭证超时时间,单位(秒)
refresh_token: 用户刷新access_token
openid: 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
scope: 用户授权的作用域,使用逗号(,)分隔

错误时微信会返回JSON数据包如下(示例为Code无效错误):
 {“errcode”:40029,“errmsg”:“invalid code”}
后台代码:

public WxUserInfoVO accessToken(String code) throws Exception {
   // 向数据库查询当前微信的公众号配置
    ThirdpartySecretVO thirdpartySecretVO = getThirdSecret();
    if(thirdpartySecretVO== null){
        throw new Exception("微信授权信息不存在");
    }
    // 获取code后,请求以下链接获取access_token:  
   	// https://api.weixin.qq/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    WxAccessTokenVO accessTokenVO = restTemplate.getForObject(wxServer+"/sns/oauth2/access_token?appid={appId}" +
            "&secret={scret}&code={code}&grant_type={grantType}",WxAccessTokenVO.class,thirdpartySecretVO.getAppId(),thirdpartySecretVO.getAppSecret(),code,this.GRANTTYPE);
    if (accessTokenVO.getErrcode() != null){
        LogHelper.monitor(String.format("ErrCode:%s,ErrMsg:%s",accessTokenVO.getErrcode(), accessTokenVO.getErrmsg()));
        throw new Exception(String.format("ErrCode:%s,ErrMsg:%s",accessTokenVO.getErrcode(), accessTokenVO.getErrmsg()));
    }
    return getWxUserInfo(accessTokenVO);
}

3. 刷新access_token (如果需要)

获取第二步的refresh_token后,请求以下链接获取access_token:
https://api.weixin.qq/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
请求参数:
appid: 必传;公众号的唯一标识
grant_type: 必传;填写为refresh_token
refresh_token: 必传;填写通过access_token获取到的refresh_token参数

响应参数:
access_token: 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
expires_in: access_token接口调用凭证超时时间,单位(秒)
refresh_token用户刷新access_token
openid: 用户唯一标识
scope: 用户授权的作用域,使用逗号(,)分隔

错误时微信会返回JSON数据包如下(示例为code无效错误):
 {“errcode”:40029,“errmsg”:“invalid code”}
由于我这边不需要进行刷新token操作 所以就没写后台代码

4. 拉取用户信息

 如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
请求地址:
 https://api.weixin.qq/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

请求参数:
access_token: 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
openid: 用户的唯一标识
lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

响应参数:
 **openid:**用户的唯一标识
nickname: 用户昵称
 **sex:**用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
province: 用户个人资料填写的省份
city: 普通用户个人资料填写的城市
country: 国家,如中国为CN
headimgurl: 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
privilege: 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
unionid: 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。

错误时微信会返回JSON数据包如下(示例为openid无效):
 {“errcode”:40003,“errmsg”:" invalid openid "}

后台代码:

/**
 * 获取微信用户信息
 * @param accessTokenVO
 * @return
 * @throws Exception
 */
public WxUserInfoVO getWxUserInfo(WxAccessTokenVO accessTokenVO) throws Exception {
    WxUserInfoVO wxUserInfoVO= restTemplate.getForObject(wxServer+"/sns/userinfo?access_token={token}&openid={openId}&lang=zh_CN",
            WxUserInfoVO.class,accessTokenVO.getAccess_token(),accessTokenVO.getOpenid(),this.LANG);
    if (wxUserInfoVO.getErrcode() != null){
        LogHelper.monitor(String.format("ErrCode:%s,ErrMsg:%s",wxUserInfoVO.getErrcode(), wxUserInfoVO.getErrmsg()));
        throw new Exception(String.format("ErrCode:%s,ErrMsg:%s",wxUserInfoVO.getErrcode(), wxUserInfoVO.getErrmsg()));
    }
    return wxUserInfoVO;
}

本文标签: 公众网页