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

在微信上測試。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM