微信公众号--根据用户opneId获取用户信息

一、登录微信公众号的测试环境,找到“网页授权获取用户基本信息”点击修改,添加上自己的回调地址域名。测试时可以写IP:端口号,正式环境只支持域名不要写http://或https://。

 二、步骤:

 1、用户同意授权,获取code:

      参考链接:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
  • scope的参数有2种:一种是snsapi_base权限只能获取OpenId而且不会弹出授权页面,另为一种是snsapi_userinfo权限会弹出授权页面并且会获取用户信息。
  • redirect_url:是回调地址,当请求成功的时候会重定向到回调页面,并返回code和state。回调地址必须是设置的回调地址域名下且需要进行urlEncode处理。
    如:http://xxxx.xxxx.cn/test/wechat/redirect?code=CODE&state=1

 2、通过code获取access_token:

       参考链接:

https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code

 3、通过access_token获取用户信息:

       参考链接:

https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=en

三、代码

1、通过消息模板推送授权链接:

/**
     * 推送给新关注的用户授权
     * @param openId 用户的openId
     */
    public static void followMessage(String openId) {
        try {
            // 发送消息的时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateFormat = simpleDateFormat.format(new Date());
            // 获取AccessToken的值
            String accessToken = WaChatServiceUtil.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            // 获取消息模版id
            String Message = MessageTemplateEnum.FOLLOW_MESSAGE_TEMPLATE.getKey();
            // 回调地址,需要用urlEncode对链接进行处理,微信公众号中需要将授权回调页面域名配置好回调地址需要在回调页面域名下
            String callbackUrl = "http%3A%2F%2F"+DOMAINNAME+"%2Fsampling-merchant-web%2Fherman%2Ftest%2Fwechat%2Fredirect.cgi";
            // appId
            String appId = WaChatServiceUtil.getAPPID();
            // 授权地址,用户点击后将进行授权,返回给回调地址code值,state为任意a-zA-Z0-9的参数值,最多128字节
            String empowerUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + callbackUrl + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

            // 设置模版消息的内容
            WeChatTemplate wc = new WeChatTemplate();
            wc.setTouser(openId);
            wc.setTemplate_id(Message);
            wc.setUrl(empowerUrl);
            Map<String, TemplateData> m = new HashMap<>();
            m.put("first", new TemplateData("欢迎关注mamain,点击下方进行授权", "#000000"));
            m.put("time", new TemplateData(dateFormat, "#000000"));
            m.put("url", new TemplateData("点击进行授权,获取您的微信名。", "#173177"));
            m.put("remark", new TemplateData("有疑问请联系客服!", "#FF0000"));
            wc.setData(m);
            //post发送授权消息模版
            String rString = WeChatUtils.sendPost(url, JSON.toJSONString(wc));
            logger.info("发送授权模版消息结果为:{}", rString);
        } catch (Exception e) {
            logger.error("发送授权模版消息失败!", e);
        }
    }

2、获取用户信息

/**
     * 回调:微信授权,获取用户code
     */
    @RequestMapping(value = "wechat/redirect", method = RequestMethod.GET,produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String wechatRedirect(HttpServletRequest request) throws IOException {
        try {
            // 获取用户code
            String code = request.getParameter("code");
            if (null==code){
                logger.error("code为空!");
                return "error:code为空,授权失败";
            }
            logger.info("code为{}",code);
            // 获取 access_token
            String appid= WaChatServiceUtil.getAPPID();
            String appSecret=WaChatServiceUtil.getAPPSECRET();
            String getToken="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
            JSONObject token = JSONObject.parseObject(WeChatUtils.sendGet(getToken));
            Object access_token=token.get("access_token");
            String openId= (String) token.get("openid");
            logger.info("access_token:{},openid{}",access_token,openId);
            // 获取用户信息
            String getUser="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
            JSONObject user = JSONObject.parseObject(WeChatUtils.sendGet(getUser));
            String wechatName= (String) user.get("nickname");
            logger.info("用户名为:{},openid为:{}",wechatName,openId);
        }catch (Exception e){
            logger.error("获取用户信息异常!", e);
        }
        return "<h1 align=\"center\">您已授权成功</h1>";
    }

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值