Webhook
Webhook
Section titled “Webhook”了解 Chaingateway 的 Webhook 功能如何为你的服务器提供即时支付通知。
Chaingateway 的 Webhook 会向你系统的端点提供实时的即时支付通知。为此,你应该在付款完成前创建一个 Webhook。此 Webhook 具有多个筛选选项,并会在交易结算并匹配你的筛选条件后立即向你提供交易信息。
Webhook 如何工作
Section titled “Webhook 如何工作”Webhook: Webhook 是应用程序向其他应用程序或服务发送实时通知的一种方式。在区块链的语境中,Webhook 可用于接收有关各种事件的通知,例如新区块被挖出、交易被确认或触发了智能合约事件。
设置 Webhook 时,你需要在自己的应用程序中提供一个 URL 端点来接收通知。每当指定的事件发生时,区块链网络就会向你的 Webhook 端点发送一个包含相关数据的 HTTP POST 请求。你的应用程序随后可以处理这些数据并采取相应的操作,例如更新数据库、发送通知或触发其他流程。
Instant Payment Notifications(IPN): IPN 是一种特定类型的 Webhook,用于支付系统的语境中,包括基于区块链的支付系统。IPN 通常用于接收有关支付相关事件的通知,例如成功的支付、失败的支付或退款。
当区块链网络上发生付款时,可以触发 IPN 来通知你的应用程序支付状态。这使你的应用程序能够更新其内部记录、为用户提供即时反馈,或根据支付状态触发后续操作。
Webhook 和 IPN 对于构建与区块链网络交互的实时事件驱动应用程序都至关重要。它们使你的应用程序能够随时了解最新事件,并基于这些事件立即采取行动。
Webhook 消息示例
Section titled “Webhook 消息示例”我们的 Webhook 系统会以以下格式推送消息
{ "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,你需要完成以下步骤:
- 创建一个接收端点,供我们向你发送 Webhook
- 使用该接收端点在 Chaingateway 上创建 Webhook
- 等待区块链事件
- 处理请求并返回正确的响应代码
在创建 Webhook 之前,你首先需要设置一个接收端。Webhook 接收端是一个监听传入 Webhook 请求的组件或端点。它充当外部系统或服务触发事件的接收方或监听方。当 Webhook 事件发生时,发送系统会向 Webhook 接收端的 URL 发起 HTTP 请求,并提供与该事件相关的数据。
Webhook 接收端的作用是处理传入的 Webhook 请求。它通常根据接收到的数据执行相应操作,例如更新数据库、触发通知或执行特定的业务逻辑。
要设置 Webhook 接收端,你需要在自己的应用程序中定义一个能够接收传入 HTTP 请求的端点。此端点应可公开访问,以便发送系统可以向它发送 Webhook 事件。接收端设置完成后,你可以配置发送系统,使其将 Webhook 事件发送到该接收端的 URL。
::: tip 重要提示: Webhook 接收端必须可以从外部访问,这一点至关重要。这意味着在 Webhook 接收端中定义的端点 URL 应可公开访问,以便发送系统能够向它们发送 Webhook 事件。请务必相应地配置你的网络设置、防火墙和安全措施,以允许传入的 HTTP 请求到达 Webhook 接收端。 :::
#!/bin/bash
# Define the endpoint URLENDPOINT_URL="https://example.com/webhook"
# Start a local server to receive the webhooknc -l -p 8080 > webhook_payload.json &
# Print the server's PIDecho "Webhook receiver is running with PID: $!"
# Wait for the webhook payload to be receivedsleep 5
# Read the received payload from the filePAYLOAD=$(cat webhook_payload.json)
# Process the webhook data# Update database, trigger notifications, execute business logic, etc.
# Send the response back to the senderecho "Webhook received successfully" | curl -X POST -d @- $ENDPOINT_URL
# Clean up the temporary filesrm webhook_payload.jsonfrom flask import Flask, request
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])def webhook_receiver(): data = request.json() # Process the webhook data # Update database, trigger notifications, execute business logic, etc. return 'Webhook received successfully'
if __name__ == '__main__': app.run()const express = require('express');const bodyParser = require('body-parser');
const app = express();app.use(bodyParser.json());
app.post('/webhook', (req, res) => { const data = req.body; // Process the webhook data // Update database, trigger notifications, execute business logic, etc. res.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{ /* * you should register a route for it like * Route::post('/webhook', [WebhookController::class, 'handle']); */ public function handle(Request $request) { // Log the webhook payload for debugging \Log::info('Webhook received: ', $request->all());
// Process the webhook payload $eventType = $request->header('X-Event-Type'); $payload = $request->all();
// Do something with this webhook receiver
// Respond to the webhook sender return response()->json(['status' => 'success']); }}创建好公开的 Webhook 接收端后,我们现在可以创建 Webhook 了。
创建 Webhook 时,你有多个选项可以筛选相关事件。
- from(string):发送方地址。
- to(string):接收方地址。
- contractaddress(string):你想要追踪的合约地址。
- token_id(string):NFT 代币 ID。
- type(string enum):要追踪的资产类型。以太坊的可能取值为 ETH、ERC20 或 ERC721。请查阅其他链的文档。
你还需要添加 url 参数,它必须是一个完全限定域名或 IP 地址,并带有指向你之前创建的 Webhook 接收端点的路由。
这意味着必须提供”url”,以及”from”或”to”中的一个。其余为可选项。
示例:
curl --request POST \ --url https://api.chaingateway.io/api/v2/ethereum/webhooks \ --header 'Authorization: YOUR_SECRET_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "from": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "url": "http://vonrueden.com/", "contractaddress": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "token_id": null, "type": "ERC20"}'import requests
url = "https://api.chaingateway.io/api/v2/ethereum/webhooks"
payload = { "from": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "url": "http://vonrueden.com/", "contractaddress": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "token_id": None, "type": "ERC20"}headers = { "Content-Type": "application/json", "Authorization": "YOUR_SECRET_TOKEN"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())import axios from 'axios';
const options = { method: 'POST', url: 'https://api.chaingateway.io/api/v2/ethereum/webhooks', headers: {'Content-Type': 'application/json', Authorization: 'YOUR_SECRET_TOKEN'}, data: { from: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', to: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', url: 'http://vonrueden.com/', contractaddress: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', token_id: null, type: 'ERC20' }};
try { const { data } = await axios.request(options); console.log(data);} catch (error) { console.error(error);}<?php
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.chaingateway.io/api/v2/ethereum/webhooks', [ 'body' => '{ "from": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "url": "http://vonrueden.com/", "contractaddress": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "token_id": null, "type": "ERC20"}', 'headers' => [ 'Authorization' => 'YOUR_SECRET_TOKEN', 'Content-Type' => 'application/json', ],]);
echo $response->getBody();<?php
use Illuminate\Support\Facades\Http;
$response = Http::withHeaders([ 'Authorization' => 'YOUR_SECRET_TOKEN', 'Content-Type' => 'application/json',])->post('https://api.chaingateway.io/api/v2/ethereum/webhooks', [ 'from' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', 'to' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', 'url' => 'http://vonrueden.com/', 'contractaddress' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', 'token_id' => null, 'type' => 'ERC20',]);
echo $response->body();响应大致如下:
{ "status": 201, "ok": true, "message": "Webhook created", "data": { "webhook": "9b2b4dcc-1479-4bcd-9b8a-015673e80f46" }}