微信系列之公眾號Token
驗證
python3
安裝web.py
可以選擇安裝``pip install web.py==0.40.dev0`
pycharm
連接線上服務器開發
1.打開pycharm
> Tools
> Deployment
1.添加服務
2.選擇SFTP
3.配置信息
1.遠程主機地址和商品
2.根主機地址
3.配置用戶名和密碼,可以選擇ssh
文件
4.**項目配置文件setting
里設置以連接遠程解釋器
token
驗證
官方文檔中map(sha1.update, list)
是無法對sha1進行持續更新哈希值,實驗過后其值仍是空字符串的哈希的值,且sha1.update
方法需要TypeError: Unicode-objects must be encoded before hashing
微信signature
,nonce
,echostr
參數如下:
參數 | 描述 |
---|---|
signature |
微信加密簽名,signature結合了開發者填寫的token參數和請求中的timestamp參數、nonce參數。 |
timestamp |
時間戳 |
nonce |
隨機數 |
echostr |
隨機字符串 |
驗證方法
1.服務器端獲取token
,nonce
,timestamp
組成列表
2.列表排序
3.排序后的元素進行摘要
4.摘要比對signature
5.響應echostr
# coding: utf-8
# filename: handle.py
import web
import hashlib
class Handle(object):
def GET(self):
"""
signature 微信加密簽名,signature 結合了開發者的
token和請求的 timestamp 與nonce
token 時間戳
nonce 隨機數
echostr 隨機字符串
:return:
"""
try:
# 請求無參數,即非 token 驗證
data = web.input()
if len(data) == 0:
return "Hello, This is handle views"
signature = data.signature
nonce = data.nonce
timestamp = data.timestamp
echostr = data.echostr
token = "******" # 基本配置的 token 填寫一樣的值
# 對 token timestamp nonce 進行排序后進行摘要
sha1_list = [token, timestamp, nonce]
sha1_list.sort()
sha1 = hashlib.sha1()
list(map(lambda s: sha1.update(s.encode('utf-8')), sha1_list))
hashcode = sha1.hexdigest()
print('func: hashcode, signature: {} {}'.format(hashcode, signature))
if hashcode == signature:
return echostr
else:
return ""
except Exception as e:
return e.reason