微信公众号推送如何写代码

2023-12-12 21:00:29 浏览数 (2)

写微信公众号推送的代码需要用到微信公众平台提供的开发者文档和API接口。以下是一个示例代码,包含了获取用户信息和回复文本消息:

python☟☟☟☟☟☟

代码语言:javascript复制
import hashlib
import xml.etree.ElementTree as ET
import requests

# 设置接口密钥和Token
api_secret = "your_api_secret"
token = "your_token"

# 验证签名
def check_signature(signature, timestamp, nonce):
    tmp_arr = [token, timestamp, nonce]
    tmp_arr.sort()
    tmp_str = ''.join(tmp_arr)
    sha1_str = hashlib.sha1(tmp_str.encode()).hexdigest()
    return sha1_str == signature

# 处理事件推送
def handle_event(request):
    xml_str = request.data.decode()
    root = ET.fromstring(xml_str)
    if root.find('Event').text == 'subscribe':
        openid = root.find('FromUserName').text
        # 获取用户信息
        user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"
        user_info_url = user_info_url.replace("ACCESS_TOKEN", get_access_token())
        user_info_url = user_info_url.replace("OPENID", openid)
        user_info = requests.get(user_info_url).json()
        # 回复文本消息
        reply_xml = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>"
        reply_xml = reply_xml % (openid, root.find('ToUserName').text, str(int(time.time())), "欢迎关注,"   user_info['nickname'])
        return reply_xml

# 获取access_token
def get_access_token():
    access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
    access_token_url = access_token_url.replace("APPID", api_appid)
    access_token_url = access_token_url.replace("APPSECRET", api_secret)
    access_token = requests.get(access_token_url).json()['access_token']
    return access_token

# 接收微信服务器的请求
@app.route('/wechat', methods=['GET', 'POST'])
def handle_wechat():
    signature = request.args.get('signature')
    timestamp = request.args.get('timestamp')
    nonce = request.args.get('nonce')
    if check_signature(signature, timestamp, nonce):
        if request.method == 'GET':
            return request.args.get('echostr')
        else:
            return handle_event(request)

if __name__ == '__main__':
    app.run()

需要注意的是,以上示例代码是使用Flask框架编写,如果你使用其他框架,需要根据框架需要进行相应的调整。同时,代码中的your_api_secret和your_token需要替换成自己的密钥和Token。

0 人点赞