Table of Contents
Requirement background
How to prevent template message push from being restricted?
Client
Collect push code
Report push code
Server
Push template message
Home Backend Development PHP Tutorial Realize unrestricted and unlimited active push of WeChat mini program template messages

Realize unrestricted and unlimited active push of WeChat mini program template messages

Mar 01, 2018 pm 02:55 PM
Restricted Applets information

Requirement background

Based on WeChat’s notification channel, WeChat mini programs provide developers with template messaging capabilities that can efficiently reach users, allowing users to interact with the mini program page. Triggered after the action, you can quickly access the message through the service notification in the WeChat chat list. Click to view the details and jump to the designated page of the mini program that sent the message.

The conditions for WeChat applet to allow the issuance of template messages are divided into two categories: payment or form submission. The restriction on sending template messages by submitting a form is "Allow developers to push a limited number of template messages to users within 7 days (one message can be sent once a form is submitted, and the number of messages submitted for multiple submissions is independent and does not affect each other) ".

However, it is obviously not enough for a user to push a notification within 7 days once triggered. For example, the check-in function uses the push of template messages to remind users to check in every day. It can only get the opportunity to push the template message once when the user checked in the day before, and then use it to send check-in reminders to the user the next day. However, in many cases, if a user forgets to sign in on a certain day, the system loses the authority to remind the user, resulting in disconnection with the user; for another example, the system wants to proactively inform the user that they are about to do a certain activity, but the WeChat applet passively triggers the notification. limit, the system will not be able to actively push messages.

How to prevent template message push from being restricted?

Breakthrough: "One form submission can issue one message, and the number of messages submitted for multiple submissions is independent and does not affect each other."

In order to break through the push limit of template messages, implement You can push at will within 7 days, as long as you collect enough push codes, which is the formId obtained every time you submit a form. A formId represents the developer's one-time permission to push template messages to the current user.

Client

Collect push code

When the attribute report-submit=true in Form component It means sending a template message, and you can get the formId by submitting the form. Next, we only need to modify the original page, and replace the interface where the user originally bound the click event with the buttonButton Group component in the form component, that is, the bindtap event of the user's interactive click is replaced by the form bindsubmit Instead, capture the user's click event to generate more push codes.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

// 收集推送码

Page({

   formSubmit: funcition(e) {

let formId = e.detail.formId;

this.collectFormIds(formId); //保存推送码

let type = e.detail.target.dataset.type; // 根据type执行点击事件

},

 

   collectFormIds: function(formId) { 

let formIds = app.globalData.globalFormIds; // 获取全局推送码数组

if (!formIds)

           formIds = [];

let data = {

           formId: formId,

           expire: new Data().getTime() + 60480000 // 7天后的过期时间戳

}

       formIds.push(data);

       app.globalData.globalFormIds = formIds;

},

})

Copy after login

Report push code

Waiting for the next time the user initiates a network request, the globalFormIds will be sent to the server.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

// 上报推送码

Page({

   onLoad: funcition(e) {

this.uploadFormIds(); //上传推送码

},

 

   collectFormIds: function(formId) { 

var formIds = app.globalData.globalFormIds; // 获取全局推送码

if (formIds.length) {

            formIds = JSON.stringify(formIds); // 转换成JSON字符串

            app.globalData.gloabalFomIds = ''// 清空当前全局推送码

}

       wx.request({ // 发送到服务器

           url: 'http://xxx',

           method: 'POST',

           data: {

               openId: 'openId',

               formIds: formIds

},

           success: function(res) {

}

});

},

})

Copy after login

Server

Storage push code

High frequency IO, using Redis to store push code.

1

2

3

4

5

6

7

8

9

/**

* 收集用户推送码

*

* @param openId        用户的openid

* @param formTemplates 用户的表单模板

*/

public void collect(String openId, List<FormTemplateVO> formTemplates) {

   redisTemplate.opsForList().rightPushAll("mina:openid:" + openId, formTemplates);

}

Copy after login

Push template message

The following implements the function of group sending, which is similar for specific users.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

/**

* 推送消息

*

* @param templateId 模板消息id

* @param page       跳转页面

* @param keyWords   模板内容

*/

public void push(String templateId, String page, String keyWords) {

String logPrefix = "推送消息";

 

// 获取access token

String accessToken = this.getAccessToken();

 

// 创建消息通用模板

MsgTemplateVO msgTemplateVO = MsgTemplateVO.builder().template_id(templateId).build();

// 跳转页面

   msgTemplateVO.setPage(StringUtils.isNotBlank(page) ? page : "");

// 模板内容

if (StringUtils.isNotBlank(keyWords)) {

String[] keyWordArr = keyWords.split(BaseConsts.COMMA_STR);

Map<String, MsgTemplateVO.KeyWord> keyWordMap = new HashMap<>(8);

for (int i = 0; i < keyWordArr.length; i++) {

MsgTemplateVO.KeyWord keyWord = msgTemplateVO.new KeyWord(keyWordArr[i]);

           keyWordMap.put(MsgTemplateVO.KEYWORD + (i + 1), keyWord);

}

       msgTemplateVO.setData(keyWordMap);

} else {

       msgTemplateVO.setData(Collections.emptyMap());

}

 

// 获取所有用户

List<String> openIdList = minaRedisDao.getAllOpenIds();

 

for (String openId : openIdList) {

// 获取有效推送码

String formId = minaRedisDao.getValidFormId(openId);

if (StringUtils.isBlank(formId)) {

           LOGGER.error("{}>>>openId={}>>>已无有效推送码[失败]", logPrefix, openId);

continue;

}

 

// 指派消息

MsgTemplateVO assignMsgTemplateVO = msgTemplateVO.assign(openId, formId);

 

// 发送消息

Map<String, Object> resultMap;

try {

String jsonBody = JsonUtils.getObjectMapper().writeValueAsString(assignMsgTemplateVO);

 

String resultBody = OkHttpUtils.getInstance().postAsString(messageUrl + accessToken, jsonBody);

           resultMap = JsonUtils.getObjectMapper().readValue(resultBody, Map.class);

catch (IOException e) {

           LOGGER.error("{}>>>openId={}>>>{}[失败]", logPrefix, openId, e.getMessage(), e);

continue;

}

 

if ((int) resultMap.get(ResponseConsts.Mina.CODE) != 0) {

           LOGGER.error("{}>>>openId={}>>>{}[失败]", logPrefix, openId, resultMap.get(ResponseConsts.Mina.MSG));

continue;

}

 

       LOGGER.info("{}>>>openId={}>>>[成功]", logPrefix, openId);

}

}

 

/**

* 根据用户获取有效的推送码

*

* @param openId 用户的openid

* @return 推送码

*/

public String getValidFormId(String openId) {

List<FormTemplateVO> formTemplates = redisTemplate.opsForList().range("mina:openid:" + openId, 0, -1);

 

String validFormId = "";

int trimStart = 0;

 

int size;

for (int i = 0; i < (size = formTemplates.size()); i++) {

if (formTemplates.get(i).getExpire() > System.currentTimeMillis()) {

           validFormId = formTemplates.get(i).getFormId();

           trimStart = i + 1;

break;

}

}

 

// 移除本次使用的和已过期的

   redisTemplate.opsForList().trim(KEY_MINA_PUSH + openId, trimStart == 0 ? size : trimStart, -1);

 

return validFormId;

}

Copy after login

The above solution can send multiple template messages to the user to recall the user within 7 days after the user last used the mini program.

This is all the details on how to implement unrestricted and unlimited active push of WeChat mini program template messages.

Related articles:

WeChat applet message push php server verification

The above is the detailed content of Realize unrestricted and unlimited active push of WeChat mini program template messages. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1255
29
C# Tutorial
1228
24
How to swipe right and reply quickly in iMessage on iOS 17 How to swipe right and reply quickly in iMessage on iOS 17 Sep 20, 2023 am 10:45 AM

How to Use Swipe to Reply in iMessages on iPhone Note: The Swipe to Reply feature only works with iMessage conversations in iOS 17, not regular SMS conversations in the Messages app. Open the Messages app on your iPhone. Then, head to the iMessage conversation and simply swipe right on the iMessage you want to reply to. Once this is done, the selected iMessage will be in focus while all other messages will be blurred in the background. You'll see a text box for typing a reply and a "+" icon for accessing iMessage apps like Check-ins, Places, Stickers, Photos, and more. Just enter your message,

What does it mean when a message has been sent but rejected by the other party? What does it mean when a message has been sent but rejected by the other party? Mar 07, 2024 pm 03:59 PM

The message has been sent but rejected by the other party. This means that the sent information has been successfully sent from the device, but for some reason, the other party did not receive the message. More specifically, this is usually because the other party has set certain permissions or taken certain actions, which prevents your information from being received normally.

iOS 17: How to use emojis as stickers in Messages iOS 17: How to use emojis as stickers in Messages Sep 18, 2023 pm 05:13 PM

In iOS17, Apple has added several new features to its Messages app to make communicating with other Apple users more creative and fun. One of the features is the ability to use emojis as stickers. Stickers have been around in the Messages app for years, but so far, they haven't changed much. This is because in iOS17, Apple treats all standard emojis as stickers, allowing them to be used in the same way as actual stickers. This essentially means you're no longer limited to inserting them into conversations. Now you can also drag them anywhere on the message bubble. You can even stack them on top of each other to create little emoji scenes. The following steps show you how it works in iOS17

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: &lt;!--index.wxml--&gt;&l

The message has been sent but was rejected by the other party. Should I block it or delete it? The message has been sent but was rejected by the other party. Should I block it or delete it? Mar 12, 2024 pm 02:41 PM

1. Being added to the blacklist: The message has been sent but rejected by the other party. Generally, you have been blacklisted. At this time, you will not be able to send messages to the other party, and the other party will not be able to receive your messages. 2. Network problems: If the recipient's network condition is poor or there is a network failure, the message may not be successfully received. At this point, you can try to wait for the network to return to normal before sending the message again. 3. The other party has set up Do Not Disturb: If the recipient has set up Do Not Disturb in WeChat, the sender’s messages will not be reminded or displayed within a certain period of time.

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How to set up Xiaomi Mi 14 Pro to light up the screen for messages? How to set up Xiaomi Mi 14 Pro to light up the screen for messages? Mar 18, 2024 pm 12:07 PM

Xiaomi 14Pro is a flagship model with excellent performance and configuration. It has achieved high sales since its official release. Many small functions of Xiaomi 14Pro will be ignored by everyone. For example, it can be set to light up the screen for messages. Although the function is small, , but it is very practical. Everyone will encounter various problems when using the mobile phone. So how to set up the Xiaomi 14Pro to light up the screen for messages? How to set up Xiaomi Mi 14 Pro to light up the screen for messages? Step 1: Open your phone’s Settings app. Step 2: Swipe down until you find the &quot;Lock screen and password&quot; option and click to enter. Step 3: In the &quot;Lock screen &amp; passcode&quot; menu, find and click the &quot;Turn on screen for notifications&quot; option. Step 4: On the &quot;Turn on screen when receiving notifications&quot; page, turn on the switch to enable

See all articles