微信系列之公眾號Token驗證


微信系列之公眾號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

微信signaturenonceechostr參數如下:

參數 描述
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


參考資料


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM