- 論壇徽章:
- 0
|
將我們的服務(wù)器放在新浪云上,搭建微信公眾賬號,下面的代碼將實現(xiàn)獲取微信token,實現(xiàn)最簡單的消息對話(用戶說什么,我們回復(fù)什么)。
因為網(wǎng)上有的代碼有錯,所以將這個傳上來供大家借鑒
注意,代碼中的空格不能多,會出錯,要嚴格縮進對齊,然后使用下面的代碼一定是無錯的。
下面文件依次為:
第一個代碼文件是index.wsgi 文件 ,它是啟動服務(wù)的文件
第二個代碼文件是config.yaml文件 , 配置文件
第三個代碼文件是meishidaren.py 文件,用于由微信開發(fā)模式獲取url 和 token,同時可以與用戶實現(xiàn)簡單通信
[Python]代碼- import sae
- from meishidaren import app
- application = sae.create_wsgi_app(app)
復(fù)制代碼 [Python]代碼- name: gourmetmaster
- version: 1
復(fù)制代碼 meishidaren.py- import time
- from flask import Flask,g,request,make_response
- import hashlib
- import xml.etree.ElementTree as ET
- app = Flask(__name__)
- app.debug=True
- @app.route('/',methods=['GET','POST'])
- def wechat_auth():
- if request.method == 'GET':
- token='liusicong'
- data = request.args
- signature = data.get('signature','')
- timestamp = data.get('timestamp','')
- nonce = data.get('nonce','')
- echostr = data.get('echostr','')
- s = [timestamp,nonce,token]
- s.sort()
- s = ''.join(s)
- if (hashlib.sha1(s).hexdigest() == signature):
- return make_response(echostr)
- else:
- rec = request.stream.read()
- xml_rec = ET.fromstring(rec)
- tou = xml_rec.find('ToUserName').text
- fromu = xml_rec.find('FromUserName').text
- content = xml_rec.find('Content').text
- 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>"
- response = make_response(xml_rep % (fromu,tou,str(int(time.time())), content))
- response.content_type='application/xml'
- return response
復(fù)制代碼 |
|