Webhooks Guide

Receive real-time notifications about SMS delivery status and other events.

What are Webhooks?

Webhooks allow OpenSMS to send real-time notifications to your application when events occur, such as SMS delivery confirmations.

Setting Up Webhooks

  1. Log in to your OpenSMS account
  2. Go to Settings → Webhooks
  3. Enter your webhook URL (e.g., https://yourapp.com/webhooks/sms)
  4. Select which events to receive
  5. Click "Save"

Webhook Events

SMS Delivered

{
  "event": "sms.delivered",
  "message_id": "msg_123456",
  "phone": "+254712345678",
  "status": "delivered",
  "timestamp": "2024-01-13T12:00:00Z"
}

SMS Failed

{
  "event": "sms.failed",
  "message_id": "msg_123456",
  "phone": "+254712345678",
  "status": "failed",
  "error": "Invalid phone number",
  "timestamp": "2024-01-13T12:00:00Z"
}

SMS Pending

{
  "event": "sms.pending",
  "message_id": "msg_123456",
  "phone": "+254712345678",
  "status": "pending",
  "timestamp": "2024-01-13T12:00:00Z"
}

Handling Webhooks

PHP Example

<?php
$payload = file_get_contents('php://input');
$event = json_decode($payload, true);

if ($event['event'] === 'sms.delivered') {
    // Update your database
    updateMessageStatus($event['message_id'], 'delivered');
} elseif ($event['event'] === 'sms.failed') {
    // Handle failure
    updateMessageStatus($event['message_id'], 'failed');
}

// Send 200 OK response
http_response_code(200);
echo json_encode(['status' => 'received']);
?>

Python Example

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhooks/sms', methods=['POST'])
def handle_webhook():
    event = request.get_json()
    
    if event['event'] == 'sms.delivered':
        update_message_status(event['message_id'], 'delivered')
    elif event['event'] == 'sms.failed':
        update_message_status(event['message_id'], 'failed')
    
    return jsonify({'status': 'received'}), 200

if __name__ == '__main__':
    app.run()

Node.js Example

const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhooks/sms', (req, res) => {
    const event = req.body;
    
    if (event.event === 'sms.delivered') {
        updateMessageStatus(event.message_id, 'delivered');
    } else if (event.event === 'sms.failed') {
        updateMessageStatus(event.message_id, 'failed');
    }
    
    res.json({ status: 'received' });
});

app.listen(3000, () => console.log('Webhook server running'));

Best Practices

  • Always return a 200 OK response within 5 seconds
  • Store webhook data in your database for processing
  • Use HTTPS for your webhook URL
  • Verify webhook signatures for security
  • Implement retry logic for failed webhook deliveries
  • Log all webhook events for debugging

Testing Webhooks

You can test your webhook endpoint by:

  1. Going to Settings → Webhooks
  2. Clicking "Send Test Event"
  3. Checking your server logs to verify receipt

Next Steps