1、接入校驗,這里我用的是Python3,在執行 pip install web.py 安裝 web.py 的時候報錯,改為 pip install web.py==0.40.dev0 即可正常安裝
# -*- coding: utf-8 -*-
import web
import hashlib
urls = (
'/wx', 'Check',
)
class Check(object):
def GET(self):
try:
data = web.input()
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr=data.echostr
token = "yufu" #這里要與微信公眾平台基本配置中的Token保持一致
list = [token, timestamp, nonce]
# 對token、timestamp和nonce按字典排序
list.sort()
# 將排序后的結果拼接成一個字符串
list = ''.join(list)
# 對結果進行sha1加密
hashcode = hashlib.sha1(list.encode('utf8')).hexdigest()
# 加密結果如果與微信服務器發送過來的簽名一致,則校驗通過,原樣返回echostr,否則返回空
if hashcode == signature:
return echostr
else:
return ''
except Exception:
return Exception
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
代碼完成之后運行

2、填寫服務器配置,URL填入域名加“/wx”,Token要與代碼中的token一致,點擊提交。

在這之前我提交多次,老是顯示連接URL超時,后來發覺問題出在sha1加密。原先我加密的代碼是 hashcode = hashlib.sha1(list).hexdigest(),沒有指定要加密的字符串的字符編碼,改為 hashcode = hashlib.sha1(list.encode('utf8')).hexdigest() 即可。
