Creare webhook
Creare webhook
Sezione intitolata “Creare webhook”Questa guida ti aiuta a creare webhook usando l’API Chaingateway. Include dettagli sulla scrittura di un ricevente webhook di base, l’iscrizione a un webhook e la gestione dei parametri specifici della chain.
Come funziona
Sezione intitolata “Come funziona”Il nostro sistema webhook funziona come un sistema Instant Payment Notification. Può essere usato per notificare al tuo software un pagamento in arrivo o la ricezione di un token. È composto da due parti di codice:
Il webhook: È l’URL dell’endpoint a cui verranno inviate le notifiche webhook. Devi fornire questo URL all’API Chaingateway al momento dell’iscrizione al webhook. Devi anche specificare i parametri di filtro come sender, receiver, contractaddress, token_id e type (tipo di transazione). Se si verifica un evento sulla blockchain che corrisponde a questi criteri, invieremo un webhook all’URL specificato.
Il ricevente webhook: È il codice che viene eseguito sul tuo server e ascolta le notifiche webhook in entrata. Riceve il payload del webhook ed esegue le azioni necessarie nel tuo software in base ai dati ricevuti.
Per configurare il sistema webhook, devi implementare il codice del ricevente webhook sul tuo server e configurare l’URL del webhook nell’API Chaingateway. Una volta configurato, ogni volta che si verifica un pagamento o la ricezione di un token, l’API Chaingateway invierà una richiesta POST al tuo URL webhook, attivando il codice del ricevente webhook e consentendo al tuo software di intraprendere le azioni appropriate.
Scrivere un ricevente webhook di base
Sezione intitolata “Scrivere un ricevente webhook di base”Un ricevente webhook è un endpoint del server che ascolta le richieste HTTP POST in entrata da ChainGateway. Di seguito trovi esempi di riceventi webhook di base in diversi linguaggi di programmazione.
Esempio di codice
Sezione intitolata “Esempio di codice”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); }}Creare un webhook per iscriverti a un evento blockchain
Sezione intitolata “Creare un webhook per iscriverti a un evento blockchain”Per iscriverti a un webhook, devi inviare una richiesta all’API ChainGateway con i parametri appropriati.
Parametri
Sezione intitolata “Parametri”- url (obbligatorio): L’URL del tuo endpoint ricevente webhook. Deve essere un URL valido.
- from: L’indirizzo del mittente (opzionale, è richiesto almeno uno tra
fromoto). - to: L’indirizzo del destinatario (opzionale, è richiesto almeno uno tra
fromoto). - contractaddress: L’indirizzo del contratto del token (opzionale).
- token_id: Obbligatorio quando non sono presenti né
fromnéto. - type: Il tipo di transazione (opzionale). Valori possibili:
TRX,TRC10,TRC20,TRC721.
Esempio di header Authorization
Sezione intitolata “Esempio di header Authorization”Sostituisci YOUR_API_TOKEN con il tuo token API effettivo.
Esempio di codice
Sezione intitolata “Esempio di codice”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();Informazioni importanti
Sezione intitolata “Informazioni importanti”- Assicurati che il tuo endpoint ricevente webhook sia pubblicamente accessibile e possa gestire richieste HTTP POST.
- Proteggi il tuo endpoint webhook convalidando la fonte delle richieste in entrata e garantendo l’integrità dei dati.
- Chaingateway non memorizza informazioni sensibili come il token. Conserva quindi queste informazioni in modo sicuro.
- Per ottenere una API key e informazioni sull’autorizzazione, consulta la sezione Per iniziare della documentazione Chaingateway.