微信系列之公衆號Token驗證

微信系列之公衆號Token驗證


python3安裝web.py能夠選擇安裝`pip install web.py==0.40.dev0python

pycharm鏈接線上服務器開發

1.打開pycharm > Tools > Deployment

1.添加服務
2.選擇SFTP
3.配置信息
1.遠程主機地址和商品
2.根主機地址
3.配置用戶名和密碼,能夠選擇ssh文件
4.**項目配置文件setting裏設置以鏈接遠程解釋器web


token驗證

官方文檔中map(sha1.update, list)是沒法對sha1進行持續更新哈希值,實驗事後其值還是空字符串的哈希的值,且sha1.update方法須要TypeError: Unicode-objects must be encoded before hashing服務器

微信signaturenonceechostr參數以下:微信

參數 描述
signature 微信加密簽名,signature結合了開發者填寫的token參數和請求中的timestamp參數、nonce參數。
timestamp 時間戳
nonce 隨機數
echostr 隨機字符串

微信圖片

驗證方法
1.服務器端獲取token,nonce,timestamp組成列表
2.列表排序
3.排序後的元素進行摘要
4.摘要比對signature
5.響應echostrssh

# 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

參考資料

相關文章
相關標籤/搜索