微信开放平台开发第三方授权登陆(四):微信公众号

 

微信开放平台开发系列文章:

微信开放平台开发第三方授权登陆(一):开发前期准备

微信开放平台开发第三方授权登陆(二):PC网页端

微信开放平台开发第三方授权登陆(三):Android客户端

微信开放平台开发第三方授权登陆(四):微信公众号

微信开放平台开发第三方授权登陆(五):微信小程序

 

 

目录

一、需求

二、开发流程

三、具体实现步骤

1.引导用户跳转到微信授权网页

2. 通过code换取网页授权access_token

3.根据token获取用户信息

四、参数位置:


一、需求

根据需求,需要拥有第三方微信登录功能,并获取到用户信息。

二、开发流程

微信公众平台第三方授权登录的应用场景在于 : 在微信客户端(PC或APP)访问第三方网页,公众号可以通过网页授权机制,获取用户基本信息,实现业务逻辑。

1用户同意授权,获取code

2通过code换取网页授权access_token

3通过access_token拉取用户信息(需scope为 snsapi_userinfo)

公众号第三方授权获取用户信息基本流程

三、具体实现步骤

1.引导用户跳转到微信授权网页

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参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节

#wechat_redirect

无论直接打开还是做页面302重定向时候,必须带此参数

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。

注意:code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期

 @RequestMapping("/login")
    public String wechatLogin(HttpServletRequest httpServletRequest) {

        // 应用授权作用域:
        // 当为snsapi_base时,不弹出授权页面,直接跳转,只能获取用户openid。
        // 当为snsapi_userinfo时,弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息
        String scope = "snsapi_userinfo";

        String state = UUID.randomUUID().toString().replaceAll("-","");

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期,可配置
        RedisPoolUtil.setEx("wechat-mp-state-"+httpServletRequest.getSession().getId(), state, Integer.parseInt(env.getProperty("wechat.mp.exTime", "1800")));

        log.info("state= "+state);

        // 微信公众平台
        String get_auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "appid="
                + env.getProperty("wechat.mp.appid")
                + "&redirect_uri="
                + env.getProperty("application.url")
                + env.getProperty("wechat.mp.redirect_uri")
                + "&response_type=code"
                + "&scope="
                + scope
                + "&state="
                + state
                + "#wechat_redirect";

        log.info("URL:"+get_auth_url);

        return "redirect:" + get_auth_url;
    }

2. 通过code换取网页授权access_token

用户同意授权后,通过code换取网页授权access_token

https://api.weixin.qq.com/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与基础支持的access_token不同

"expires_in":7200,  // access_token接口调用凭证超时时间,单位(秒)

"refresh_token":"REFRESH_TOKEN", //用户刷新access_token

"openid":"OPENID",  //用户唯一标识

"scope":"SCOPE" }   //用户授权的作用域,使用逗号(,)分隔

错误返回样例:

{"errcode":40029,"errmsg":"invalid code"}


 

@RequestMapping("/getInfo")
    public String getInfo(HttpServletRequest httpServletRequest, Model model) {

        String code = httpServletRequest.getParameter("code");
        String state = httpServletRequest.getParameter("state");

        String value = RedisPoolUtil.get("wechat-mp-state-"+httpServletRequest.getSession().getId());

        log.info("Code = " + code+"  . State="+state+"    value="+value);

        /* 如果state值不匹配,则为非法请求,抛出异常 */
        if (StringUtils.isEmpty(code)||StringUtils.isEmpty(state)||value==null || !state.equals(value)){
            throw new RuntimeException("非法请求");
        }

        // 通过code换取网页授权access_token
        String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" +
                env.getProperty("wechat.mp.appid") +
                "&secret=" +
                env.getProperty("wechat.mp.secret") +
                "&code=" +
                code +
                "&grant_type=authorization_code";

        log.info(get_access_token_url);


        JSONObject accessTokenJsonObject = HttpClientUtils.httpGet(get_access_token_url);

        checkResult(accessTokenJsonObject);
        // 成功获取
        String access_token = (String) accessTokenJsonObject.get("access_token");
        Integer expires_in = (Integer) accessTokenJsonObject.get("expires_in");//access_token接口调用凭证超时时间,单位(秒)
        String userOpenid = (String) accessTokenJsonObject.get("openid");//用户唯一标识
        String scope = (String) accessTokenJsonObject.get("scope");//用户授权的作用域,使用逗号(,)分隔

        // TODO:文档没有写返回unionid,需要在实际公众号中进行测试(绑定开放平台的会有),如果没有unionid,则用openid存储用户,虽然这并不是合理的做法。因为openid仅仅该公众号下的用户唯一标识。。。

//        access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,
//        refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权

        WeChatUserInfo weChatUserInfo = null;

        weChatUserInfo = null; //FIXME: 根据unionid从数据库中查询
        if (weChatUserInfo == null){
            weChatUserInfo = getMPWeChatUserInfo(access_token,userOpenid);
            // insert into database

        }

        if (weChatUserInfo.getUnionid()!=null){
            // 当前是绑定开放平台的公众号.Union将成为唯一标识

        }

        model.addAttribute(weChatUserInfo);
        return "wechatUser";
    }

3.根据token获取用户信息

http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

参数

描述

access_token

网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同

openid

用户的唯一标识

lang

返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

正确时返回的JSON数据包如下:

{

"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"
}

private WeChatUserInfo getMPWeChatUserInfo(String accessToken, String openId){

        String get_userInfo_url = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" +
                accessToken +
                "&openid=" +
                openId +
                "&lang=zh_CN";

        JSONObject userInfoJsonObject = HttpClientUtils.httpGet(get_userInfo_url);

        checkResult(userInfoJsonObject);

        String user_openid = (String) userInfoJsonObject.get("openid");
        String user_nickname = (String) userInfoJsonObject.get("nickname");
        Integer user_sex = (Integer) userInfoJsonObject.get("sex");//用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
        String user_province = (String) userInfoJsonObject.get("province");
        String user_city = (String) userInfoJsonObject.get("city");
        String user_country = (String) userInfoJsonObject.get("country");//国家,如中国为CN,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
        String user_headimgurl = (String) userInfoJsonObject.get("headimgurl");//头像
        List user_privilege = (List) userInfoJsonObject.get("privilege");//用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
        String user_unionid = (String) userInfoJsonObject.get("unionid");


        WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
        weChatUserInfo.setOpenid(user_openid);
        weChatUserInfo.setNickname(user_nickname);
        weChatUserInfo.setSex(user_sex);
        weChatUserInfo.setProvince(user_province);
        weChatUserInfo.setCity(user_city);
        weChatUserInfo.setCountry(user_country);
        weChatUserInfo.setHeadimgurl(user_headimgurl);
        weChatUserInfo.setPrivilege(StringTools.listToString(user_privilege));
        weChatUserInfo.setUnionid(user_unionid);

        log.info("用户信息如下:" +
                "   opeinId:" + user_openid +
                "   用户昵称:" + user_nickname +
                "   用户的性别:" + user_sex +
                "   省份:" + user_province +
                "   城市:" + user_city +
                "   国家:" + user_country +
                "   头像:" + user_headimgurl +
                "   用户特权信息:" + user_privilege +
                "   UnionId:" + user_unionid
        );

        return weChatUserInfo;
    }

四、参数位置:

开放平台绑定公众号:

  • 4
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值