In the general process, the user performs shopping and other operations in the mini program, and the mini program pops up an authorization popup to request user authorization. After authorization is successful, the Server can send messages to the user through the API of wechat

The official documentation

Key steps

Selecting a message template

Go into the applet background and select subscribe message templates, each of which provides a specific style

Template Application for Authorization

wx.requestSubscribeMessage({
  tmplIds: ['Wi1RBTvrTxGgWm3tfbLj_hy8ItGF_YW72QohcGNSPyE'.'jhN393J2oMKUO_6vPjUJF9iSASrNBN42i1sTmHMRuvY'.'wgkRJwfhkBXZkAyO4P0xO-7rLMkN7t-bQMwfpfnhqA0'].success(res) {
    console.log(res); }});Copy the code

The user should see the following effect:

Send messages through the Server

Server interface documentation: developers.weixin.qq.com/miniprogram…

Access token

You can obtain the token through the following tools of the wechat development platform

Mp.weixin.qq.com/debug/cgi-b…

To obtain the openid

Developers.weixin.qq.com/miniprogram…

wx.login({
  success (res) {
    if (res.code) {
      // Initiate a network request
      wx.request({
        url: `https://api.weixin.qq.com/sns/jscode2session?appid=xxx&secret=xxx&js_code=${res.code}&grant_type=authorization_code`.data: {
          code: res.code
        }
      }).then(res= > {
        console.log(res); })}else {
      console.log('Login failed! ' + res.errMsg)
    }
  }
})
Copy the code

Send the sample

curl --location --request POST 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=39_6R8c2NgR8mvb6ju9nXXFLuzdpH3yZdlWdHG8geNPvxsvl7 VBvucOct2K5--lQRd2BNObfzsi4wjIVj9Gd-vY8CaV9R3xdtR20np6yH_3hEd6LQSTOp-otcrwUnA44EV9kie0icgGk8k-vGcIDBWjADASQL' \ --header  'Content-Type: application/json' \ --data-raw '{ "touser": "oS2PW5fRasqF0GW6qwuK3BsDORqQ", "template_id": "Wi1RBTvrTxGgWm3tfbLj_hy8ItGF_YW72QohcGNSPyE", "lang": "zh_CN", "data": { "time1": { "value": "The 2019-11-09 21:43"}, "amount2" : {" value ": 9999999999}," phrase3 ": {" value" : "withdrawal success"}}} 'Copy the code

tips

A one-off template and a long-term template cannot be authorized at the same time

{errCode: 20002.errMsg: "requestSubscribeMessage:fail Templates type must be same"}
Copy the code