Code Examples

Ready-to-use code snippets for integrating WebhookBox into your applications.

JavaScript / Node.js

Sending a webhook with fetch

const webhookUrl = 'https://webhookbox.io/w/your-endpoint-id';

const response = await fetch(webhookUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    event: 'user.created',
    data: {
      id: 123,
      email: 'user@example.com',
      timestamp: new Date().toISOString()
    }
  })
});

console.log('Response:', response.status);

Using Axios

const axios = require('axios');

const webhookUrl = 'https://webhookbox.io/w/your-endpoint-id';

const payload = {
  event: 'payment.completed',
  amount: 99.99,
  currency: 'USD',
  customer: { id: 456, email: 'customer@example.com' }
};

try {
  const response = await axios.post(webhookUrl, payload);
  console.log('Webhook sent:', response.status);
} catch (error) {
  console.error('Error:', error.message);
}

Python

Using requests library

import requests
import json
from datetime import datetime

webhook_url = 'https://webhookbox.io/w/your-endpoint-id'

payload = {
    'event': 'order.shipped',
    'order_id': 'ORD-12345',
    'tracking_number': 'TRK-67890',
    'timestamp': datetime.utcnow().isoformat()
}

headers = {
    'Content-Type': 'application/json'
}

response = requests.post(
    webhook_url,
    data=json.dumps(payload),
    headers=headers
)

print(f'Status: {response.status_code}')
print(f'Response: {response.text}')

Async with aiohttp

import aiohttp
import asyncio
import json

async def send_webhook():
    webhook_url = 'https://webhookbox.io/w/your-endpoint-id'

    payload = {
        'event': 'data.sync',
        'status': 'completed',
        'records': 1500
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(webhook_url, json=payload) as response:
            print(f'Status: {response.status}')
            body = await response.text()
            print(f'Response: {body}')

asyncio.run(send_webhook())

Go

Standard library

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

func main() {
    webhookURL := "https://webhookbox.io/w/your-endpoint-id"

    payload := map[string]interface{}{
        "event":     "deployment.success",
        "version":   "v1.2.3",
        "timestamp": time.Now().Format(time.RFC3339),
    }

    jsonData, err := json.Marshal(payload)
    if err != nil {
        panic(err)
    }

    resp, err := http.Post(webhookURL, "application/json",
                          bytes.NewBuffer(jsonData))
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Printf("Status: %d\n", resp.StatusCode)
}

Ruby

Using Net::HTTP

require 'net/http'
require 'uri'
require 'json'

webhook_url = URI('https://webhookbox.io/w/your-endpoint-id')

payload = {
  event: 'subscription.renewed',
  user_id: 789,
  plan: 'premium',
  timestamp: Time.now.iso8601
}

http = Net::HTTP.new(webhook_url.host, webhook_url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(webhook_url)
request['Content-Type'] = 'application/json'
request.body = payload.to_json

response = http.request(request)
puts "Status: #{response.code}"
puts "Body: #{response.body}"

PHP

Using cURL

<?php
$webhookUrl = 'https://webhookbox.io/w/your-endpoint-id';

$payload = [
    'event' => 'invoice.paid',
    'invoice_id' => 'INV-001',
    'amount' => 250.00,
    'timestamp' => date('c')
];

$ch = curl_init($webhookUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "Status: $httpCode\n";
echo "Response: $response\n";

Using the WebhookBox API

These examples show how to interact with the WebhookBox API to manage your endpoints programmatically.

Creating an endpoint

// JavaScript
const response = await fetch('https://webhookbox.io/api/v1/endpoints', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Production Webhook',
    response_config: {
      status_code: 200,
      body: { received: true }
    }
  })
});

const endpoint = await response.json();
console.log('New endpoint:', endpoint.url);

Fetching recent requests

# Python
import requests

api_key = 'YOUR_API_KEY'
endpoint_id = 'YOUR_ENDPOINT_ID'

headers = {
    'Authorization': f'Bearer {api_key}'
}

response = requests.get(
    f'https://webhookbox.io/api/v1/endpoints/{endpoint_id}/requests',
    headers=headers,
    params={'limit': 10}
)

requests_data = response.json()
for req in requests_data['data']:
    print(f"{req['method']} - {req['created_at']}")

Best Practices

  • Always use HTTPS webhook URLs in production
  • Implement retry logic with exponential backoff
  • Include timestamps in your webhook payloads
  • Use webhook signatures for production endpoints
  • Log webhook responses for debugging