小程序统一服务消息 小程序订阅消息 Python

注意:新发布的小程序不在支持统一服务消息,需要使用订阅消息功能

小程序模板消息接口将于2020年1月10日下线,开发者可使用订阅消息功能

 

1。获取模板id

首先要公众平台 登录上小程序管理平台

找到订阅消息》 添加我的模

 

添加一个 获取到模板id

如: -QQQNKEVORnwRUmwotyQQoZ_ObaSjkA44Qfn6AtIJUx

小程序统一服务消息 小程序订阅消息 Python

2 ,授权

https://developers.weixin.qq.com/miniprogram/dev/api/open-api/subscribe-message/wx.requestSubscribeMessage.html

通过微信 api wx.requestSubscribeMessage(Object object)

用户授权模板可以推送消息

 

3 .服务端发送模板消息

subscribeMessage.send

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

 

 

# todo 获取access_token

def get_token():

# APPID, SECRET = 'wx8fe512646732596d', '8725fc1e12b9750e3c90a38d3201dec2'

url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(APPID,

SECRET)

respon = requests.get(url)

content = respon.content

 

content = content.decode('utf-8')

data = json.loads(content)

return data.get("access_token")

 

 

# 微信模板

MessageTemplates = ["-QQQNKEVORnwRUmwotyQQoZ_ObaSjkA44Qfn6AtIJUg",]

 

def subscribeMessage_send(touser,template_id=MessageTemplates[0],json_data=None,page=None):

"""订阅消息发送服务消息"""

# https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html#HTTPS%20调用

token = get_token()

if not token:

return False

url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={}".format(token)

 

data = {}

data["touser"] = touser

data["template_id"] = template_id

data["miniprogram_state"] = "formal"

 

if page:

data["page"] = page

 

data["data"] = json_data

try:

response = requests.post(url,json=data,)

content = response.content.decode('utf-8')

data = json.loads(content)

print(data)

return data

except Exception as e:

return {'errcode': 2, 'errmsg': '通信失败'}

 

测试:

 

json_data= {

"thing1": {

"value": "339208499"

},

"thing2": {

"value": "TIT创意园"

},

"date3": {

"value": "2015年01月05日"

}}

subscribeMessage_send("o_Ezd4km_mrPxdMJ19ff0oU8ASuA", template_id=MessageTemplates[0], json_data=json_data, page="pages/today/today")