跳至主要内容

Handle webhooks

Use the code examples of the webhooks’ handling functions for a single endpoint.

The webhooks used in the examples:

# 使用以下示例代码来处理您集成环境中的 Webhook 事件。
#
# 1. 将此代码复制到新创建的 `server.py` 文件中。
#
# 2. 安装必要的依赖项:
# python -m pip install fastapi[all]
#
# 3. 在 http://localhost:8000 地址上运行服务器
# python server.py

import fastapi, hashlib, hmac, json, typing

app = fastapi.FastAPI()

@app.post("/webhook")
async def webhook(request: fastapi.Request) -> dict[str, typing.Any]:
secret_key = "<YOUR_S2S_KEY>" # 请替换为您的实际 Webhook Secret Key

raw_payload = await request.body()
payload = raw_payload.decode()
timestamp = request.headers["x-aghanim-signature-timestamp"]
received_signature = request.headers["x-aghanim-signature"]

if not verify_signature(secret_key, payload, timestamp, received_signature):
raise fastapi.HTTPException(status_code=403, detail="Invalid signature")

data = json.loads(payload)
event_type = data["event_type"]
event_data = data["event_data"]

raise fastapi.HTTPException(status_code=400, detail="Unknown event type")

def verify_signature(secret_key: str, payload: str, timestamp: str, received_signature: str) -> bool:
signature_data = f"{timestamp}.{payload}"
computed_hash = hmac.new(secret_key.encode(), signature_data.encode(), hashlib.sha256)
computed_signature = computed_hash.hexdigest()
return hmac.compare_digest(computed_signature, received_signature)

if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

Testing

To test the webhooks’ implementation, locally, send the requests below.

curl -X POST "https://<YOUR_WEBHOOK_ENDPOINT_DOMAIN>/<YOUR_WEBHOOK_ENDPOINT_URI>" \
-H 'x-aghanim-signature-timestamp: <EVENT_TIMESTAMP>' \
-H 'x-aghanim-signature: <HMAC-SHA256_SIGNATURE>' \
-H 'user-agent: Aghanim/0.1.0' \
-H 'content-type: application/json' \
-H 'accept: */*' \
-H 'host: <YOUR_WEBHOOK_ENDPOINT_DOMAIN>' \
-d '{
"event_id": "whevt_eAeXhOxLwxy",
"event_type": "player.verify",
"idempotency_key": null,
"event_data": {
"player_id": "testplayer"
},
"context": null
}'

需要技术支持?
联系我们的集成技术团队: integration@aghanim.com