使用Python和Azure函数的Xero API Webhook服务器

2024-10-08 18:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Azure Function应用程序从Xero接收Webhook进行处理。但是,我的哈希计算不正确,这使我陷入困境

我认为这与Python处理Body请求的方式有关

代码如下:

#import Logging module to log errors to console
import logging

#import Azure Functions
import azure.functions as func

#import Cryptopackages
import hmac
import hashlib
import base64

#import JSON
import json

XERO_KEY = 'key here'

#function to generate key
def create_sha256_signature(key, message):
    messagecoded = bytes(message, 'UTF-8')
    return base64.b64encode(hmac.new(key.encode(), messagecoded, digestmod=hashlib.sha256).digest()).decode()

#Define Main function - Recieve a HTTP reponse
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Recieved a Request from Xero')
    
    #Parse HASH Key from Header
    xerosign = req.headers.get('x-xero-signature')
    logging.info(xerosign)
    
    #Get JSON body
    Data = req.get_body()
    Body = Data
    #Body = json.dumps(payload, separators=(",", ":")).strip()
    logging.info(Body)
    
    #Get Signature from defined function
    signature = create_sha256_signature(XERO_KEY, str(Body))
    
    logging.info(signature)
    logging.info(xerosign)

    if hmac.compare_digest(xerosign, signature):
        return func.HttpResponse(
            status_code=200)
    else:
        return func.HttpResponse(
            status_code=401
            )

身体要求是

{
    "events": [],
    "lastEventSequence": 0,
    "firstEventSequence": 0,
    "entropy": "TXHKKDMKUHWFBYTVJSQU"
}

标题x-xero-signature=C7G5M2SVxs/fAJM8fFLahzex32Rr7jwMHixX/OgvkFQ=


Tags: tokeyimportinforeturnloggingfunctionbody
2条回答

我发表了一个implementing webhooks using node的例子。虽然语言不同,但概念保持不变。重要的是不要修改传入的原始请求主体,否则签名验证将失败。在使用node和express时,这意味着配置主体解析器中间件以专门用于webhooks端点的原始请求主体。这篇链接文章中有一个例子

另外,另一位Xero开发者布道者在implementing webhooks in aws lambda using python上写了这篇文章。虽然本文中的内容比您需要的更多,但它确实包含了一个代码段,可以帮助您通过“接收意图”签名验证

在回顾了Rett Behrens所做的工作之后,对Azure Function应用程序处理数据的方式进行了进一步的挖掘。我有一个利用Node.js的有效解决方案,它规定了Microsoft处理API响应的方式,如果不输入“body”:“它会自动从初始post请求中使用body进行响应。因此,在Xero排除空体的情况下会产生问题

https://github.com/mast3rbow/Xero-Functionapp

github repo包括我的工作示例,它将使企业能够直接将Xero事件发送到Microsoft Power Automation,以便在那里进行一些逻辑处理

相关问题 更多 >

    热门问题