Code Examples

Code Examples

This page contains code examples in different programming languages to help you integrate with Web Hook Box.

This example shows how to create a new webhook using the Web Hook Box API:

// Creating a webhook using PHP and cURL
        $apiToken = 'YOUR_API_TOKEN';
        $url = 'https://webhookbox.example.com/api/webhooks';
        $data = [
        'description' => 'My test webhook',
        'forwardUrl' => 'https://myapp.example.com/webhook-receiver',
        'enableForwarding' => true
        ];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $apiToken,
        'Content-Type: application/json'
        ]);
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($statusCode === 201) {
        $webhook = json_decode($response, true);
        echo "Webhook created successfully! URL: " . $webhook['url'];
        } else {
        echo "Error creating webhook: " . $response;
        }

Using Guzzle HTTP client:

// Using Guzzle HTTP client
        use GuzzleHttp\Client;
        $client = new Client();
        $apiToken = 'YOUR_API_TOKEN';
        try {
        $response = $client->post('https://webhookbox.example.com/api/webhooks', [
        'headers' => [
        'Authorization' => 'Bearer ' . $apiToken,
        'Content-Type' => 'application/json',
        ],
        'json' => [
        'description' => 'My test webhook',
        'forwardUrl' => 'https://myapp.example.com/webhook-receiver',
        'enableForwarding' => true
        ]
        ]);
        $webhook = json_decode($response->getBody(), true);
        echo "Webhook created successfully! URL: " . $webhook['url'];
        } catch (\Exception $e) {
        echo "Error creating webhook: " . $e->getMessage();
        }

This example shows how to receive and process incoming webhooks:

// webhook-receiver.php
        // Receive and process incoming webhooks
        // Get the raw payload
        $payload = file_get_contents('php://input');
        $headers = getallheaders();
        // Log the incoming webhook (optional)
        file_put_contents(
        'webhook_log.txt',
        date('[Y-m-d H:i:s]') . " Received webhook:\n" .
        json_encode([
        'headers' => $headers,
        'payload' => json_decode($payload, true)
        ], JSON_PRETTY_PRINT) . "\n\n",
        FILE_APPEND
        );
        // Process the webhook based on content type
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        if (strpos($contentType, 'application/json') !== false) {
        $data = json_decode($payload, true);
        // Handle the webhook data
        if (isset($data['event'])) {
        switch ($data['event']) {
        case 'payment.success':
        // Handle successful payment
        processSuccessfulPayment($data);
        break;
        case 'user.created':
        // Handle user creation
        processNewUser($data);
        break;
        default:
        // Handle unknown event type
        logUnknownEvent($data);
        break;
        }
        }
        }
        // Always respond with a 200 OK to acknowledge receipt
        http_response_code(200);
        echo json_encode(['status' => 'received']);
        // Example processing functions
        function processSuccessfulPayment($data) {
        // Implementation for processing payments
        }
        function processNewUser($data) {
        // Implementation for handling new users
        }
        function logUnknownEvent($data) {
        // Log unknown event types for later analysis
        }

Using Symfony framework:

// Using Symfony framework
        namespace App\Controller;
        use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
        use Symfony\Component\HttpFoundation\Request;
        use Symfony\Component\HttpFoundation\Response;
        use Symfony\Component\Routing\Annotation\Route;
        use Psr\Log\LoggerInterface;
        class WebhookController extends AbstractController
        {
        #[Route('/webhook-receiver', methods: ['POST'])]
        public function receive(Request $request, LoggerInterface $logger): Response
        {
        // Get the raw payload
        $payload = $request->getContent();
        $data = json_decode($payload, true);
        // Log the incoming webhook
        $logger->info('Received webhook', [
        'headers' => $request->headers->all(),
        'payload' => $data
        ]);
        // Process the webhook
        if (isset($data['event'])) {
        switch ($data['event']) {
        case 'payment.success':
        // Handle payment
        $this->processPayment($data);
        break;
        // Handle other events...
        }
        }
        // Always acknowledge receipt
        return $this->json(['status' => 'received']);
        }
        private function processPayment(array $data): void
        {
        // Implementation
        }
        }

This example shows how to fetch webhook requests from the API:

// Fetching webhook requests using PHP
        $apiToken = 'YOUR_API_TOKEN';
        $webhookUuid = 'YOUR_WEBHOOK_UUID';
        $url = "https://webhookbox.example.com/api/webhooks/{$webhookUuid}/requests";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $apiToken
        ]);
        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($statusCode === 200) {
        $data = json_decode($response, true);
        echo "Found " . $data['total'] . " webhook requests\n";
        foreach ($data['items'] as $request) {
        echo "Request ID: " . $request['id'] . "\n";
        echo "Received at: " . $request['receivedAt'] . "\n";
        echo "Method: " . $request['httpMethod'] . "\n";
        echo "----------------------------------------\n";
        }
        } else {
        echo "Error fetching webhook requests: " . $response;
        }

This example shows how to create a new webhook using Node.js:

// Creating a webhook using Node.js and fetch
        const createWebhook = async () => {
        const apiToken = 'YOUR_API_TOKEN';
        const url = 'https://webhookbox.example.com/api/webhooks';
        try {
        const response = await fetch(url, {
        method: 'POST',
        headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({
        description: 'My test webhook',
        forwardUrl: 'https://myapp.example.com/webhook-receiver',
        enableForwarding: true
        })
        });
        if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const webhook = await response.json();
        console.log(`Webhook created successfully! URL: ${webhook.url}`);
        return webhook;
        } catch (error) {
        console.error('Error creating webhook:', error);
        }
        };
        createWebhook();

Using axios:

// Using axios
        const axios = require('axios');
        const createWebhook = async () => {
        const apiToken = 'YOUR_API_TOKEN';
        const url = 'https://webhookbox.example.com/api/webhooks';
        try {
        const response = await axios.post(url, {
        description: 'My test webhook',
        forwardUrl: 'https://myapp.example.com/webhook-receiver',
        enableForwarding: true
        }, {
        headers: {
        'Authorization': `Bearer ${apiToken}`,
        'Content-Type': 'application/json'
        }
        });
        console.log(`Webhook created successfully! URL: ${response.data.url}`);
        return response.data;
        } catch (error) {
        console.error('Error creating webhook:', error.response ? error.response.data : error.message);
        }
        };
        createWebhook();

This example shows how to receive and process incoming webhooks with Express.js:

// Using Express.js to receive webhooks
        const express = require('express');
        const bodyParser = require('body-parser');
        const app = express();
        const port = process.env.PORT || 3000;
        // Parse JSON bodies
        app.use(bodyParser.json());
        // Webhook receiver endpoint
        app.post('/webhook-receiver', (req, res) => {
        const payload = req.body;
        const headers = req.headers;
        // Log the incoming webhook
        console.log('Received webhook:', {
        headers,
        payload
        });
        // Process the webhook based on event type
        if (payload.event) {
        switch(payload.event) {
        case 'payment.success':
        processPayment(payload);
        break;
        case 'user.created':
        processNewUser(payload);
        break;
        default:
        console.log('Unknown event type:', payload.event);
        }
        }
        // Always acknowledge receipt
        res.status(200).json({ status: 'received' });
        });
        function processPayment(data) {
        // Implementation for processing payments
        console.log('Processing payment:', data.id);
        }
        function processNewUser(data) {
        // Implementation for handling new users
        console.log('Processing new user:', data.user.email);
        }
        // Start the server
        app.listen(port, () => {
        console.log(`Webhook receiver listening at http://localhost:${port}`);
        });

This example shows how to create and manage webhooks using Python:

import requests
        import json
        # API configuration
        API_TOKEN = 'YOUR_API_TOKEN'
        API_BASE_URL = 'https://webhookbox.example.com/api'
        HEADERS = {
        'Authorization': f'Bearer {API_TOKEN}',
        'Content-Type': 'application/json'
        }
        def create_webhook(description, forward_url=None, enable_forwarding=False):
        """
        Create a new webhook
        """
        url = f"{API_BASE_URL}/webhooks"
        payload = {
        'description': description,
        'forwardUrl': forward_url,
        'enableForwarding': enable_forwarding
        }
        response = requests.post(url, headers=HEADERS, json=payload)
        if response.status_code == 201:
        webhook = response.json()
        print(f"Webhook created successfully! URL: {webhook['url']}")
        return webhook
        else:
        print(f"Error creating webhook: {response.text}")
        return None
        def list_webhooks(page=1, limit=20):
        """
        List all webhooks
        """
        url = f"{API_BASE_URL}/webhooks?page={page}&limit={limit}"
        response = requests.get(url, headers=HEADERS)
        if response.status_code == 200:
        data = response.json()
        print(f"Found {data['total']} webhooks")
        return data['items']
        else:
        print(f"Error listing webhooks: {response.text}")
        return []
        def get_webhook_requests(webhook_uuid, page=1, limit=20):
        """
        Get requests for a specific webhook
        """
        url = f"{API_BASE_URL}/webhooks/{webhook_uuid}/requests?page={page}&limit={limit}"
        response = requests.get(url, headers=HEADERS)
        if response.status_code == 200:
        data = response.json()
        print(f"Found {data['total']} requests for webhook {webhook_uuid}")
        return data['items']
        else:
        print(f"Error getting webhook requests: {response.text}")
        return []
        # Example usage
        if __name__ == "__main__":
        # Create a new webhook
        webhook = create_webhook(
        description="My Python webhook",
        forward_url="https://myapp.example.com/webhook-receiver",
        enable_forwarding=True
        )
        if webhook:
        # List all webhooks
        webhooks = list_webhooks()
        # Get requests for the new webhook
        if webhook.get('id'):
        requests = get_webhook_requests(webhook['id'])

This example shows how to receive webhooks with Flask:

from flask import Flask, request, jsonify
        import logging
        import json
        from datetime import datetime
        app = Flask(__name__)
        # Configure logging
        logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        filename='webhooks.log'
        )
        logger = logging.getLogger(__name__)
        @app.route('/webhook-receiver', methods=['POST'])
        def webhook_handler():
        """
        Handle incoming webhooks
        """
        # Get data from request
        payload = request.json
        headers = dict(request.headers)
        # Log the webhook
        logger.info("Received webhook: %s", json.dumps({
        'headers': headers,
        'payload': payload
        }))
        # Process webhook based on event type
        if payload and 'event' in payload:
        event_type = payload['event']
        if event_type == 'payment.success':
        process_payment(payload)
        elif event_type == 'user.created':
        process_new_user(payload)
        else:
        logger.warning("Unknown event type: %s", event_type)
        # Always acknowledge receipt
        return jsonify({'status': 'received', 'timestamp': datetime.utcnow().isoformat()})
        def process_payment(data):
        """Process payment webhook data"""
        logger.info("Processing payment: %s", data.get('id'))
        # Implementation here
        def process_new_user(data):
        """Process new user webhook data"""
        logger.info("Processing new user: %s", data.get('user', {}).get('email'))
        # Implementation here
        if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0', port=5000)

Ruby examples coming soon.

Go examples coming soon.

Have a different use case?

These examples demonstrate common scenarios, but we're always adding more examples for different languages and frameworks.

If you need help with a specific integration not covered here, please contact our support team.