微信授权登录实现

微信授权登录。和其它授权类似,需要去官方渠道注册开发者账号,微信授权登录需要到微信公众平台申请.

假设获取到了公众平台appid。

和扫码类似,进入微信指定的一个链接。

但是授权登录是先直接访问微信指定的页面。(扫码是从自己页面跳转到指定微信链接,再回调自己页面。授权是直接从指定的链接地址跳转回自己指定页面

先上代码:

var param=location.href.split("?")[1];
//wechat
var url=encodeURIComponent("http://h5.laikanxing.com/h5-crowd/html/wechat.html?"+param);
    window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxadc302736fea5abf&redirect_uri="+
        url+"&response_type=code&scope=snsapi_userinfo&"+param+"#wechat_redirect";

param:需要带回的参数。

url:回调页面。(公众平台注册的域

以上步骤可以从前台跳转,可以从后端进行转发。看个人业务需求。

当用户确认授权登录以后,微信从定向到指定回调页面,并且url后拼接了换取用户信息的code。

拿到code以后,和网页扫码登录一样,进行几步交换(必须后台进行)。

后台Java代码:

/**
     * activity
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/get/h5/wechat/{code}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public LoginResultJSON getWechatUserInfo(@PathVariable("code") String code) {
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxadc302736fea5abcf&secret=11241d710a5726a57e6ebd2dfd98b0bf&code="+code+"&grant_type=authorization_code";
        String result=RequestUtil.get(url);
        JSONObject jsonObject=new JSONObject(result);
        String access_token=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");
        url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
        result=RequestUtil.get(url);
        jsonObject=new JSONObject(result);
        ThirdPartyUserLoginInfoJSON json=new ThirdPartyUserLoginInfoJSON();
        json.setDeviceId(null);
        json.setDeviceSystem(null);
        json.setHeadUrl(jsonObject.getString("headimgurl"));
        json.setNickname(jsonObject.getString("nickname"));
        json.setSourceType(2);
        json.setUniqId(jsonObject.getString("openid"));
        return userService.thirdPartyLogin(json);
    }

具体换取解释,请看上篇。第三方登录集合

posted @ 2016-10-11 23:00  黑衣帽子  阅读(5871)  评论(6编辑  收藏  举报