Implement WeChat applet template message Unrestricted, unlimited active push

Source: Internet
Author: User
Tags call back openid php server

Requirements background

Based on the notification channel, the applet provides the developer with the ability to effectively reach the user's template message, triggered by the user's interaction with the applet page, the service notification in the chat list can quickly enter the view message, click to view the details can also jump to the message of the Small program designated page.

The applet allows the conditions for issuing template messages to be divided into two categories: payment or submission of forms. By submitting a form to the template message is limited to "allow developers to push a limited number of users within 7 days of the template message (1 Submission form can be issued 1, multiple submissions of the next number of independent, not affect each other)".

However, it is obviously not enough to push 1 notifications within 7 days of a user 1-time trigger. For example, the check-in function uses the push of the template message to remind the user to sign in every day, only to get the opportunity to push the template message once the user sign in the previous day, and then use it to send a check-in reminder to the user. However, in many cases, the user forgot to sign in one day, the system loses the user's permission, causing the user to disconnect from the contact; For example, the system would like to proactively inform users of the upcoming activity, however, due to the small program passive trigger notification restrictions, the system will not be able to actively push messages.

How do I make the push of template messages not restricted?

Breach: "1 times submit form can be issued 1, several times to submit the number of independent, mutual not affect"

In order to break through the push limit of the template message, to achieve a willful push within 7 days, just collect enough push code, that is, every time the form is submitted to get the formid. A formid represents a single permission for a developer to push a template message to the current user.

Client

Collect push Codes

When the properties in a form component are report-submit=true, a template message is sent, and the form is submitted to get formid. Next, as long as the original page to be modified, the user originally bound the Click event interface with the form component of the button component to replace, that is, the user's interactive click of the Bindtap event is replaced by the form Bindsubmit, thus capturing the user's Click event to generate more push code.

//collects the Push code page ({formsubmit:funcition (e) {Let formId = E.detail.formid;this.collectformids (formId);//Save push code let type = E. Detail.target.dataset.type; Execute Click event according to type}, Collectformids:function (formId) {Let formids = app.globalData.globalFormIds;//Get Global Push Code array if (!formid s) formids = [];let data = {formid:formid, expire:new data (). GetTime () + 60480000//7 days later       Expiry timestamp} formids.push (data); App.globalData.globalFormIds = Formids;}) 

Escalate push Code

Waits for the next time the user initiates a network request, sends the Globalformids to the server.

//escalated Push code page ({onload:funcition (e) {this.uploadformids ();//Upload Push code}, Collectformids:function (formId) {var formids = App.globalData.globalFormIds; Get global Push Code if (formids.length) {formids = Json.stringify (formids);//Convert to JSON string App.globalData.gloa Balfomids = ";               Empty current global Push Code} wx.request ({//Send to Server URL: ' http://xxx ', Method: ' POST ', data: { OpenID: ' OpenID ', Formids:formids}, Success:function (res) {}});}) 

Service side

Store Push Codes

High-frequency Io, using Redis to store push codes.

/*** collect user Push codes * * @param openid        user's openid* @param formtemplates user's form template */public void Collect (String openId, list< Formtemplatevo> formtemplates) {   redistemplate.opsforlist (). Rightpushall ("Mina:openid:" + OpenID, formtemplates);}

Push template messages

/*** Push Message * * @param templateid template message id* @param page jump page * @param keyWords template content */public void push (String TemplateID, String page, String keyWords) {string logprefix = "Push message";//Get access tokenstring Accesstoken = This.getaccesstoken ();//Create   Message generic template Msgtemplatevo Msgtemplatevo = Msgtemplatevo.builder (). template_id (TemplateID). build ();//Jump page Msgtemplatevo.setpage (Stringutils.isnotblank page) page: "");//template content 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 ());} Get all users list<string> openidlist = Minaredisdao.getallopenids (); for (String openid:openidlist) {//Get valid push code sTring formId = Minaredisdao.getvalidformid (openId), if (Stringutils.isblank (formId)) {Logger.error ("{}&GT;&GT;&G T;openid={}>>> no valid push code [failed], Logprefix, openId); continue;} assigning messages Msgtemplatevo Assignmsgtemplatevo = msgtemplatevo.assign (openId, formId);//Send Message 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={}>>>{}[failed]", Logprefix, OpenId, E.getmessag E (), e); continue;} if ((int) resultmap.get (ResponseConsts.Mina.CODE)! = 0) {logger.error ("{}>>>openid={}>>>{}[failed       ] ", Logprefix, OpenId, Resultmap.get (ResponseConsts.Mina.MSG)); continue;} Logger.info ("{}>>>openid={}>>>[success]", Logprefix, openId);}}/*** get a valid push code based on user * * @param OpenID user's openid* @return push code */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;}} Remove the used and expired redistemplate.opsforlist (). Trim (Key_mina_push + openId, TrimStart = = 0? size:trimstart,-1); return VA Lidformid;}

The above scheme can be implemented in 7 days after the user last used the applet, send multiple template messages to the user to call back the user.

This is all the details of the method of implementing the Applet template message without restriction and unlimited proactive push.

Related articles:

Small program message push PHP server Authentication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.