Flask+腾讯云windows主机快速搭建微信公众号接口

0x00

在腾讯云官网https://cloud.tencent.com注册认证后可以免费领取一个月的云主机使用,本例中选用的是windows server2012

0x01

主要代码 first.py 提供简单重复会话

 1 # -*- coding=utf-8 -*-
 2 import time
 3 from flask import Flask,request,g,make_response
 4 import hashlib
 5 import xml.etree.ElementTree as ET
 6 
 7 app = Flask(__name__)
 8 
 9 
10 @app.route('/wx',methods=['GET','POST'])
11 def wechat_auth():
12     if request.method == 'GET':
13         token='yourtoken' #微信配置所需的token
14         data = request.args
15         signature = data.get('signature','')
16         timestamp = data.get('timestamp','')
17         nonce = data.get('nonce','')
18         echostr = data.get('echostr','')
19         s = [timestamp,nonce,token]
20         s.sort()
21         s = ''.join(s)
22         if (hashlib.sha1(s).hexdigest() == signature):
23             return make_response(echostr)
24     else:
25         rec = request.stream.read()
26         xml_rec = ET.fromstring(rec)
27         tou = xml_rec.find('ToUserName').text
28         fromu = xml_rec.find('FromUserName').text
29         content = xml_rec.find('Content').text
30         xml_rep = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"
31         response = make_response(xml_rep % (fromu,tou,str(int(time.time())), content))
32         response.content_type='application/xml'
33         return response
34     return 'Hello weixin!'
35 
36 if __name__ == '__main__':
37     app.run(host='0.0.0.0',port=80)

0x02

在主机上安装python,并pip安装flask(不设置python全局变量时可以在python安装目录下的script下运行,tips:在目录下按shift+右键可快速打开在当前目录的cmd)

0x03

使用IIS部署flask项目详见 https://segmentfault.com/a/1190000008909201(部署成功后会在文件夹下生成python的编译文件.pyc,当部署新的项目时先在iis上停止服务器,删除掉目录下.pyc文件,然后再开启服务器)

0x04

腾讯云的公网ip访问时只允许iis的80端口服务,部署时将项目部署到80端口上

0x05

在微信公众平台中设置接口的url和token(注意与代码中的token保持一致url为http://你的主机的公网ip/),提交若提示系统错误一般是接口服务器无法通过公网ip进行访问,提示token验证失败时注意设置的token保持一致。

0x06

在微信上测试。。

原文地址:https://www.cnblogs.com/QQQmadNULL/p/6906383.html