This article mainly uses Python to implement a simple call to WeChat applet to subscribe to the message interface.

Call step

1. Get access_token
2. Call the subscription message delivery interface

I won’t talk about getting access_token here. You can get it by calling the interface directly. Here it is mainly for sending subscription messages. Because of the complete and available business code, obtaining access_token also requires some professional processing, such as caching access_token, verifying the validity period of access_token, etc.

Call code

import requests
import json

# json数据格式请求参数
data = {
  "touser": "o9usm0bhIkcbAyxM0RzDXi9tjHhM", # 接收用户的openid
  "template_id": "WZiCliW1zVtHXqX7dGnFNvFO4Bx3MOSjPRA7LAcwQuw", # 模板id
  "page": "pages/index/index",
  "miniprogram_state":"formal",
  "lang":"zh_CN",
  "data": {
      "character_string1": {
          "value": "2021-08-01"
      },
      "thing4": {
          "value": "Python推送小程序订阅消息"
      }
  }
}

# 设置请求头
header = {'Content-Type': 'application/json'}
# 请求地址
url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=获取到的access_token"
# 请求体
response = requests.post(url, headers=header, data = json.dumps(data))
# 打印请求结果
print(response.text)

image.png

Returning the following json means the delivery is successful

{"errcode":0,"errmsg":"ok","msgid":1983688405318189057}

image.png
image.png

The official document of the WeChat applet is attached here, and the above related parameters can be found in the document to understand its purpose

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html

Combined with GUI

Friends with strong hands-on ability can also combine with Python's own GUI library Tkinter to implement a simple operation interface. Because the access_token is only valid for 2 hours and the number of generations per day is limited, we cannot generate a new access_token every time a message is pushed, otherwise, the number of generations is exhausted and you will not be able to call the interface to send messages.

Therefore, the access_token should be cached locally or in the database, and then each time the subscription message interface is called, the validity period of the access_token is judged. If it has not expired, you can use the locally cached access_token. If it has expired, call the interface to generate a new access_token. , So that the number of access_token calls per day is basically sufficient.

image.png

Author:TANKING
WeChat:sansure2016


TANKING
4.8k 声望541 粉丝

热爱分享,热爱创作,热爱研究。