微信生成带参数二维码(用户id), 扫码可获取用户id

生成带参数的二维码: 
        
https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html

示例代码: 

    /**
     * 生成带参数的二维码
     *
     * @param userId    用户id
     * @return
     */
    @GetMapping
    @RequestMapping("/createTicket/{userId}")
    public AjaxResult createTicket(@PathVariable Long userId){
        String ossUrl = ticketService.createTicket(userId);
        Map<String, String> map = new HashMap<>();
        map.put("ossUrl", ossUrl);
        return AjaxResult.success("操作成功", map);
    }

    /**
     * 生成带参数的二维码
     *
     * @param userId    用户id
     * @return
     */
    @Override
    public String createTicket(Long userId) {

        if (userId == null) {
            userId = 0L;
        }

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

        // 生成永久二维码
        String data = String.format("{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": %d}}}", userId);

        // 发送POST请求获取ticket
        RestTemplate restTemplate = new RestTemplate();
        // {"ticket":"gQGi8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyNGN1TzRPaU5jSkgxMDAwMHcwMzUAAgRoga9lAwQAAAAA","url":"http:\/\/weixin.qq.com\/q\/024cuO4OiNcJH10000w035"}
        String ticketResponse = restTemplate.postForObject(url, data, String.class);

        // 解析ticket
        JSONObject jsonObject = JSONObject.parseObject(ticketResponse);
        String ticket = jsonObject.getString("ticket");

        //  根据ticket获取二维码图片URL
        String ticketUrl = String.format("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s", ticket);

        // 上传oss
        String ossUrl = ossUtils.strToInputStreamUpload(ticketUrl);

        log.info("生成的带参数二维码URL:" + ossUrl);
        return ossUrl;
    }

扫码接收事件推送:
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html

示例代码: 

    /**
     * 接收用户消息并回复消息
     *
     * @param request       xml内容
     * @return              xml格式的字符串
     */
    @PostMapping("/validateWeChatServer")
    public String receiveMessage(HttpServletRequest request) {
        return weChatService.receiveMessage(request);
    }

  /**
     * 接收用户消息并回复消息
     *
     * @param request       xml内容
     * @return              xml格式的字符串
     */
    @Override
    public String receiveMessage(HttpServletRequest request) {

        ServletInputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            HashMap<String, String> map = new HashMap<>();
            SAXReader reader = new SAXReader();

            try {
                // 读取request输入流, 获取Document对象
                Document document = reader.read(inputStream);
                // 获取root节点
                Element root = document.getRootElement();
                // 获取所有的子节点
                List<Element> elements = root.elements();
                for (Element element : elements) {
                    map.put(element.getName(), element.getText());
                }
                log.info("接收到的用户消息: {}", map);
            } catch (DocumentException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 关注用户, 保存到数据库
            ResUser user = SpringUtils.getBean(IResUserService.class).attentionMedia(map.get("FromUserName"));
            // 回复消息
            String message = getReplyTextMessage(map, user);
            log.info("回复消息: {}", message);
            return message;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

private String getReplyTextMessage(HashMap<String, String> map, ResUser user) {
	// 未关注用户时Event=subscribe, EventKey=qrscene_4(事件KEY值,qrscene_为前缀,后面是自定义的用户id)
	// 获取 "qrscene_" 后面的值
	Long userId = Long.valueOf(map.get("EventKey").substring("qrscene_".length()));
	
	// TODO
	
}

接收到的用户消息: {Ticket=gQFC8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyaWplQzQzaU5jSkgxMDAwME0wM3oAAgR6r7BlAwQAAAAA, CreateTime=1706078168, EventKey=qrscene_4, Event=subscribe, ToUserName=gh_da9c697c8555, FromUserName=oUjEt6xFAs2ABHsmLyJeSUe-WVXI, MsgType=event}

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yixian123.com

谢谢打赏,祝老板心想事成

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值