1. 程式人生 > >odoo後臺實現微信公眾號驗證

odoo後臺實現微信公眾號驗證

def not append 官網 github targe method sign code

在微信公眾號開發的其中一個步驟是微信服務器調用我們自己的網站驗證身份,這一步微信服務器會傳遞過來4個參數,可是按照官方的寫法,卻無法驗證通過,下面是官方的驗證方法:

import hashlib
import web

class Handle(object):
    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "hello, this is handle view"
            signature 
= data.signature timestamp = data.timestamp nonce = data.nonce echostr = data.echostr token = "xxxx" #請按照公眾平臺官網\基本配置中信息填寫 list = [token, timestamp, nonce] list.sort() sha1 = hashlib.sha1() map(sha1.update, list) hashcode
= sha1.hexdigest() print "handle/GET func: hashcode, signature: ", hashcode, signature if hashcode == signature: return echostr else: return "" except Exception, Argument: return Argument

網上有網友寫的專門的模塊,經過實際驗證可行,現將這部分的代碼單獨抽取如下:

    @http.route(/wechat_public_account_auth/validate, type=http, auth="none", methods=["GET"])
    def validate_auth(self, signature, timestamp, nonce, echostr, **kw):
        token = "guoodoo"  # 請按照公眾平臺官網\基本配置中信息填寫
        list = [token, timestamp, nonce]
        list_data = []
        for data in list:
            list_data.append(self.to_binary(data))
        list_data.sort()
        _delimiter = self.to_binary(b‘‘)
        str_to_sign = _delimiter.join(list_data)
        hashcode = hashlib.sha1(str_to_sign).hexdigest()
        if hashcode == signature:
            return echostr
        else:
            return ""

    def to_binary(self, value, encoding=utf-8):
        """Convert value to binary string, default encoding is utf-8
        :param value: Value to be converted
        :param encoding: Desired encoding
        """
        if not value:
            return b‘‘
        if isinstance(value, six.binary_type):
            return value
        if isinstance(value, six.text_type):
            return value.encode(encoding)

        return self.to_text(value).encode(encoding)

    def to_text(self, value, encoding=utf-8):
        """Convert value to unicode, default encoding is utf-8
        :param value: Value to be converted
        :param encoding: Desired encoding
        """
        if not value:
            return ‘‘
        if isinstance(value, six.text_type):
            return value
        if isinstance(value, six.binary_type):
            return value.decode(encoding)

        return six.text_type(value)

經過比較發現,主要的不同是對token,timestap,nonce字符串進行了編碼,代碼寫好之後,在微信公眾平臺上填寫相關信息進行測試,如下圖所示.

全部源代碼可以訪問這個地址

技術分享圖片

如果通過,微信開放平臺會記錄下我們的信息,如果失敗無法保存。

odoo後臺實現微信公眾號驗證