SMS Automation

WebHook Code for Incoming SMS

Automate incoming SMS with secure webhooks. Event-driven POSTs to your server for auto-reply and inbox automation.

Event-Driven AutomationHMAC SHA-256 Security
Overview

Automate Incoming SMS Messages

A Webhook sends notifications to your server when SMS arrives. When someone texts your Android device, your server receives an HTTP POST as the gateway delivers that event (timing depends on device connectivity and our path). Learn more about SMS delivery reports and API documentation.

With webhooks, you can build automation. Auto-reply systems. CRM integrations. Ticket creation. Order confirmations. And more. All happens automatically when someone texts your device. See real-world SMS use cases or check our PHP integration guide for code examples.

  • Event-driven POSTs: Your endpoint receives a callback when SMS arrives on the paired device (subject to connectivity)
  • Secure verification: HMAC SHA-256 signature proves it's real
  • Lots of options: Build auto-reply, integrations, and custom workflows
POST['messages']
POST
HTTP Method
SHA-256
HMAC Security
Push
Event callbacks
JSON
Data Format
Code

Complete PHP Webhook Handler

Copy-paste ready PHP code for handling incoming SMS webhooks with signature verification

webhook-handler.php
<?php
header('Content-Type: application/json');

$secret = getenv('SMS_GATEWAY_WEBHOOK_SECRET');
$timestamp = $_SERVER['HTTP_X_SMSGATEWAY_TIMESTAMP'] ?? '';
$sigHeader = $_SERVER['HTTP_X_SMSGATEWAY_SIGNATURE'] ?? '';
$eventId = $_SERVER['HTTP_X_SMSGATEWAY_EVENT_ID'] ?? '';
$body = file_get_contents('php://input');

if ($timestamp === '' || $sigHeader === '' || $secret === '') {
    http_response_code(400);
    echo json_encode(['error' => 'missing_signature']);
    exit;
}

if (abs(time() - (int) $timestamp) > 300) {
    http_response_code(401);
    echo json_encode(['error' => 'stale_timestamp']);
    exit;
}

$expected = 'v1=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret);
$ok = false;
foreach (preg_split('/\s+/', $sigHeader) as $candidate) {
    if (hash_equals($expected, $candidate)) {
        $ok = true;
        break;
    }
}
if (!$ok) {
    http_response_code(401);
    echo json_encode(['error' => 'bad_signature']);
    exit;
}

// Deduplicate on X-SmsGateway-Event-Id (retries and replays reuse it).
$data = json_decode($body, true) ?: [];
$type = $data['type'] ?? '';
$message = $data['data']['message'] ?? [];

if ($type === 'message.received') {
    $from = $message['number'] ?? '';
    $text = $message['text'] ?? '';
    error_log("Inbound SMS $eventId from $from: $text");
}

http_response_code(200);
echo json_encode(['ok' => true]);
01

Signature Verification

HMAC SHA-256 makes sure only real requests from SMS Gateway get processed. Always verify first.

02

JSON Message Data

Each message has ID, number, content, deviceID, simSlot, timestamps, and status info.

03

Auto-Reply Logic

Implement intelligent auto-reply by checking message content and responding via SMS Gateway API.

Payload

Webhook Message Structure

Understanding the data you receive in webhook POST requests

Message Fields

  1. 01

    id

    Event id (also X-SmsGateway-Event-Id)

  2. 02

    type

    message.received, message.delivered, message.failed, …

  3. 03

    data.message.id

    Message id for DLR and replies

  4. 04

    data.message.number

    Remote number in E.164

  5. 05

    data.message.text

    SMS body

  6. 06

    data.message.deviceId

    Android device that handled it

  7. 07

    data.message.status

    Received, Delivered, Failed, …

  8. 08

    data.message.campaignId

    Campaign id when the send created one

  9. 09

    data.message.metadata

    Your metadata copied from the send

  10. 10

    data.message.deliveredAt

    Present on Delivered events

Security Headers

X-SmsGateway-Signature

v1= hex HMAC-SHA256 of {timestamp}.{raw body} keyed with the endpoint secret. During rotation the header carries both signatures, space-separated.

Content-Type

application/json

X-SmsGateway-Event-Id

Deduplicate on this id. Retries and replays reuse it.

Steps

How to Set Up Your Webhook

Step-by-step guide to implementing incoming SMS automation

  1. 01

    Create a PHP Script

    Create a new PHP file on your web server (e.g., webhook-handler.php). This script will receive incoming SMS notifications from SMS Gateway.

  2. 02

    Define Your API Key

    Store the signing secret returned once when you create the webhook (or rotate it). There is no read path for the secret.

  3. 03

    Verify the Signature

    Read X-SmsGateway-Timestamp and X-SmsGateway-Signature. Compute v1=hex HMAC-SHA256 of "{timestamp}.{raw body}" with the endpoint secret and compare. Reject stale timestamps.

  4. 04

    Decode and Process Messages

    Decode the JSON body. Branch on type (message.received, message.delivered, message.failed). Deduplicate on X-SmsGateway-Event-Id.

  5. 05

    Configure Webhook URL

    In the dashboard or via POST /webhooks, register your HTTPS URL and the events you want (or ["*"]). The create response includes the signing secret once.

  6. 06

    Test Your Webhook

    Send a test SMS to your device and verify that your webhook script receives the notification and processes it correctly.

Use cases

Webhook Automation Use Cases

Limitless possibilities for incoming SMS automation

01

Auto-Reply Systems

Automatically respond to specific keywords or phrases with predefined messages

02

CRM Integration

Create tickets, update customer records, or log conversations in your CRM system

03

Order Processing

Process order confirmations, track shipments, or handle customer inquiries via SMS

04

Alert Systems

Trigger notifications, alerts, or emergency protocols based on SMS keywords

Security

Webhook Security Best Practices

Essential security measures for production webhook implementations

01

Always Verify Signatures

Never process messages without verifying the HTTP_X_SG_SIGNATURE header. Return 401 for invalid signatures.

02

Use HTTPS URLs

Your webhook endpoint must use HTTPS to encrypt data in transit. Never use plain HTTP for webhooks.

03

Implement Rate Limiting

Protect your server from abuse by implementing rate limiting on webhook endpoints.

04

Log All Requests

Keep detailed logs of all webhook requests for debugging and security monitoring purposes.

05

Handle Errors Gracefully

Use try-catch blocks and return appropriate HTTP codes (200, 400, 401, 500) based on processing results.

06

Process Asynchronously

For heavy processing, queue messages and respond quickly to avoid timeout issues.

FAQ

Frequently Asked Questions

Common questions about SMS Gateway Webhooks and automation

01What is a Webhook in SMS Gateway?

A Webhook sends notifications to your server when SMS arrives on your Android device. It's automatic. Your app can respond right away. No need to keep checking. Learn about SMS delivery reports and check the API reference.

02How do I set up a Webhook for incoming SMS?

Create a script that accepts POST requests. Verify X-SmsGateway-Signature (v1= hex HMAC-SHA256 of timestamp.body) with your webhook signing secret. Decode the JSON event. Put your URL in the dashboard or POST /webhooks. See our PHP SMS integration guide for complete examples.

03What is the X-SmsGateway-Signature header used for?

X-SmsGateway-Signature is v1= followed by the hex HMAC-SHA256 of "{timestamp}.{raw body}", keyed with your endpoint secret (returned once on create/rotate). The timestamp is X-SmsGateway-Timestamp. Always verify before trusting the body.

04What data is included in the Webhook payload?

Each event has id, type (for example message.received or message.delivered), createdAt, apiVersion, and data.message with id, number, text, status, deviceId, and timestamps. Delivery events may include campaignId and metadata from the original send.

05Can I auto-reply to incoming SMS using Webhooks?

Yes! In your Webhook script, check the message content. Use POST /api/v1/messages to send an auto-reply. For example, if someone sends 'HI', your script can send a welcome message back automatically. Check the API reference for sending SMS.

06How do I secure my Webhook endpoint?

Always check X-SmsGateway-Signature using HMAC-SHA256 of timestamp.body with your webhook secret. Reject timestamps older than about five minutes. Return 401 if the signature does not match. Use HTTPS. Deduplicate on X-SmsGateway-Event-Id.

07What should I return from my Webhook script?

Your Webhook should return any HTTP 2xx when the event is accepted. Anything else is retried with backoff up to six times over about eight hours. Twenty consecutive failures switch the endpoint off.

08Can I use Webhooks with other programming languages?

Yes! The example shows PHP, but you can use any server-side language. Node.js, Python, C#, Java, Ruby, Go. As long as it can accept POST requests, verify HMAC signatures, and process JSON data. See our PHP integration and C# integration guides.

Get started

Start Automating Incoming SMS Today

Download SMS Gateway and set up your webhook handler to automate SMS processing, implement auto-reply, and integrate with your systems.