Back to BlogTutorials

WhatsApp API PHP Integration: Send Messages with PHP in 2026

WALYTIC TEAMNOVEMBER 11, 20269 MIN READ

Why Integrate WhatsApp into Your PHP Application?

PHP powers a large portion of the web — from WordPress sites to custom enterprise backends. Adding WhatsApp messaging to your PHP stack gives you a direct, high-open-rate channel for order updates, appointment reminders, payment follow-ups, and customer support, all triggered by your own application logic.

This guide walks through the complete WhatsApp API PHP integration using Walytic's REST API. No SDK is required — just PHP's built-in cURL extension, an API key, and the code examples below.

How the WhatsApp REST API Works with PHP

Walytic exposes a standard REST API that accepts JSON payloads over HTTPS. Your PHP code sends a `POST` request with an API key and message payload; Walytic delivers the message to the recipient's WhatsApp in seconds.

Walytic supports two connection modes, selectable from your dashboard:

Connection ModeSetup TimeRequirement
Linked deviceUnder 60 secondsScan a QR code with your existing WhatsApp number
WhatsApp Cloud APIA few minutesMeta Business account connected

Both modes use identical API calls. Your PHP code stays the same regardless of which mode you choose, so you can start with a linked number for fast onboarding and switch to the official Cloud API later with zero code changes. See /features for a full comparison.

Prerequisites

Before writing any code, you need:

  1. A Walytic account — 14-day free trial, no credit card required
  2. A WhatsApp number connected (linked device or Cloud API)
  3. An API key: Settings → API Keys → Generate New Key
  4. Your Instance ID from the same Settings page
  5. PHP 7.4+ with the cURL extension enabled (`php -m | grep curl` to verify)

Step 1: Create a Reusable API Helper

Add this helper function to your PHP project. It handles authentication and JSON encoding for all subsequent requests:

TEMPLATE
<?php

define('WALYTIC_API_KEY', getenv('WALYTIC_API_KEY'));
define('WALYTIC_INSTANCE_ID', getenv('WALYTIC_INSTANCE_ID'));
define('WALYTIC_BASE_URL', 'https://api.walytic.com/api');

function walytic_post(string $endpoint, array $payload): array {
    $ch = curl_init(WALYTIC_BASE_URL . $endpoint);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . WALYTIC_API_KEY,
            'Content-Type: application/json',
        ],
        CURLOPT_TIMEOUT        => 10,
    ]);

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

    if ($response === false || $status >= 400) {
        return ['success' => false, 'error' => "HTTP $status"];
    }

    return json_decode($response, true) ?? ['success' => false];
}

Store your credentials as environment variables — never hardcode them in source files:

BASH
WALYTIC_API_KEY=your_api_key_here
WALYTIC_INSTANCE_ID=your_instance_id_here

Step 2: Send a Text Message

With the helper in place, sending a WhatsApp text message takes five lines:

TEMPLATE
function send_text(string $phone, string $message): bool {
    $result = walytic_post('/messages/send', [
        'instanceId' => WALYTIC_INSTANCE_ID,
        'to'         => $phone,
        'type'       => 'text',
        'text'       => ['body' => $message],
    ]);

    return $result['success'] ?? false;
}

// Usage
send_text('14155552671', 'Hi Sarah! Your order #1042 has shipped and arrives Friday.');

The `to` field takes the phone number in E.164 format without the `+` sign (e.g., `14155552671` for a US number).

Step 3: Send an Image or Document

Pass a public URL for the asset. Walytic fetches and delivers it automatically:

TEMPLATE
// Send an image with a caption
function send_image(string $phone, string $url, string $caption = ''): bool {
    $result = walytic_post('/messages/send', [
        'instanceId' => WALYTIC_INSTANCE_ID,
        'to'         => $phone,
        'type'       => 'image',
        'image'      => ['url' => $url, 'caption' => $caption],
    ]);

    return $result['success'] ?? false;
}

// Send a PDF document
function send_document(string $phone, string $url, string $filename): bool {
    $result = walytic_post('/messages/send', [
        'instanceId' => WALYTIC_INSTANCE_ID,
        'to'         => $phone,
        'type'       => 'document',
        'document'   => ['url' => $url, 'filename' => $filename],
    ]);

    return $result['success'] ?? false;
}

// Examples
send_image('14155552671', 'https://yoursite.com/product.jpg', 'Your order is packed!');
send_document('14155552671', 'https://yoursite.com/invoice-1042.pdf', 'Invoice-1042.pdf');

Supported types: images (JPG, PNG, GIF, WebP), documents (PDF, DOCX, XLSX), audio (MP3, OGG), and video (MP4).

Step 4: Receive Messages with a Webhook

To respond to inbound messages in real time, set your webhook URL in the Walytic dashboard under Settings → Webhooks. Walytic will `POST` a JSON payload to your endpoint whenever a customer sends a message.

TEMPLATE
<?php
// webhook.php — your public HTTPS endpoint

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

if (($payload['event'] ?? '') === 'message.received') {
    $from = $payload['data']['from'];
    $text = strtolower(trim($payload['data']['text']['body'] ?? ''));

    if ($text === 'order status') {
        walytic_post('/messages/send', [
            'instanceId' => WALYTIC_INSTANCE_ID,
            'to'         => $from,
            'type'       => 'text',
            'text'       => ['body' => 'Please reply with your order number and we will look it up.'],
        ]);
    } elseif ($text === 'hours') {
        walytic_post('/messages/send', [
            'instanceId' => WALYTIC_INSTANCE_ID,
            'to'         => $from,
            'type'       => 'text',
            'text'       => ['body' => 'We are open Mon-Fri 9 am-6 pm. How can we help?'],
        ]);
    }
}

http_response_code(200);
echo 'ok';

Always return HTTP 200 immediately. If your endpoint takes longer than a few seconds, Walytic retries delivery automatically.

Practical Use Cases in PHP Applications

Order Shipping Notifications

Hook into your order system and send a confirmation when an order ships:

TEMPLATE
function notify_order_shipped(array $order): void {
    $message = "Hi {$order['customer_name']}! Order #{$order['id']} has shipped. "
             . "Track it here: {$order['tracking_url']}";

    send_text($order['phone'], $message);
}

Appointment Reminders

Reduce no-shows by sending a reminder 24 hours before a booking:

TEMPLATE
function send_appointment_reminder(array $booking): void {
    $message = "Reminder: your appointment with {$booking['provider']} "
             . "is tomorrow at {$booking['time']}. "
             . "Reply YES to confirm or CANCEL to reschedule.";

    send_text($booking['phone'], $message);
}

Payment Reminders

Automate overdue invoice follow-ups to opted-in customers:

TEMPLATE
function send_payment_reminder(array $invoice): void {
    $amount  = number_format($invoice['amount'], 2);
    $message = "Hi {$invoice['client_name']}, invoice #{$invoice['id']} "
             . "for $$amount is overdue. Pay here: {$invoice['payment_link']}";

    send_text($invoice['phone'], $message);
}

Error Handling Reference

HTTP StatusMeaningRecommended Action
200Message queuedLog the `messageId` for delivery tracking
400Bad requestCheck phone format (no `+`) and required fields
401Invalid API keyRegenerate the key in your Walytic dashboard
429Rate limit exceededRetry after a 1-second pause
503Service unavailableRetry with exponential backoff

Add retry logic for transient errors:

TEMPLATE
function send_text_with_retry(string $phone, string $message, int $max_retries = 3): bool {
    for ($i = 0; $i < $max_retries; $i++) {
        if (send_text($phone, $message)) {
            return true;
        }
        sleep(1 << $i); // 1s, 2s, 4s
    }
    error_log("WhatsApp delivery failed after $max_retries attempts to $phone");
    return false;
}

Next Steps

You now have everything needed to send and receive WhatsApp messages from a PHP application. Here is a suggested path forward:

  1. Start a 14-day free trial and connect your WhatsApp number
  2. Add the `walytic_post()` helper to your project and set the environment variables
  3. Send a test text message to verify the connection
  4. Add `webhook.php` to your server and register the URL in the Walytic dashboard
  5. Explore the API reference for all available endpoints and the integrations page for n8n and MCP server options

For teams managing customer conversations at scale, Walytic also includes a shared inbox and CRM so your support agents can handle replies alongside your automated flows.

Ready to go live? Start a 14-day free trial — full API access from day one, yearly plans from $48/year.

Ready to Automate WhatsApp?

Start sending bulk messages, automate follow-ups, and build chatbots, all with flat-rate pricing. No per-message fees.