区块链支付 Webhook 的工作原理
Chaingateway 中的 Webhook 是一种订阅:当交易符合你设置的筛选条件时,例如有转账打入你的某个地址,我们的服务器就会向你的 URL 发送一个 HTTP POST 请求。这样你无需轮询,就能收到即时支付通知。Webhook 适用于 Ethereum、BNB Smart Chain、Polygon、Arbitrum、TRON 和 Bitcoin,不适用于 Solana。
Webhook 是如何工作的?
Section titled “Webhook 是如何工作的?”你提供一个公开的 URL 和一个筛选条件,Chaingateway 会针对每笔匹配的交易调用一次该 URL。该调用是带 JSON 请求体的 HTTP POST。你的应用读取请求体并据此行动,例如把订单标记为已支付。用于支付时,这种模式也叫 Instant Payment Notification,简称 IPN。
请在预期付款到来之前不久,用将收款的地址创建 Webhook。每条通知都带有下面的数据。type 是资产类型,这里是一笔 TRC20 代币转账。
{ "id": "9d18457f-c71c-4be4-ae7c-ce04e48359ed", "webhook_id": "9ced86a9-b8d9-4bc2-bbd8-5ffe5b456bc8", "from": "TTd9qHyjqiUkfTxe3gotbuTMpjU8LEbpkN", "to": "DScWVXehzWdV2YS8fA2ryNsiHpKiLgAxM", "blocknumber": "65542464", "datetime": "2024-09-25 14:48:27", "tokenid": null, "type": "TRC20", "contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "txid": "18f52f2a55b94a6e3705de4abb18e95dfce79970f27b29450705c561e12b6988", "amount": 108935}创建 Webhook 之前我需要准备什么?
Section titled “创建 Webhook 之前我需要准备什么?”你需要一个接收端,也就是你服务器上能接受来自互联网的 POST 请求的端点。整个流程分四步:
- 构建一个 Chaingateway 能够访问的接收端点。
- 创建一个指向该接收端的 Webhook。
- 等待匹配的区块链事件。
- 读取请求体,并返回 HTTP 状态码 200。
接收端必须可以公开访问。请检查防火墙、反向代理和网络规则,因为私有地址或被封锁的端口会导致每次投递都失败。如果你设置了个人密钥,请在信任每个请求之前先校验它的签名,详见 Webhook 安全。下面的接收端只读取请求体并返回响应。
from flask import Flask, request
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])def webhook_receiver(): data = request.get_json() # Process the webhook data # Update database, trigger notifications, execute business logic, etc. return 'Webhook received successfully', 200
if __name__ == '__main__': app.run()const express = require('express');
const app = express();app.use(express.json());
app.post('/webhook', (req, res) => { const data = req.body; // Process the webhook data // Update database, trigger notifications, execute business logic, etc. res.status(200).send('Webhook received successfully');});
app.listen(3000, () => { console.log('Webhook receiver is listening on port 3000');});<?php
$data = file_get_contents('php://input');$payload = json_decode($data, true);
// Process the webhook data// Update database, trigger notifications, execute business logic, etc.
http_response_code(200);echo 'Webhook received successfully';<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WebhookController extends Controller{ /* * Register a route for it, for example: * Route::post('/webhook', [WebhookController::class, 'handle']); */ public function handle(Request $request) { $payload = $request->all();
// Process the webhook payload \Log::info('Webhook received: ', $payload);
return response()->json(['status' => 'success']); }}如何创建 Webhook?
Section titled “如何创建 Webhook?”向 /api/v2/{chain}/webhooks 发送 POST 请求。请求体需要包含你的接收端的 url 和一个筛选条件。筛选字段如下。
| 字段 | 含义 |
|---|---|
url | 必填。接收端的完整 URL,包括路径。 |
from | 要监控的发送方地址。 |
to | 要监控的接收方地址。 |
contractaddress | 你想追踪的代币的合约地址。Bitcoin 上不可用。 |
token_id | NFT 代币 id。 |
type | 资产类型。Ethereum 和 Arbitrum:ETH、ERC20、ERC721。Polygon:MATIC、ERC20、ERC721。BNB Smart Chain:BNB、BEP20、BEP721。TRON:TRX、TRC10、TRC20、TRC721。 |
reference | 你自己的标签,最长 255 个字符。 |
请提供 from 或 to。如果两者都不提供,API 要求提供 contractaddress 和 token_id。Bitcoin 的 Webhook 只接受 url、from 和 to。地址格式会被校验,不匹配的地址会返回状态码 422,并在 errors 中给出字段名。
curl --request POST \ --url https://app.chaingateway.io/api/v2/ethereum/webhooks \ --header 'Authorization: Bearer YOUR_API_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "url": "https://example.com/webhook", "contractaddress": "0xdac17f958d2ee523a2206206994597c13d831ec7", "type": "ERC20", "reference": "order-1042"}'import requests
url = "https://app.chaingateway.io/api/v2/ethereum/webhooks"
payload = { "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "url": "https://example.com/webhook", "contractaddress": "0xdac17f958d2ee523a2206206994597c13d831ec7", "type": "ERC20", "reference": "order-1042"}headers = { "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_TOKEN"}
response = requests.post(url, json=payload, headers=headers)print(response.json())import axios from 'axios';
const options = { method: 'POST', url: 'https://app.chaingateway.io/api/v2/ethereum/webhooks', headers: {'Content-Type': 'application/json', Authorization: 'Bearer YOUR_API_TOKEN'}, data: { to: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', url: 'https://example.com/webhook', contractaddress: '0xdac17f958d2ee523a2206206994597c13d831ec7', type: 'ERC20', reference: 'order-1042' }};
try { const { data } = await axios.request(options); console.log(data);} catch (error) { console.error(error.response?.data ?? error);}<?php
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://app.chaingateway.io/api/v2/ethereum/webhooks', [ 'json' => [ 'to' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', 'url' => 'https://example.com/webhook', 'contractaddress' => '0xdac17f958d2ee523a2206206994597c13d831ec7', 'type' => 'ERC20', 'reference' => 'order-1042', ], 'headers' => [ 'Authorization' => 'Bearer YOUR_API_TOKEN', ],]);
echo $response->getBody();成功的调用返回状态码 201 和 Webhook 的 id:
{ "status": 201, "ok": true, "message": "Webhook created", "data": { "webhook": "9b2b4dcc-1479-4bcd-9b8a-015673e80f46" }}你可以这样管理现有的 Webhook:用 GET /api/v2/{chain}/webhooks 列出,用 GET .../webhooks/{id} 读取单个,用 PUT .../webhooks/{id} 修改,用 DELETE .../webhooks/{id} 删除。付款到账后请删除该 Webhook,这样它就不会继续匹配之后的转账。当 id 不存在时,PUT 会返回状态码 404 和消息 Webhook not found。
投递失败时会发生什么?
Section titled “投递失败时会发生什么?”Chaingateway 不会自行重试失败的投递。失败的通知会被保存下来,你需要自己读取并重新发送。相关的两个端点是 GET /api/v2/{chain}/webhooks/notifications/failed 和 POST /api/v2/{chain}/webhooks/notifications/{id}/retry。列表通过 page 查询参数分页。
每个条目显示 txid、目标 url、你的服务器已保存的 response 以及 attempts 次数。启动重试后,该通知会从失败列表中移除。如果重试也失败,它会回到列表中。GET /api/v2/{chain}/webhooks/notifications 会列出所有通知,包括成功的。请运行一个小任务,定期检查失败列表并重试其中的通知,同时让接收端具备幂等性,以 txid 作为键,这样重复的通知也不会造成影响。
如何发现 Solana 上的充值?
Section titled “如何发现 Solana 上的充值?”Solana 没有 Webhook 端点。OpenAPI 文件只为 Ethereum、BNB Smart Chain、Polygon、Arbitrum、TRON 和 Bitcoin 定义了它们。对于 Solana,请定期读取收款地址的余额或列出交易,并把结果与你的记录对比。
- RFC 9110, HTTP Semantics 定义了 POST 方法,以及接收端返回的 2xx 状态码。
- Ethereum transactions 描述了 EVM 链上通知中出现的交易字段。
- TRON transaction documentation 描述了 TRON
type取值背后的交易类型。