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

版权声明:本文为博主原创文章,转载添加原文链接 https://blog.csdn.net/qq_34190023/article/details/82017767

微信公众平台第三方授权登陆开发文档

需要微信公众号认证后才能获取用户信息。微信公众平台微信号适合用于公众号内微信登录

注:微信公众号绑定微信开放平台后,可以获取unionid用户唯一标识

一、需求

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

二、开发流程

微信公众平台第三方授权登录的应用场景在于 : 在微信客户端(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 wecharLogin(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("wechar- mp -state-"+httpServletRequest.getSession().getId(), state, Integer.parseInt(env.getProperty("wechar.mp.exTime", "1800")));

        String get_auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?"

                + "appid="

                + env.getProperty("wechar.mp.appid")

                + "&redirect_uri="

                + env.getProperty("wechar.mp.redirect_uri")

                + "&response_type=code"

                + "&scope="

                + scope

                + "&state="

                + state

                + "#wechat_redirect";

        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("wechar-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("wechar.mp.appid") +

                "&secret=" +

                env.getProperty("wechar.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");//用户授权的作用域,使用逗号(,)分隔

        log.info(access_token + "-" + userOpenid + "-" + scope);

 

        WeCharUserInfo weCharUserInfo = getMPWeCharUserInfo(access_token,userOpenid);

        if (weCharUserInfo.getUnionid()!=null){

            // 当前是绑定开放平台的公众号.Union将成为唯一标识

 

        }

        model.addAttribute(weCharUserInfo);

        return "wecharUser";

    }

 

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 WeCharUserInfo getMPWeCharUserInfo(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");//只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
    WeCharUserInfo weCharUserInfo = new WeCharUserInfo();
    weCharUserInfo.setOpenid(user_openid);
    weCharUserInfo.setNickname(user_nickname);
    weCharUserInfo.setSex(user_sex);
    weCharUserInfo.setProvince(user_province);
    weCharUserInfo.setCity(user_city);
    weCharUserInfo.setCountry(user_country);
    weCharUserInfo.setHeadimgurl(user_headimgurl);
    weCharUserInfo.setPrivilege(StringTools.listToString(user_privilege));
    weCharUserInfo.setUnionid(user_unionid);

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

    return weCharUserInfo;
}

 

猜你喜欢

转载自blog.csdn.net/qq_34190023/article/details/82017767