公众号扫码登陆

2022-01-07  本文已影响0人  梦过无烟

第一步、 获取微信token

 public String getWxAccessToken() {

        String accessToken = (String) redissonClient.getBucket(wxToken).get();
        if (StrUtil.isEmpty(accessToken)) {
            String url = String.format(
                    "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                    appConfig.getWxAppid(), appConfig.getWxSecret());
            String result = HttpUtil.get(url);
            JSONObject jsonObject = JSONObject.parseObject(result);
            accessToken = jsonObject.getString("access_token");
            Long expiresIn = jsonObject.getLong("expires_in");
            redissonClient.getBucket(wxToken).set(accessToken, expiresIn, TimeUnit.SECONDS);
        }

        return accessToken;
    }

第二步、获取二维码

public QrCodeModel getQrCode() {

        String url =
                String.format("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s", getWxAccessToken());

        JSONObject paramJson = new JSONObject();
        paramJson.put("expire_seconds", 86400);
        paramJson.put("action_name", "QR_STR_SCENE");

        JSONObject sceneInfo = new JSONObject();
        sceneInfo.put("scene_id", ObjectId.getObjectId());

        JSONObject scene = new JSONObject();
        scene.put("scene", sceneInfo);

        paramJson.put("action_info", scene);
        paramJson.put("scene_str", ObjectId.getObjectId());

        String result = HttpUtil.post(url, paramJson.toJSONString());
        logger.debug(result);

        QrCodeModel model = new QrCodeModel();
        JSONObject jsonObject = JSON.parseObject(result);
        model.setTicket(jsonObject.getString("ticket"));
        model.setUrl(jsonObject.getString("url"));
        return model;
    }

第三步 获取用户信息

#页面根据生成二维码时的 ticket 轮询获取用户信息
#后端获取用户信息
public OpenUserInfoModel queryUserInfoByOpenid(String openid) {

        // 客户登陆

        if (StrUtil.isEmpty(openid)) {
            throw new BusinessException(1001, "微信平台返回openid错误");
        }

        String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN",
                getWxAccessToken(), openid);

        String result = HttpUtil.get(url);

        JSONObject jsonObject = JSONObject.parseObject(result);
        WxUserInfoModel wxUserModel = new WxUserInfoModel();
        wxUserModel.setOpenid(openid);
        wxUserModel.setNickName(jsonObject.getString("nickname"));
        if (!org.springframework.util.StringUtils.isEmpty(wxUserModel.getNickName())) {
            wxUserModel.setNickName(wxUserModel.getNickName());
        }
        wxUserModel.setGender(jsonObject.getInteger("sex"));
        wxUserModel.setProvince(jsonObject.getString("province"));
        wxUserModel.setCity(jsonObject.getString("city"));
        wxUserModel.setCountry(jsonObject.getString("country"));
        wxUserModel.setAvatarUrl(jsonObject.getString("headimgurl"));
        wxUserModel.setUnionid(jsonObject.getString("unionid"));
      //处理你自己的业务逻辑
    }

微信公众号回调事件处理

/***
     * 微信服务器触发get请求用于检测签名
     * 
     * @return
     */
    @GetMapping("/handleWxCheckSignature")
    @ApiOperation(value = "签名检测")
    public String handleWxCheckSignature(HttpServletRequest request) {

        String echostr = request.getParameter("echostr");
        return echostr;
    }

    /**
     * 接收微信推送事件
     * 
     * @param request
     * @return
     */
    @PostMapping("/handleWxCheckSignature")
    @ApiOperation(value = "微信事件处理")
    public String handleWxEvent(HttpServletRequest request) {

        try {
            InputStream inputStream = request.getInputStream();

            StringBuilder sb = new StringBuilder();
            String line;

            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            Map<String, Object> objectMap = XmlUtil.xmlToMap(sb.toString());

            logger.debug("map:{}", objectMap);

            String userOpenId = (String) objectMap.get("FromUserName");
            String ticket = (String) objectMap.get("Ticket");

            String event = (String) objectMap.get("Event");

            if (subscribe.equalsIgnoreCase(event) || scan.equalsIgnoreCase(event)) {
                // 查询ticket是否存在
                Boolean aBoolean = openUserInfoService.checkUserTicket(userOpenId, ticket);
                if (aBoolean) {
                    return "success";
                }

                // 获取用户信息
                openUserInfoService.queryUserInfoByOpenid(userOpenId);
                // 保存二维码ticket
                openUserInfoService.saveUserTicket(userOpenId, ticket);

                String result = "<xml>\n" + "  <ToUserName><![CDATA[" + userOpenId + "]]></ToUserName>\n"
                        + "  <FromUserName><![CDATA[" + appConfig.getFromUserName() + "]]></FromUserName>\n"
                        + "  <CreateTime>" + System.currentTimeMillis() / 1000 + "</CreateTime>\n"
                        + "  <MsgType><![CDATA[text]]></MsgType>\n" + "  <Content><![CDATA[登录成功]]></Content>\n"
                        + "</xml>";
                return result;
            }

            return "success";
        } catch (Exception e) {
            //ignore
        }

        return "success";
    }
上一篇下一篇

猜你喜欢

热点阅读