微信第三方授权

   第三方登陆,可能大家刚看到这个词的时候就是 一脸懵,什么东西

其实,道理很简单.

首先,你要明白一个流程,

first,生成一个你想让用户同意授权的链接,并且通过这个链接能返回到用户同意后,你想处理数据的位置

second,你要明白不是谁点这个链接都有用,你是微信第三方授权,你需要微信用户点击链接才有用

third,用户同意之后,会返回code这个String

now,代码

pom依赖与我的微信公众号开发一样

生成链接

 @RequestMapping("/aut")
    public void authorize() {
        //设置回调地址
        WechatMpConfig w = new WechatMpConfig();
        WxMpService wxMpService = w.wxMpService();//配置wxMpService,不会的去我别的文章看一下
        String url = "http://2078e56f.ngrok.io/userInfo";//用户同意授权后,微信服务器返回用户信息的路径
    String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
        System.out.println("生成的授权链接:"+redirectUrl);
    }

生成的的链接大概是酱的:

https://open.weixin.qq.com/connect/oauth2/authorizeappid=wx950a3634b529f157&redirect_uri=http%3A%2F%2F2078e56f.ngrok.io%2Fwechat%2FuserInfo&response_type=code&scope=snsapi_userinfo&state=&connect_redirect=1#wechat_redirect

用下面的代码来接收并处理code

 @RequestMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code) {
        String result = "";
        WechatMpConfig w = new WechatMpConfig();
        WxMpService wxMpService = w.wxMpService();
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            boolean b = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
            String name = wxMpUser.getNickname();
            System.out.println(wxMpUser.getCity()+"--"+wxMpUser.getHeadImgUrl()+"--"+wxMpUser.getCountry());
            System.out.println(name);
            System.out.println(b);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return result;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值