创建 Webhook
创建 Webhook
Section titled “创建 Webhook”本指南帮助你使用 Chaingateway API 创建 Webhook。内容包括编写基础 Webhook 接收端、订阅 Webhook 以及处理链专属参数的详细信息。
我们的 Webhook 系统作为 Instant Payment Notification 系统运作。它可用于通知你的软件有入账付款或代币接收。它由两部分代码组成:
Webhook:这是 Webhook 通知将被发送到的端点 URL。你需要在订阅 Webhook 时将此 URL 提供给 Chaingateway API。你还需要指定筛选参数,如 sender、receiver、contractaddress、token_id 和 type(交易类型)。如果区块链上发生匹配这些条件的事件,我们将向你指定的 URL 发出 Webhook。
Webhook 接收端:这是运行在你服务器上、监听传入 Webhook 通知的代码。它接收 Webhook payload,并根据接收到的数据在你的软件中执行必要的操作。
要设置 Webhook 系统,你需要在服务器上实现 Webhook 接收端代码,并在 Chaingateway API 中配置 Webhook URL。设置完成后,每当发生付款或代币接收,Chaingateway API 都会向你的 Webhook URL 发送 POST 请求,触发 Webhook 接收端代码,让你的软件采取相应的操作。
编写一个基础 Webhook 接收端
Section titled “编写一个基础 Webhook 接收端”Webhook 接收端是一个服务器端点,监听来自 ChainGateway 的传入 HTTP POST 请求。以下是不同编程语言中基础 Webhook 接收端的示例。
const express = require('express');const app = express();const port = 3000;
app.use(express.json());
app.post('/webhook', (req, res) => { console.log('Received webhook:', req.body); res.status(200).send('Webhook received');});
app.listen(port, () => { console.log(`Webhook receiver listening at http://localhost:${port}`);});from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])def webhook(): data = request.json print('Received webhook:', data) return jsonify({'status': 'Webhook received'}), 200
if __name__ == '__main__': app.run(port=3000)<?phpif ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = file_get_contents('php://input'); $json = json_decode($data, true); file_put_contents('php://stderr', print_r($json, TRUE)); http_response_code(200); echo json_encode(['status' => 'Webhook received']);}?>/** To integrate this code into a Laravel application, follow these steps:** 1. Create a new route in your `routes/web.php` file:* Route::post('/webhook', [WebhookController::class, 'handleWebhook']);** 2. Create a new controller using the Artisan command:* php artisan make:controller WebhookController** This will create a new `WebhookController` class in the `app/Http/Controllers` directory.** 3. Open the newly created `WebhookController.php` file and replace its content with the code provided above.** Now, your Laravel application is ready to handle webhooks using the `WebhookController` class.**/
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WebhookController extends Controller{ public function handleWebhook(Request $request) { $data = $request->all(); file_put_contents('php://stderr', print_r($data, TRUE)); return response()->json(['status' => 'Webhook received'], 200); }}创建 Webhook 以订阅区块链事件
Section titled “创建 Webhook 以订阅区块链事件”要订阅 Webhook,你需要使用适当的参数向 ChainGateway API 发送请求。
- url(必填):你的 Webhook 接收端点的 URL。必须是有效的 URL。
- from:发送方地址(可选,
from或to中至少需要一个)。 - to:接收方地址(可选,
from或to中至少需要一个)。 - contractaddress:代币的合约地址(可选)。
- token_id:当
from和to都不存在时必填。 - type:交易类型(可选)。可能的取值:
TRX、TRC10、TRC20、TRC721。
Authorization Header 示例
Section titled “Authorization Header 示例”将 YOUR_API_TOKEN 替换为你的实际 API token。
curl --request POST \ --url https://api.chaingateway.io/v2/webhooks \ --header 'Accept: application/json' \ --header 'content-type: application/json' \ --header 'Authorization: YOUR_API_TOKEN' \ --data '{ "url": "http://yourdomain.com/webhook", "from": "TXSenderAddress", "to": "TXReceiverAddress", "contractaddress": "0xTokenContractAddress", "token_id": "12345", "type": "TRC20"}'import requests
url = "https://api.chaingateway.io/v2/webhooks"payload = { "url": "http://yourdomain.com/webhook", "from": "TXSenderAddress", "to": "TXReceiverAddress", "contractaddress": "0xTokenContractAddress", "token_id": "12345", "type": "TRC20"}headers = { 'Accept': 'application/json', 'content-type': 'application/json', 'Authorization': 'YOUR_API_TOKEN'}
response = requests.post(url, json=payload, headers=headers)print(response.json())const axios = require('axios');
const url = 'https://api.chaingateway.io/v2/webhooks';const payload = { url: 'http://yourdomain.com/webhook', from: 'TXSenderAddress', to: 'TXReceiverAddress', contractaddress: '0xTokenContractAddress', token_id: '12345', type: 'TRC20'};const headers = { 'Accept': 'application/json', 'content-type': 'application/json', 'Authorization': 'YOUR_API_TOKEN'};
axios.post(url, payload, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });<?phprequire 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();$response = $client->post('https://api.chaingateway.io/v2/webhooks', [ 'headers' => [ 'Accept' => 'application/json', 'content-type' => 'application/json', 'Authorization' => 'YOUR_API_TOKEN', ], 'json' => [ 'url' => 'http://yourdomain.com/webhook', 'from' => 'TXSenderAddress', 'to' => 'TXReceiverAddress', 'contractaddress' => '0xTokenContractAddress', 'token_id' => '12345', 'type' => 'TRC20' ]]);
echo $response->getBody();?><?php
use Illuminate\Support\Facades\Http;
$response = Http::withHeaders([ 'Accept' => 'application/json', 'content-type' => 'application/json', 'Authorization' => 'YOUR_API_TOKEN',])->post('https://api.chaingateway.io/v2/webhooks', [ 'url' => 'http://yourdomain.com/webhook', 'from' => 'TXSenderAddress', 'to' => 'TXReceiverAddress', 'contractaddress' => '0xTokenContractAddress', 'token_id' => '12345', 'type' => 'TRC20']);
echo $response->body();- 确保你的 Webhook 接收端点可以公开访问,并能够处理 HTTP POST 请求。
- 通过验证传入请求的来源并确保数据完整性,来保护你的 Webhook 端点安全。
- Chaingateway 不会存储诸如 token 之类的敏感信息。因此,请安全地保存这些信息。
- 有关获取 API key 和了解授权的信息,请参阅 Chaingateway 文档的”快速开始”部分。