The applet sends a template message to the user - a one-time template realizes "long-term subscription"

Hello everyone! I play Yasuo and I know C. When writing small programs, we have the need to send messages to users, such as sending reminder notifications, or some important notifications to form a closed loop of services. This will use the message sending function of WeChat . Next, I will use the Java language to demonstrate in detail how to use one-time subscription messages to send messages to users.

1. Wechat message sending process

insert image description here

Because WeChat is a relatively formal social software, the action of actively sending messages to users is easily used by some merchants as a means of marketing. In order to avoid users being harassed, it is up to the users to directly decide whether to accept the message. This design is very good!

2. Subscribe to news

2.1 Message template

To send a message, you must use the official message template provided by the WeChat Mini Program. The message template can be obtained on the WeChat official account platform (the premise is that you have registered), as shown in the figure below:
insert image description here
After selecting the template, click the button in the operation bar 选用. As shown below:
insert image description here

insert image description here

2.1.1 Description of message content:

insert image description here

(1) Template id: the unique identifier of the template, 微信小程序端and 服务器端both must be used to determine which template to use.
(2) Detailed content: Here is the content of the message. The warm is the title { {ting6.DATA}}and the value.

The content in the rest of the templates is not important and will not be described here.

2.2 Message Types

(1) One-time subscription : After the user subscribes independently, he can send a corresponding service message for an unlimited time; only one message can be sent for each subscription.

(2) Long-term subscription : After a user subscribes once, they can send multiple messages for a long time. Long-term subscriptions have high requirements for qualifications, and 目前长期性订阅消息仅向政务民生、医疗、交通、金融、教育等线下公共服务开放,后期将逐步支持到其他线下公共服务业务。this article uses one-time subscriptions.

2.3 Message sending

(1) Method: wx.requestSubscribeMessage(Object object)(WeChat official document entry) It should be wx.requestSubscribeMessage()used 微信小程序端to invoke the subscription message interface. As shown below:
insert image description here

2.3.1 Precautions:

(1) Trigger mode: wx.requestSubscribeMessage(Object object) can only be used to trigger by clicking the button.

(2) One-time message: As mentioned in the message type, 一次性订阅消息after the user subscribes independently, the message can only be sent once.

3. Front-end code

3.1 Front-end code

(1) Front-end Html code:

  ...
  //由点击事件调出订阅消息界面
  <button bindtap="subScriptionMessage"></button>
  ...

(2) Front-end JS code:

...
//调出 模板消息界面
 subScriptionMessage(){
    
    
	 wx.requestSubscribeMessage({
    
    
	  	//模板id,可以写多个
		tmplIds:['sn12-c51f_1PCY52t0u5UZbqKaS7z4G7U1mV-4ZH']
		//成功回调
		success(res){
    
    
	        console.log(res);
	    },
	    //失败回调
	    fail(res){
    
    
	        console.log(res);
	    }
  	})
 } 
...

3.2 Backend code

(1) Code

import lombok.extern.slf4j.Slf4j;
  	//微信小程序id
    private final String appId = "xxx";
    //微信小程序密钥
    private final String appSecret = "xxx";
    //模板id
    private final String templateId = "xxx";
    //用户openid
    private final String openUserId = "xxxx";
    //消息内容-温馨提示
    private final String warmTip = "hello,tough gay!";
    //跳转页面地址
    private final String pageUrl = "pages/index/index";
    //获取token接口
    private final String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId + "&secret=" + appSecret;
    //发送消息接口
    private final String sendWxUserMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";
 
    public void sendMessage(){
    
    
        //获取token
        String accessTokenResult = HttpClientUtil.doGet(getTokenUrl);
        String accessToken = JSONObject.parseObject(accessTokenResult).getString("access_token");
        SendMsgToWxUserRequestDTO sendMsgToWxUserRequestDTO = new SendMsgToWxUserRequestDTO();
        sendMsgToWxUserRequestDTO.setAccessToken(accessToken);
        sendMsgToWxUserRequestDTO.setTouser(openUserId);
        sendMsgToWxUserRequestDTO.setTemplate_id(templateId);
        JSONObject key = new JSONObject();
        //温馨提醒
        JSONObject thing6OfValue = new JSONObject();
        thing6OfValue.put("value",warmTip);
        key.put("thing6",thing6OfValue);
        //当前时间
        JSONObject time2 = new JSONObject();
        time2.put("value", DateUtil.dateToString(new Date(),DateUtil.DATETIME_FORMATTER));
        key.put("time2",time2);
        sendMsgToWxUserRequestDTO.setData(key);
        sendMsgToWxUserRequestDTO.setPage(pageUrl);
        String sendMessageUrl = sendWxUserMsgUrl + accessToken;
        log.info("发送消息参数:{}",JSONObject.toJSONString(sendMsgToWxUserRequestDTO));
        String s = HttpClientUtil.doPost(sendMessageUrl, JSONObject.toJSONString(sendMsgToWxUserRequestDTO));
        log.info("发送消息参数,返回值:{}",s);
    }

(2) Effect of sending message:

insert image description here

3.2.1 Step breakdown:

(1) Call the token acquisition interface:

interface:

GET: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=APP_SECRET

Request parameters:

appid secret
applet id applet key

Parameter Description:

appidThe values ​​of and secrettwo can be found in the background of the WeChat applet.insert image description here

return value:

access_token expires_in
token value Effective time

(2) Call the sending message interface:

interface:

POST : https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=TOKEN

Request parameters:

accessToken touser template_id page data
token message recipient message templateid Click on the message details to jump to the page Message content

Parameter Description:

token: by 步骤1getting

toUser:It belongs to WeChat users openId, and can be obtained when logging in to obtain user information in the WeChat applet.

page:进入小程序查看It is the page that jumps after clicking the message .

insert image description here
data:is the content in the message template. It should be noted that the content in the message template is assigned and displayed in the form of keyand . Take the following template as an example: we can see that there are only two message contents in the message template: and , which correspond to and respectively .value工作通知
insert image description here
温馨提示时间keything6time2

Remember, keyit must be consistent with the template! ! !

3.3 Possible problems

3.3.1 Parameters are illegal:

Error content:

{
    
    "errcode":47003,"errmsg":"argument invalid! data.thing6.value invalid rid: 63904a7c-774dbdca-33bce62d"}

reason:

(1) The value in the message template is empty. All fields displayed in the message template are required.
(2) What is in the code keydoes not correspond to what is in the target.
(3) keyThe corresponding valuecontent is too long.

4. Practical application

Through the above introduction, I think everyone has two general understandings of 微信小程序sending . We know that after the user agrees, the server can only send a message to the user. If you want to send it again later, you need to ask the user whether to subscribe. So what if we want to keep sending messages to users? How should we deal with such a scenario?模板消息
订阅消息一条

4.1 "Always keep the selection above"

When asking the user whether to agree to receive the message, there is one below 总是保持以上选择, if the user 勾选了clicks 确定, then if the user is asked whether to agree to receive the message again later, it will not pop up 订阅消息界面.
insert image description here

How should we judge users 勾选了保持以上选择?

You can use the WeChat Mini Program wx.getSetting({})method. This method will 勾选了保持以上选择print out the template id after. So we need to 订阅界面determine whether the template id is included in the success callback method setting.
insert image description here

4.2 Implementation ideas

  • Add an indication to the WeChat user in the background database 字段:check_flag, indicating whether to check 总是保持以上选择, true:勾选了, false:未勾选.
  • In wx.requestSubscribeMessage()the call of the success callback method, wx.setting()it is judged whether the user has selected it 总是保持以上选择.
  • If yes, modify check_flag=true.
  • In 微信小程序the must-click place, add the calling wx.requestSubscribeMessage()method.
  • Called if lastcheck_flag .truewx.requestSubscribeMessage()

Then it can be realized that the user clicks once on the login interface to send multiple messages to the user. If the user does not want to receive messages again. You can modify it in the three dots in the upper right corner of my applet 设置.

4.3 Code:


//在用户必点的地方,调用订阅消息方法
clickSubscribeMessage(){
    
    
   let flag = wx.getStorageSync('checkFlag');
   console.log(false);
   //订阅消息
   if(flag == 1){
    
    
     let workTaskTemplateId = app.globalData.workTaskTemplateId;
     wx.requestSubscribeMessage({
    
    
       tmplIds: [workTaskTemplateId],
       success(res){
    
    
         console.log(res);
       },
       fail(res){
    
    
         console.log(res);
       }
     })
   }
 }
...
//订阅消息
  subScriptionMessage(){
    
    
    var that = this;
    //模板id
    let workTaskTemplateId = 'xxx';
    wx.requestSubscribeMessage({
    
    
      tmplIds: [workTaskTemplateId],
      success (res) {
    
     
        if(JSON.stringify(res).indexOf("reject") != -1){
    
    
          console.log("拒绝")
        } 
        if(JSON.stringify(res).indexOf("accept") != -1){
    
    
          console.log("接受")
          wx.getSetting({
    
    
            withSubscriptions: true,
            success (res) {
    
    
              console.log(res.subscriptionsSetting)
              if(JSON.stringify(res.subscriptionsSetting).indexOf(workTaskTemplateId) != -1){
    
    
                console.log("用户选择了“保持以上选择”")
                that.checkFlag();
              }
            }
          })
        } 
      },
      fail(res){
    
    
        console.log(res);
      }
    })
  },
 ...
 //请求后台接口,修改check_flag 
 checkFlag(){
    
    
 	//请求后台修改check_flag 字段为true
    wx.request({
    
    
      url: 'xxxx',
      ...
      success:function(res){
    
    
        //如果修改成功将check_status字段放到storage中
        wx.setStorageSync("checkFlag",true)
      },
      fail:function(res){
    
    },
    })
 }

If you have a better way, please leave a message. The above screenshot example comes from a WeChat applet I made TaskPlan. The link is as follows, welcome to visit:

☞ ☞ ☞ People will always change, so why not change for the better? ——TaskPlan

Guess you like

Origin blog.csdn.net/qq_42785250/article/details/128192824