今天開始使用 Python3 來處理微信公衆號數據,首先進入開發文檔可以看到需要先驗證一下 token ,觀察一下代碼發現是使用 web 框架搭建一個監聽端,收到信息後對幾個數據進行 sha1 計算,比對後來判斷是否是微信消息。
示範代碼對於 python3 來說有一些小地方需要修改,這裏直接貼上修改後的代碼
# -*- coding: utf-8 -*-
# filename: handle.py
import hashlib
import web
class Handle(object):
def GET(self):
try:
data = web.input()
print('data:',data)
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "zangguicheng" #請按照公衆平臺官網\基本配置中信息填寫
list = [token, timestamp, nonce]
list.sort()
#修改代碼如下,在 python2 中,sort 後爲一個列表文件,但在 python3 中爲迭代器,所以需要手動進行拼接。
str1=''
for i in list:
str1 += i
sha1 = hashlib.sha1()
sha1.update(str1.encode('utf-8'))
#拼接之後還需要將他以 utf-8 的編碼格式轉換爲 byte 類型才能進行 sha1 計算
hashcode = sha1.hexdigest()
#以上幾行代碼爲驗證 token 需要修改的代碼
print("handle/GET func: hashcode", hashcode, "signature: ", signature)
if hashcode == signature:
return echostr
else:
return ''
except Exception or Argument:
return Argument
如需要幫忙驗證 token 或是有想要交流微信公衆號開發請加QQ
723831904