-
注册了微信公众号个人订阅号,在设置与开发菜单中选择基本配置菜单,同意成为开发者,获取到公众号相关信息。URL填写服务地址,这个地址必须是外网地址并且是80端口或者443端口,token是可以随意填写,作为一个密码,加密键可以随机生成,消息加密选择明文就可以了。提交后,启用服务器配置。
-
使用natapp穿透内网,natapp基于ngrok的反向代理软件,通过在公网和本地运行的Web服务器之间建立一个安全的通道,可以捕获和分析所有通道上的流量,便于分析和重放。启动服务后记录好服务地址。
# 配置config.ini文件
#将本文件放置于natapp同级目录 程序将读取 [default] 段
#在命令行参数模式如 natapp -authtoken=xxx 等相同参数将会覆盖掉此配置
#命令行参数 -config= 可以指定任意config.ini文件,需要指定获取到的认证码authtoken
[default]
authtoken=xxxxxxxxxxxxxxxx #对应一条隧道的authtoken
clienttoken= #对应客户端的clienttoken,将会忽略authtoken,若无请留空,
log=none #log 日志文件,可指定本地文件, none=不做记录,stdout=直接屏幕输出 ,默认为none
loglevel=ERROR #日志等级 DEBUG, INFO, WARNING, ERROR 默认为 DEBUG
http_proxy= #代理设置 如 http://10.123.10.10:3128 非代理上网用户请务必留空
- 使用pip安装微信的python sdk - wechatpy,python web框架-falcon和wsgi服务器-waitress。创建脚本connection.py。
# -*- coding:utf-8 -*-
import falcon
from falcon import uri
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from wechatpy import parse_message
from wechatpy.replies import TextReply, ImageReply
class Connect(object):
def on_get(self, req, resp):
query_string = req.query_string
query_list = query_string.split('&')
b = {}
for i in query_list:
b[i.split("=")[0]] = i.split("=")[1]
try:
check_signature(token='BhtV9P2Zr1OJJihwNRzPj', signature=b['signature'], timestamp=b['timestamp'], nonce=b['nonce'])
resp.body = (b['echostr'])
except InvalidSignatureException:
pass
resp.status = falcon.HTTP_200
def on_post(self, req, resp):
xml = req.stream.read()
msg = parse_message(xml)
# 拿到用户的文本或图片,原样返回
if msg.type == 'text':
reply = TextReply(content=msg.content, message=msg
xml = reply.render()
resp.body = (xml)
resp.status = falcon.HTTP_200
elif msg.type == 'image':
reply = ImageReply(media_id=msg.media_id, message=msg)
xml = reply.render()
resp.body = (xml)
resp.status = falcon.HTTP_200
app = falcon.API()
connect = Connect()
app.add_route('/connect', connect)
代码写好后,启动程序:
waitress-serve --port=80 connect:app