本章内容主要阐述如何通过Python语言来实现微信公众号客服消息的推送,包括文本信息以及媒体信息(picture,voice,video等),其他方式可参考腾讯官方文档 https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
实现思路:
- 上微信公众号平台注册一个微信公众号测试号,链接:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
- 获取微信公众号的appID 和appsecret(在微信公众号平台上注册微信公众号后即可查看到)
- 获取公众号的access_token值,access_token是公众号全局唯一接口调用凭据,公众号调用各接口时都需要使用access_token。该值目前有效期限是每2小时,超过2小时后需重新获取,且每天仅可获取2000次。
api接口:
接口调用请求说明
https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
- 获取设备的opend_id。opend_id为关注公众号粉丝(有关注公众号的微信账号)的用户id,想要给粉丝发消息,就必须要获取到粉丝的open_id
- 根据微信公众号平台上给的api接口使用方法,调用对应的api接口给粉丝发送不同类型的消息。(详情请见微信公众号官方文档)
API接口:
http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN
下列代码示例是通过“客服消息”接口来实现给粉丝发送消息。
# -*- encoding:utf-8 -*-
import requests
import json
class SendMessage():
def __init__(self):
self.appID = 'xxxx'
self.appsecret = 'xxxx'
self.access_token = self.get_access_token()
self.opend_ids = self.get_openid()
def get_access_token(self):
"""
获取微信公众号的access_token值
"""
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.\
format(self.appID, self.appsecret)
print(url)
headers = {
'U