接入教程
1. 登录Adyen账户并访问管理API设置页面
2. 在Webhooks部分配置接收通知的端点URL
3. 选择要订阅的事件类型并保存设置
4. 在您的服务器上实现Webhook处理器以接收事件
5. 验证接收到的Webhook签名以确保安全性
6. 测试Webhook功能并进行集成验证
Python Webhook验证示例
import hmac
import hashlib
from flask import Flask, request
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook_handler():
payload = request.get_data(as_text=True)
signature = request.headers.get('X-Adyen-Signature')
webhook_key = 'YOUR_WEBHOOK_KEY'
calculated_signature = hmac.new(
webhook_key.encode('utf-8'),
payload.encode('utf-8'),
hashlib.sha256
).hexdigest()
if hmac.compare_digest(calculated_signature, signature):
event_data = request.json
# 处理事件逻辑
return {'status': 'processed'}, 200
else:
return {'error': 'Invalid signature'}, 401
if __name__ == '__main__':
app.run(port=3000)
PHP Webhook接收示例
<?php
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_ADYEN_SIGNATURE'] ?? '';
$webhookKey = 'YOUR_WEBHOOK_KEY';
$calculatedSignature = hash_hmac('sha256', $payload, $webhookKey);
if (hash_equals($calculatedSignature, $signature)) {
$eventData = json_decode($payload, true);
// 处理事件逻辑
$eventType = $eventData['type'] ?? '';
$eventId = $eventData['id'] ?? '';
// 记录或处理事件
file_put_contents('webhook_log.txt',
date('Y-m-d H:i:s') . " - {$eventType}: {$eventId}\n",
FILE_APPEND
);
http_response_code(200);
echo json_encode(['status' => 'processed']);
} else {
http_response_code(401);
echo json_encode(['error' => 'Invalid signature']);
}
?>
Node.js Webhook服务器示例
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
const WEBHOOK_KEY = 'YOUR_WEBHOOK_KEY';
app.post('/webhook', (req, res) => {
const payload = JSON.stringify(req.body);
const signature = req.headers['x-adyen-signature'];
const calculatedSignature = crypto
.createHmac('sha256', WEBHOOK_KEY)
.update(payload)
.digest('hex');
if (crypto.timingSafeEqual(
Buffer.from(calculatedSignature, 'hex'),
Buffer.from(signature, 'hex')
)) {
const eventData = req.body;
console.log('Received event:', eventData.type);
// 处理事件逻辑
// ...
res.status(200).json({ status: 'processed' });
} else {
res.status(401).json({ error: 'Invalid signature' });
}
});
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
常见问题
如何验证Webhook请求的真实性?
Adyen使用HMAC SHA256签名验证Webhook请求。每个请求都包含X-Adyen-Signature头,您需要使用预共享的Webhook密钥对请求体计算HMAC SHA256签名,并与请求头中的签名进行比较验证。
Webhook服务器应该返回什么HTTP状态码?
成功处理Webhook后应返回2xx状态码(推荐200)。如果签名验证失败应返回401,服务器错误返回5xx。Adyen可能会重试非2xx响应的请求。
Webhook事件包含哪些常见字段?
典型Webhook事件包含:事件类型(type)、事件ID(id)、时间戳(timestamp)、相关资源ID(resourceId)和事件详情(data)。具体字段结构请参考Adyen官方文档。
Aitishiku.com