주요 콘텐츠로 건너뛰기

Handle webhooks

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

The webhooks used in the examples:

# 통합에서 웹훅 이벤트를 처리하기 위해 이 샘플 코드를 사용하세요.
#
# 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>" # 실제 웹훅 비밀 키로 교체하세요

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