当普通用户想公众号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL上。

微信的可以收到用户的消息类型分文本、图片、语言、视频、小视频、地理位置和链接,所对应的MsgType分别为[text,image,voice,video,shortvideo,location,link]。

请注意:
1、关于重试的消息排重,推荐使用msgid排重。
2、微信服务器在五秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次。假如服务器无法保证在五秒内处理并回复,
可以直接回复空串,微信服务器不会对此作任何处理,并且不会发起重试。详情请见“发送消息-被动回复消息”。
3、如果开发者需要对用户消息在5秒内立即做出回应,即使用“发送消息-被动回复消息”接口向用户被动回复消息时,可以在
公众平台官网的开发者中心处设置消息加密。开启加密后,用户发来的消息和开发者回复的消息都会被加密(但开发者通过客服
接口等API调用形式向用户发送消息,则不受影响)。关于消息加解密的详细说明,请见“发送消息-被动回复消息加解密说明”。

微信收到的消息类型结构
微信被动回复的消息类型结构

微信文本自动回复

我们以微信的文本消息类型做为列子说明。
首先我们来看看文本消息的XML结构个说明

<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId></xml>
参数 描述
ToUserName 开发者微信号
FromUserName 发送方帐号(一个OpenID)
CreateTime 消息创建时间 (整型)
MsgType text
Content 文本消息内容
MsgId 消息id 64位整型

由于POST过来的是XML类型我数据,所以我们首要做的就是做xml解析。Python中自带了xml解析模块了。就直接导入进行解析

import xml.etree.cElementTree as etxmldata = '''<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId></xml>'''xml_rec = et.fromstring(xmldata)ToUserName = xml_rec.find('ToUserName').text
fromUser = xml_rec.find('FromUserName').text
MsgType = xml_rec.find('MsgType').text
Content = xml_rec.find('Content').text
MsgId = xml_rec.find('MsgId').textprint(ToUserName, fromUser ,MsgType ,Content, MsgId)

打印结果

toUser fromUser text this is a test 1234567890123456

解析了xml之后,我们就要给用户回消息。我们回复的消息也是xml类型

<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
参数 是否必须 描述
ToUserName 接收方帐号(收到的OpenID)
FromUserName 开发者微信号
CreateTime 消息创建时间 (整型)
MsgType text
Content 回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)

回复消息的时候需要注意一点,就是我们回复给用户的ToUserName和FromUserName和接收到的应该是相反的,就是邮件的发送一样。
新建一个muban.py

text_str = '''<xml><ToUserName>![CDATA[%s]]</ToUserName><FromUserName>![CDATA[%s]]</FromUserName><CreateTime>%s</CreateTime><MsgType>![CDATA[text]]</MsgType><Content>![CDATA[%s]]</Content></xml>'''def reply_muban(type):if type == 'text':return text_str

打开我们之前的main.py,导入模板,添加xml解析代码和返回代码,由于是POST过来的,所以我们需要做POST判断

# -*- coding:utf-8 -*-from flask import Flask,request
from time import time
import xml.etree.ElementTree as et
import mubanimport hashlibapp = Flask(__name__)
app.debug = True@app.route('/wx_flask',methods=['GET','POST'])
def wechat():if request.method == 'GET':token = 'xiaoqingxin'data = request.argssignature = data.get('signature','')timestamp = data.get('timestamp','')nonce = data.get('nonce','')echostr = data.get('echostr','')list = [token, timestamp, nonce]list.sort()s = list[0] + list[1] + list[2]hascode = hashlib.sha1(s.encode('utf-8')).hexdigest()if hascode == signature:return echostrelse:return ""if request.method == 'POST':xmldata = request.argsxml_rec = et.fromstring(xmldata)ToUserName = xml_rec.find('ToUserName').textfromUser = xml_rec.find('FromUserName').textMsgType = xml_rec.find('MsgType').textContent = xml_rec.find('Content').textMsgId = xml_rec.find('MsgId').textreturn muban.reply_muban(MsgType) % (fromUser, ToUserName, int(time()), Content)if __name__ == '__main__':app.run()

现在来运行我们的代码,在公众号中发送消息就可以收到回复了。

可以看到我这里还有其他的回复,我把代码贴下,和文本回复差不多。

muban.py

# -*- coding:utf-8 -*-text_str = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>"img_str = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[%s]]></MediaId></Image></xml>"image_text_lj = "<ArticleCount>%s</ArticleCount><Articles>%s</Articles></xml>"
image_text_item = "<item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item>"def reply_muban(type):if type == "text":return text_strelif type == "image":return img_strdef image_text_new_muban(itemDic):items = ""for item in itemDic:items += image_text_item % (item['Title'], item['Description'], item['PicUrl'], item['Url'])return image_text_str + (image_text_lj % (len(itemDic), items))

main.py

 if request.method == 'POST':str_xml = request.stream.read()xml = etree.fromstring(str_xml)msgType = xml.find("MsgType").textxml_muban = muban.reply_muban(msgType)if msgType == "text":content = xml.find("Content").textfromUser = xml.find("FromUserName").texttoUser = xml.find("ToUserName").textreturn xml_muban % (fromUser, toUser, int(time()), content)elif msgType == "image":fromUser = xml.find("FromUserName").texttoUser = xml.find("ToUserName").textmediaid = xml.find("MediaId").textprint(xml_muban % (fromUser, toUser, int(time()), mediaid))return xml_muban % (fromUser, toUser, int(time()), mediaid)else:itemDic = [{'Title':'Title','Description':'Description','PicUrl':'https://ss0.baidu.com/73x1bjeh1BF3odCf/it/u=3705265267,3767781981&fm=85&s=DE0A5C2A7D264E1B62FD99CB0300C0B1','Url':'www.baidu.com'},{'Title':'Title1','Description':'Description1','PicUrl':'https://ss0.baidu.com/73x1bjeh1BF3odCf/it/u=3705265267,3767781981&fm=85&s=DE0A5C2A7D264E1B62FD99CB0300C0B1','Url':'www.baidu.com'}]fromUser = xml.find("FromUserName").texttoUser = xml.find("ToUserName").textmediaid = xml.find("MediaId").textreturn muban.image_text_new_muban(itemDic) % (fromUser, toUser, int(time()))if __name__ == '__main__':app.run()

微信收到的消息类型结构
微信被动回复的消息类型结构

Python3-Flask-微信公众号开发-3相关推荐

  1. Flask 微信公众号开发

    公众号接口 1. 公众号消息会话 目前公众号内主要有这样几类消息服务的类型,分别用于不同的场景. 群发消息 公众号可以以一定频次(订阅号为每天1次,服务号为每月4次),向用户群发消息,包括文字消息.图 ...

  2. python 微信公众号开发[1] 后台服务器端配置与公众号开发配置

    更新时间:2020年3月7日 微信公众号开发的硬件必备条件:(1)申请一个公众号 (2)有公网ip的服务器(最好是阿里云,腾讯云等的云服务器)(3)解析到(2)中服务器地址的域名(阿里云,腾讯云购买即 ...

  3. Python微信公众号开发平台

    上大学的时候,对微信公众号开发浅尝辄止的玩了一下,感觉还是挺有意思的. //www.jb51.net/article/133677.htm后来服务器到期了,也就搁置了.由于发布web程序,使用PHP很 ...

  4. Python微信公众号开发

    摘要: 大三上的时候,对微信公众号开发浅尝辄止的玩了一下,感觉还是挺有意思的.http://blog.csdn.net/marksinoberg/article/details/54235271 后来 ...

  5. 基于python的微信公众号开发

    最近想自学服务器方面的知识,用微信公众号开发来练手.阅读了一些文章,实践以后总结一下. 租了腾讯云服务器,操作系统为 Ubuntu Server 14.04.1 LTS 64位,分配了一个公网IP地址 ...

  6. 微信公众号开发的一些方法总结

    概述 微信公众号开发,其实就是微信使用者.微信公众号平台和自身服务器的http消息交互:在这一系列过程中,微信公众号平台充当了中介和转发作用(如图1所示).需要注意的是,微信公众号平台向自身服务器转发 ...

  7. python微信公众号开发教程_python微信公众号开发简单流程实现

    本文为大家分享了python微信公众号开发的简单过程,供大家参考,具体内容如下 网上有很多微信公众号的开发教程,但是都是好几年前的了,而且很多都是抄袭其他人的,内容几乎一模一样.真的无语了.只好自己总 ...

  8. 使用Python进行微信公众号开发(二)接收消息

    写在前面 <使用Python进行微信公众号开发>系列文章将与大家分享如何使用Python一步步搭建微信公众号后台服务器. 效果体验 扫码"是雯子吖"公众号进行体验 配置 ...

  9. 微信公众号开发本地环境开发_如何在5分钟内使HTTPS在本地开发环境上工作

    微信公众号开发本地环境开发 Almost any website you visit today is protected by HTTPS. If yours isn't yet, it shoul ...

  10. 微信公众号开发用书php,php微信公众号开发(3)php实现简单微信文本通讯

    <PHP实战:PHP微信公众号开发(3)PHP实现简单微信文本通讯>要点: 本文介绍了PHP实战:PHP微信公众号开发(3)PHP实现简单微信文本通讯,希望对您有用.如果有疑问,可以联系我 ...

最新文章

  1. python decorator ssh_Python库现后门 可窃取用户SSH信息
  2. html应用模板,HTML5--应用网页模板
  3. 第二章:方法区和运行时常量池溢出
  4. mysql 2005开发版,SQL server 2019 开发版下载
  5. windows2003安全设置
  6. linux x64 ffmpeg,ffmpeg编译arm64动态包
  7. matlab 局部图放大或缩小
  8. Spring Boot异常处理
  9. SIP中第三方呼叫控制(3PCC)建立流程
  10. Windows编程 第七回 绘图课(上)
  11. 生成手写文字图片_如何把手机图片转成PDF文件?这个技巧你一定能学会!
  12. [LeetCode] Balanced Binary Tree 平衡二叉树
  13. 1 100的奇数和编程php,用PHP求出1—100中的基数之和,偶数之和
  14. 关于sematic segmentation的几篇论文(二)
  15. 126邮箱stmp服务器,网易邮箱设置海外服务器 打造海外邮件快车道
  16. 第三章 输入验证----tapestry教程Enjoying Web DevelopmenEnjoying Development翻译
  17. Java使用POI实现导出Word文档
  18. adb命令查看手机电量_使用adb命令查看电池电量信息
  19. 各类工控软件图库(组态王,威纶通,西门子,昆仑通泰等通用
  20. 【操作系统】“哲学家进餐”问题

热门文章

  1. GIS与地质灾害评价
  2. JQuery对DOM的操作【三】
  3. 阿里巴巴面试资源汇总。
  4. 智能外呼系统助力全行业销售自动化
  5. dockerfile创建镜像与容器卷与容器查看
  6. Linux内存 mem 和 swap
  7. 合成孔径雷达干涉测量InSAR数据处理、地形三维重建、形变信息提取、监测等实践技术应用
  8. python:math模块的应用
  9. BOS金蝶云星空二开常用接口插件
  10. 为什么建议大家用 Linux 开发?爽啊!