微信授权登录

第一部分:微信授权获取基本信息的介绍

如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。

关于网页授权回调域名的说明

1、在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的开发者中心页配置授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加http://等协议头;
2、授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.htmlhttp://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.comhttp://music.qq.comhttp://qq.com无法进行OAuth2.0鉴权
3、如果公众号登录授权给了第三方开发者来进行管理,则不必做任何设置,由第三方代替公众号实现网页授权即可

关于网页授权的两种scope的区别说明

1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
3、用户管理类接口中的“获取用户基本信息接口”,是在用户和公众号产生消息交互或关注后事件推送后,才能根据用户OpenID来获取用户基本信息。这个接口,包括其他微信接口,都是需要该用户(即openid)关注了公众号后,才能调用成功的。

关于网页授权access_token和普通access_token的区别

1、微信网页授权是通过OAuth2.0机制实现的,在用户授权给公众号后,公众号可以获取到一个网页授权特有的接口调用凭证(网页授权access_token),通过网页授权access_token可以进行授权后接口调用,如获取用户基本信息;
2、其他微信接口,需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。

关于UnionID机制

1、请注意,网页授权获取用户基本信息也遵循UnionID机制。即如果开发者有在多个公众号,或在公众号、移动应用之间统一用户帐号的需求,需要前往微信开放平台(open.weixin.qq.com)绑定公众号后,才可利用UnionID机制来满足上述需求。
2、UnionID机制的作用说明:如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为同一用户,对同一个微信开放平台下的不同应用(移动应用、网站应用和公众帐号),unionid是相同的。

关于特殊场景下的静默授权

1、上面已经提到,对于以snsapi_base为scope的网页授权,就静默授权的,用户无感知;
2、对于已关注公众号的用户,如果用户从公众号的会话或者自定义菜单进入本公众号的网页授权页,即使是scope为snsapi_userinfo,也是静默授权,用户无感知。

 

具体而言,网页授权流程分为四步:

1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

 

 第二部分:实现微信网页授权的详细方法

 

下面,我们来按照这个步骤来实现这个功能:

1、引导用户进入授权页面同意授权,获取code 

2、通过code换取网页授权access_token(与基础支持中的access_token不同) 

3、通过网页授权access_token和openid获取用户基本信息

 

Java实现:

1、引导用户进入授权页面同意授权,获取code 

    这一步其实就是将需要授权的页面url拼接到微信的认证请求接口里面,比如需要用户在访问页面 lovebread.tunnel.qydev.com/auth 时进行授权认证,那么拼接后的授权验证地址为:

    https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx88888888&redirect_uri=http://lovebread.tunnel.qydev.com/auth&response_type=code&scope=snsapi_base&state=xxxx_state#wechat_redirect

    这里面需要替换appid、redirect_uri为实际的信息。其中的scope参数有两个值:

    snsapi_base:只能获取到用户openid。好处是静默认证,无需用户手动点击认证按钮,感觉上像是直接进入网站一样。

    snsapi_userinfo:可以获取到openid、昵称、头像、所在地等信息。需要用户手动点击认证按钮。

 相关代码:

/**
     * 生成用于获取access_token的Code的Url
     * 192.168.1.7:8080/account/auth
     * @return
     */
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public void getRequestCodeUrl(HttpServletResponse response) {
 //此处是一个读取properties的一个工具类,网上一堆!wechat_realm_name是微信公众号的域名,去自己微信公众号里可以找到

        String wechat_realm_name = PropertiesUtil.getValue("wechat_realm_name");
   //此处是一个url编码工具,网上好多,随便找一个就行
        String urlEncodeUTF8 = UrlEncodeUtils.urlEncodeUTF8("http://" + wechat_realm_name + "/account/auth");
   //微信公众的ID
        String APPID = PropertiesUtil.getValue("wechat_id");
        String url = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                APPID, urlEncodeUTF8, "snsapi_userinfo", "xxxx_state");
        try {
  //本人用的是重定向到授权页面
            response.sendRedirect(url);
        }catch (Exception e){
            log.error("重定向异常: {}", e);
        }
    }

2、通过第一步获取的code换取网页授权access_token(与基础支持中的access_token不同) 

    这一步需要在控制器中获取微信回传给我们的code,通过这个code来请求access_token。

/**
     *
     * 获取授权用户信息
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public String auth(@RequestParam("code") String code,HttpServletRequest request) {
        Map<String, String> result = getUserInfoAccessToken(code);//通过这个code获取access_token
        String openId = result.get("openid");
        if (StringUtils.isNotEmpty(openId)) {

            log.info("try getting user info. [openid={}]", openId);
            Map<String, String> userInfo = getUserInfo(result.get("access_token"), openId);//使用access_token获取用户信息
            log.info("received user info. [result={}]", userInfo);
            Account account = accountService.save(userInfo, getRemortIP(request));
            return "profile";
        }
        return null;
    }
/**
     *
     * 获取授权用户信息
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public String auth(@RequestParam("code") String code,HttpServletRequest request) {
        Map<String, String> result = getUserInfoAccessToken(code);//通过这个code获取access_token
        String openId = result.get("openid");
        if (StringUtils.isNotEmpty(openId)) {

            log.info("try getting user info. [openid={}]", openId);
            Map<String, String> userInfo = getUserInfo(result.get("access_token"), openId);//使用access_token获取用户信息
            log.info("received user info. [result={}]", userInfo);
            Account account = accountService.save(userInfo, getRemortIP(request));
            return "profile";
        }
        return null;
    }

/**
     * 获取请求用户信息的access_token
     *
     * @param code
     * @return
     */
    public static Map<String, String> getUserInfoAccessToken(String code) {
        JsonObject object = null;
        Map<String, String> data = new HashMap();
        try {
            String APPID = PropertiesUtil.getValue("wechat_id");
            String APPSECRET = PropertiesUtil.getValue("wechat_secret");
            String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    APPID, APPSECRET, code);
            log.info("request accessToken from url: {}", url);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            object = token_gson.fromJson(tokens, JsonObject.class);
            log.info("request accessToken success. [result={}]", object);
            data.put("openid", object.get("openid").toString().replaceAll("\"", ""));
            data.put("access_token", object.get("access_token").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            log.error("fail to request wechat access token. [error={}]", ex);
        }
        return data;
    }
请求access_token返回样例:
[result={
"access_token":"OezXcEiiBSKSxW0eoylIeK6mXnzDdGmembMkERL1o1PtpJBEFDaCSwseSTzvZhiKK7Q35O-YctaOFfyJYSPMMEsMq62zw8T6VDljgKJY6g-tCMdTr3Yoeaz1noL6gpJeshMPwEXL5Pj3YBkw",
"expires_in":7200,
"refresh_token":"OezXcEiiBSKSxW0eoylIeK6mXnzDdGmembMkERL1o1PtpJBEFDaCSwseSTOIGqz3ySJRe-lv124wxxtrBdXGd3X1YGysFJnCxjtIE-jaMkvT7aN-12nBa4YtDvr5VSKCU-_UeFFnfW0K3JmZGRA",
"openid":"oN9UryuC0Y01aQt0jKxZXbfe658w",
"scope":"snsapi_userinfo"}]
通过access_token和openid获取用户基本信息:

/**
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public static Map<String, String> getUserInfo(String accessToken, String openId) {
        Map<String, String> data = new HashMap();
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        log.info("request user info from url: {}", url);
        JsonObject userInfo = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            userInfo = token_gson.fromJson(response, JsonObject.class);
            log.info("get userinfo success. [result={}]", userInfo);
            data.put("openid", userInfo.get("openid").toString().replaceAll("\"", ""));
            data.put("nickname", userInfo.get("nickname").toString().replaceAll("\"", ""));
            data.put("city", userInfo.get("city").toString().replaceAll("\"", ""));
            data.put("province", userInfo.get("province").toString().replaceAll("\"", ""));
            data.put("country", userInfo.get("country").toString().replaceAll("\"", ""));
            data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            log.error("fail to request wechat user info. [error={}]", ex);
        }
        return data;
    }
获取用户信息返回样例:
[result={
"openid":"oN9UryuC0Y01aQt0jKxZXbfe658w",
"nickname":"lovebread",
"sex":1,
"language":"zh_CN",
"city":"",
"province":"",
"country":"中国",
"headimgurl":"http://wx.qlogo.cn/mmopen/bRLXzTf2f6HNfBTd72heAA7vNKsGKvK3dfreewrewsPff9OaMWib0GibbA8daQmNQvQhagtiaicf4vNC5nYU3ia821QQ/0",
"privilege":[]}]


  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值