当前位置:网站首页>【项目实训】微信公众号获取用户openid

【项目实训】微信公众号获取用户openid

2022-06-12 01:13:00 par_ser

首先,为了方便公众号开发测试,可以申请测试号,地址如下

微信公众平台

向指定用户推送消息,通常需要他的openId,要获取用户的openId,可以通过微信公众号的网页授权回调(搭配一个用户绑定页面,可以将微信公众号用户与我们自己的系统的用户建立联系)

上面是微信开发文档的说明,可以看到如果我们仅仅想做用户绑定,然后推送模板消息的话,那么scope只需要为snsapi_base

    @GetMapping("/getUserCode")
    public String  getUserCode(){
        String backUrl = "http://ip端口/wx/getUserOpenId";
        String getOpenIdUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri="+ backUrl+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        getOpenIdUrl = getOpenIdUrl.replace("APPID",appid);
        return "redirect:" + getOpenIdUrl;
    }

    /**
     * 获取用户openId
     * @return
     * @throws IOException
     */
    @GetMapping("/getUserOpenId")
    public  String getUserOpenId(HttpServletRequest request)throws IOException{
        //获取code
        String code = request.getParameter("code");
        System.out.println("code:"+code);
        if(code== null){
            System.out.println("code为空");
        }
        String openid = WechatUserUtil.exchangeCode2OpenId(code,appid,secret);
        return openid;
    }

 

    public static String exchangeCode2OpenId(String code,String appId,String appSecret) {
        String openid = "";
        try {
            // 换取access_token 其中包含了openid
            // 这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该access_token用于调用其他接口)不同。
            String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
                    .replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
            String jsonStr = HttpUtil.sendGet(URL);
            System.out.println("----------微信换取openid返回的结果:{}----------");
            Gson gson = new Gson();
            WechatOpenId wechatOpenId = gson.fromJson(jsonStr, WechatOpenId.class);
            if (null != wechatOpenId) {
                openid = wechatOpenId.getOpenid();
            }
        } catch (Exception e) {
            System.out.println("----------微信换取openid发生了异常:{}----------");
        }
        return openid;
    }

原网站

版权声明
本文为[par_ser]所创,转载请带上原文链接,感谢
https://blog.csdn.net/par_ser/article/details/125238625