This article is related to the code address: github original link: original link

Type of applets message push

  • Subscribe to news
  • Template message
  • Unified Service message
  • The news of the service

Because the template message has been taken offline, the example message here is a subscription message

To implement subscription messages, we need to know the parameter values of several small programs

  • Small program appid

  • Applets key

  • Applet subscription template ID (template_id)

All of the above parameters can be found in the applets management back – up

The small program end

  • Before development, you need to obtain the template ID of the small program setting. If there is no template setting message, you can add a new template mp.weixin.qq.com

  • After you have the TEMPLATE ID, you need to obtain the permission to deliver messages

The user has the permission to deliver push messages

When the order or other operations are completed, the client applet subscription message interface is activated to obtain the user operation results

// index. WXML <button bindtap="bindSubscribeMessage"> wx.requestSubscribeMessage({ tmplIds: ['tmplIds'], success (res) { console.log(res) } }) }Copy the code

Transfer user code

Since the message push server needs the small program OpenID, we need to send the code to the server through the wx.login login applet

bindLogin() {
  2. The development server requests the wechat server to obtain openID */ through code + appID + secret
  wx.login({
    success: res= > {
      if (res.code) {
        const { task } = this.data;
        this.request(Object.assign(task, { code: res.code })); }}}); }Copy the code

The service side

Since you are emulating the server here, using Koa to implement the basic process, the other back-end implementation processes should be the same

Since push messages require the access_token and openID applets, we need to get these two parameters first

Access to the process

Get the small program client pass parameter code

Get the parameter code through the app/send interface of the client

function getBodyMessage(ctx) {
  const { body } = ctx.request;
  return body;
}
Copy the code

To obtain the openid

Obtain the OpenID through code + secret(small program key) + appID

function getOpenId(js_code) {
 return new Promise(resolve= > {
   http(
	{
	  url: `https://api.weixin.qq.com/sns/jscode2session`.method: 'get'.qs: {
    		grant_type: 'authorization_code',
    		js_code,
    		appid: APP.appid,
    		secret: APP.secret
    	},
    	json: true // Set the data returned to JSON
     },
     (error, response, body) => {
    	if(! error && response.statusCode ==200) { resolve(body); }}); }); }Copy the code

Get access_token

function getAccessToken() {
	return new Promise(resolve= > {
		http(
			{
				url: `${WX_API}/token`.method: 'get'.qs: {
					grant_type: 'client_credential'.// Pay attention to type
					appid: APP.appid,
					secret: APP.secret
				},
				json: true // Set the data returned to JSON
			},
			(error, response, body) => {
				if(! error && response.statusCode ==200) {
					const{ access_token } = body; resolve(access_token); }}); }); }Copy the code

Push message

After we obtain the OpenID and access_token, we can push the message to the user

function sendMessage({ access_token, openid, msg }) {
	const requestData = {
		touser: openid,
    template_id: APP.template_id,
    // Template message attributes and attribute values need to be aware of content limitations
		data: {
			thing1: {
				value: msg.taskName
			},
			thing10: {
				value: msg.remarks
			},
			thing9: {
				value: msg.className
			}
		}
  };
  console.log(requestData);
	return new Promise((resolve, reject) = > {
		http(
			{
			    // Note that access_token needs to be passed in interface form
				url: `${WX_API}/message/subscribe/send? access_token=${access_token}`.headers: {
					'content-type': 'application/json'
				},
				method: 'post'.body: requestData, // Make sure you place it on the body, not the form
				json: true // Set the data returned to JSON
			},
			(error, response, body) => {
				if(! error && response.statusCode ==200) {
					resolve(body);
				} else{ reject(); }}); }); }Copy the code

Here we need to note:

  • Note The content limits of subscription message parameter values are required for the delivered message template

  • Pay attention to delivering template message attributes

  • In development mode, an authorization message is sent once

  • The back-end startnpm run dev

Implementation effect

The 2020-03-05 update

There are two types of templates in the applets template message

  • One-time subscription
  • Subscribe for a long time

The two templates are differentiated according to the service types of the mini program. Only part of the service types are: offline services such as medical care, people’s livelihood, transportation and education are open for long-term subscription template library selection.

A community post details some of the differences


Welcome to pay attention to the public number, we communicate and progress together.