Implementation steps for WeChat applet to implement subscription message push

1. Preparation

  Prepare the mini program account and development environment. My mini program is developed based on uniapp, and the backend code is developed based on SpringBoot. At the same time, read the official documentation first to learn about mini program subscription messages and how the backend sends subscription messages. The official documentation address is as follows:

  1. "Mini Program Subscription News"
  2. "Send Subscription Message"

2. Implementation steps

2.1. Enable and configure message push

   Log in to the WeChat mini program backend, go to Development->Development Management->Development Settings, scroll down to the message push panel, and fill in your own server push address. Token (token) and EncodingAESKey (message encryption key) are optional. It is best not to change or leak them after setting them. The background interface verification is required.
Insert image description here

2.2. Build push interface service

   In the above configuration, the relevant service interface needs to be used. The service interface requires two interfaces with the same name, one supports Get and the other supports Post. The Get method mainly implements permission ownership authentication and is only called once; while the Post method, when When a user actively subscribes to a one-time message in the WeChat applet, the Tencent server will request the Post interface and send the user's relevant behavioral event results to the developer server. Only users subscribed by the user are allowed to push messages. In fact, what is received here is not just Message subscription events, various interactive events are received here. The following code simply implements parsing and does not implement relevant logic in detail.

@RequestMapping(value = "get")
    @ResponseBody
    public String get(HttpServletRequest request,String signature, String timestamp, String nonce, String echostr) {
    
    
        if(request.getMethod().equalsIgnoreCase("get")){
    
    //用来校验,一般会验证前端配置的token等,这里简化了代码。
            return echostr;
        }else if(request.getMethod().equalsIgnoreCase("POST")){
    
    //接收用户的相关行为事件结果
            try {
    
    
                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                StringBuilder requestContent = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
    
    
                    requestContent.append(line);
                }
                reader.close();
                //接收:{"ToUserName":"gh_ea84a199bf81","FromUserName":"oG0NJ5Oi_3Dd1HlZJ14xfnA0sJ6s","CreateTime":1686131943,"MsgType":"event","Event":"subscribe_msg_popup_event","List":{"PopupScene":"0","SubscribeStatusString":"accept","TemplateId":"4ondVRxk4L20ihrJ3iI15BDK72XatGPxE0MeCVwHasQ"}}
                logger.info("接收:" + requestContent.toString());
                return "";
            } catch (IOException e) {
    
    
                // 处理异常情况
                e.printStackTrace();
                logger.error("异常:" + e.getMessage());
                return e.toString();
            }
        }else{
    
    
            logger.info("不是get 或 post方法");
            return null;
        }
    }
2.3. Message template application

  Select a public template on the WeChat public platform or apply for a template that meets your needs (it needs to comply with the rules). Here we have chosen a public template. After the application is approved, we can obtain information such as the message template ID and detailed content.

1. For individual developers’ WeChat mini program accounts, it is not possible to directly add subscription message templates. The function of subscribing to message templates is only available to corporate entities’ WeChat official accounts and mini-programs.
2. Personal developer accounts can only use existing subscription message templates to push subscription messages, and cannot customize or add new templates.

Insert image description here
Insert image description here

2.4. User authorization

  Obtain the user's authorization to subscribe to messages in the mini program: In the applet, you need to call the wx.requestSubscribeMessage interface to obtain the user's authorization to subscribe to messages. After the user agrees to authorize, you can get the user's subscription message subscription status.

//uniapp封装了wx.requestSubscribeMessage接口
uni.requestSubscribeMessage({
    
    
 tmplIds: ['4ondVRxk4L20ihrJ3iI15BDK72XatGPxE0MeCVwHasQ'],
  success (res) {
    
    
	  console.log(res);
  }
})

For detailed usage of this method, please refer to "wx.requestSubscribeMessage(Object object) Usage"official document.

  Click the button that calls the above method, and the following page will pop up. After selecting Allow, you can receive notification messages pushed by the backend.

Insert image description here

2.5. Message push implementation

  In practical applications, we should maintain a data table of WeChat users who need to push messages, including whether the user has subscribed, the WeChat user's openid and other information. Here is a temporary demonstration, which omits this information and directly hardcodes the template ID. Message content, WeChat user openId and other information.

/**
 * 订阅消息推送方法
 */
public class WeChatSubscribeMessageSender {
    
    
    private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
    public static void sendSubscribeMessage(String accessToken, String openid, String templateId, String page, String data) {
    
    
        try {
    
    
            String url = API_URL + "?access_token=" + accessToken;

            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setDoOutput(true);

            // 构建请求体
            String body = buildRequestBody(openid, templateId, page, data);
            byte[] requestBodyBytes = body.getBytes(StandardCharsets.UTF_8);

            // 发送请求
            connection.getOutputStream().write(requestBodyBytes);

            // 读取响应
            int responseCode = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
    
    
                response.append(line);
            }
            reader.close();

            if (responseCode == HttpURLConnection.HTTP_OK) {
    
    
                // 请求成功处理逻辑
                System.out.println("发送订阅消息成功");
                System.out.println(response.toString());
            } else {
    
    
                // 请求失败处理逻辑
                System.out.println("发送订阅消息失败");
                System.out.println("响应码:" + responseCode);
                System.out.println(response.toString());
            }

            connection.disconnect();
        } catch (IOException e) {
    
    
            // 异常处理逻辑
            e.printStackTrace();
        }
    }

    private static String buildRequestBody(String openid, String templateId, String page, String data) {
    
    
        // 构建请求体的JSON字符串
        return String.format(
                "{\"touser\":\"%s\",\"template_id\":\"%s\",\"page\":\"%s\",\"data\":%s}",
                openid, templateId, page, data);
    }
}
//推送消息的时候需要accessToken,这里是获取token的方法,在实际环境中,一般是定时刷新,两个小时内有效,获取accesstoken时需要appid和secret信息,一般是后台参数或常量进行配置。
 //获取accessToken的请求接口
private final static String GetAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";

public String refreshAccessToken(String appid, String secret){
    
    
        if(StringUtils.isEmpty(appid) || StringUtils.isEmpty(secret)){
    
    
            logger.error("刷新微信AccessToken时,缺少appid或secret参数!");
            throw new WxBzException(SysErrorCode.SYS_ERROR_700000,"刷新微信AccessToken时,缺少appid或secret参数!");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("appid",appid);
        param.put("secret",secret);
        ResponseEntity<JSONObject> resp = restTemplate.getForEntity(GetAccessToken, JSONObject.class,param);
        JSONObject jsonObj = resp.getBody();
        String accessToken = null;
        if(jsonObj != null){
    
    
            accessToken = jsonObj.getString("access_token");
        }
        return accessToken;
    }
//消息推送的模拟方法
@Controller
@RequestMapping(value = "/api/wx/xcx")
public class WxApi {
    
    

    Logger logger = LoggerFactory.getLogger(WxApi.class);

    @Autowired
    private WxCommonService wxCommonService;

    @RequestMapping(value = "sendMsg")
    @ResponseBody
    public String sendMsg(HttpServletRequest request){
    
    
        //String token = request.getParameter("token");
        //请求 微信接口 获取 accessToken
        String accessToken = wxCommonService.refreshAccessToken(WxConstants.WX_XCX_APPID,WxConstants.WX_XCX_SECRET);
        String openid = "接收消息的微信用户的openId";
        String templateId = "微信订阅消息模板";
        String page = "点击消息的跳转路径";
        // 构建订阅消息内容的JSON对象
        // 构建订阅消息内容的JSON对象
        JSONObject messageData = new JSONObject();
        messageData.put("thing1", createDataItem("提醒内容", "您有新的提醒"));
        messageData.put("thing2", createDataItem("作业名称", "Java作业"));
        messageData.put("time3", createDataItem("截至日期", "2023-06-30"));
        messageData.put("thing4", createDataItem("发布人员", "张三"));
        // 将订阅消息内容转换为JSON字符串
        String jsonData = messageData.toJSONString();
        WeChatSubscribeMessageSender.sendSubscribeMessage(accessToken,openid,templateId,page,jsonData);
        return null;
    }
    private static Map<String, Object> createDataItem(String name, String value) {
    
    
        Map<String, Object> item = new HashMap<>();
        item.put("value", value);
        return item;
    }
}
2.6. Test simulated messages

  After completing the above work, start the service, first subscribe to the message through the WeChat applet,
and then call the simulated message push method http://localhost:8080/api/wx/ xcx/sendMsg, at this time the message will be received in the WeChat service, as shown in the figure below;
Insert image description here

Guess you like

Origin blog.csdn.net/hou_ge/article/details/131201731