# Send a WhatsApp message with PHP and the Cloud API

> Send WhatsApp text and template messages from plain PHP 8.5 with cURL and Cloud API v26.0, read the message ID and retry only on 130429 and 131056.

Published 2026-11-04. Z-API Omni team.

Send a WhatsApp message from PHP with one cURL POST to `https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages`. Add a Bearer token, an explicit `Content-Type: application/json` header and a `json_encode`d body. A successful call returns an ID in `messages[0].id`. That ID means Meta accepted the message, and delivery is reported later by webhook. The script below runs on the PHP 8.5 CLI with the `curl` extension and no packages.

## What you need

PHP 8.5 is the newest branch, and 8.5.12 is the current patch release ([PHP supported versions](https://www.php.net/supported-versions.php), [php.net](https://www.php.net/), accessed 2026-11-04). The script also runs on 8.3 and 8.4. Check that `curl` appears in the output of `php -m` before you start.

The token, the phone number ID and the Graph API version come from environment variables. They use the same names as in [the Python version](/academy/articles/send-whatsapp-message-python-cloud-api/) and [the Node.js version](/academy/articles/send-whatsapp-message-nodejs-cloud-api/) of this guide. [The Cloud API test number guide](/academy/articles/whatsapp-cloud-api-test-number-get-started/) gives you the first two, and [Cloud API access tokens](/academy/articles/whatsapp-cloud-api-access-tokens-system-user/) covers a token you can leave running.

Meta's send sample uses v26.0 ([Meta send messages, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages)). The Graph API versions table lists v26.0 as the newest, released 29 July 2026 ([Graph API versions, accessed 2026-11-04](https://developers.facebook.com/docs/graph-api/changelog/versions/)).

```bash
php -m | grep curl
export WHATSAPP_TOKEN="ACCESS_TOKEN"
export PHONE_NUMBER_ID="PHONE_NUMBER_ID"
export GRAPH_VERSION="v26.0"
```

`GRAPH_BASE` is optional. It defaults to `https://graph.facebook.com`, and setting it lets you run the script against a local mock, as the last section shows.

## The script

```php
<?php
// send_whatsapp.php
declare(strict_types=1);

const RETRY_CODES = [130429, 131056]; // throughput and pair rate: wait, then retry

final class WhatsAppError extends RuntimeException
{
    public function __construct(public readonly int $status, public readonly array $error)
    {
        $code = (int) ($error['code'] ?? 0);
        $message = $error['message'] ?? 'no error object in the response';
        $details = $error['error_data']['details'] ?? '';
        parent::__construct("HTTP $status, code $code: $message $details", $code);
    }
}

function env_or_exit(string $name): string
{
    $value = getenv($name);
    if ($value === false || $value === '') {
        fwrite(STDERR, "Set the $name environment variable\n");
        exit(1);
    }
    return $value;
}

function post_message(string $url, string $token, array $payload): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json', "Authorization: Bearer $token"],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT => 15,
    ]);
    $body = curl_exec($ch);
    if ($body === false) {
        throw new RuntimeException('cURL error: ' . curl_error($ch));
    }
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    try {
        $data = json_decode(json: $body, associative: true, flags: JSON_THROW_ON_ERROR);
    } catch (JsonException) {
        throw new RuntimeException("HTTP $status, body is not JSON: " . substr($body, 0, 200));
    }
    if (!is_array($data)) {
        throw new RuntimeException("HTTP $status, unexpected body: " . substr($body, 0, 200));
    }
    if ($status >= 400 || isset($data['error'])) {
        throw new WhatsAppError($status, (array) ($data['error'] ?? []));
    }
    return $data;
}

function send(string $url, string $token, array $payload, int $attempts = 4): array
{
    for ($attempt = 0; ; $attempt++) {
        try {
            return post_message($url, $token, $payload);
        } catch (WhatsAppError $e) {
            $code = $e->getCode();
            if (!in_array($code, RETRY_CODES, true) || $attempt === $attempts - 1) {
                throw $e;
            }
            // 131056: Meta's 4^X schedule (1, 4, 16 s). 130429: this script's choice (1, 2, 4 s).
            $wait = $code === 131056 ? 4 ** $attempt : 2 ** $attempt;
            fwrite(STDERR, "code $code, retrying in {$wait}s\n");
            sleep($wait);
        }
    }
}

function text_payload(string $to, string $body): array
{
    return [
        'messaging_product' => 'whatsapp',
        'recipient_type' => 'individual',
        'to' => $to,
        'type' => 'text',
        'text' => ['preview_url' => false, 'body' => $body],
    ];
}

function template_payload(string $to, string $name, string $language, array $params): array
{
    $template = ['name' => $name, 'language' => ['code' => $language]];
    if ($params !== []) { // name=value becomes a named parameter, a bare value a positional one
        $parameters = [];
        foreach ($params as $p) {
            if (str_contains($p, '=')) {
                [$key, $value] = explode('=', $p, 2);
                $parameters[] = ['type' => 'text', 'parameter_name' => $key, 'text' => $value];
            } else {
                $parameters[] = ['type' => 'text', 'text' => $p];
            }
        }
        $template['components'] = [['type' => 'body', 'parameters' => $parameters]];
    }
    return [
        'messaging_product' => 'whatsapp',
        'recipient_type' => 'individual',
        'to' => $to,
        'type' => 'template',
        'template' => $template,
    ];
}

$args = array_slice($argv, 1);
$kind = $args[0] ?? '';
if (!(($kind === 'text' && count($args) === 3) || ($kind === 'template' && count($args) >= 4))) {
    fwrite(STDERR, "usage: php send_whatsapp.php text TO BODY | template TO NAME LANGUAGE [PARAMS...]\n");
    exit(2);
}

$token = env_or_exit('WHATSAPP_TOKEN');
$phoneNumberId = env_or_exit('PHONE_NUMBER_ID');
$version = getenv('GRAPH_VERSION') ?: 'v26.0';
$base = rtrim(getenv('GRAPH_BASE') ?: 'https://graph.facebook.com', '/');
$url = "$base/$version/$phoneNumberId/messages";

$payload = $kind === 'text'
    ? text_payload($args[1], $args[2])
    : template_payload($args[1], $args[2], $args[3], array_slice($args, 4));

try {
    $data = send($url, $token, $payload);
} catch (WhatsAppError $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    fwrite(STDERR, 'fbtrace_id: ' . ($e->error['fbtrace_id'] ?? 'none') . "\n");
    fwrite(STDERR, match ($e->getCode()) {
        131047 => "Window closed: send an approved template instead.\n",
        190 => "Token expired: create a new access token.\n",
        default => '',
    });
    exit(1);
} catch (Exception $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
}

$message = $data['messages'][0] ?? [];
echo 'accepted: ' . trim(($message['id'] ?? '?') . ' ' . ($message['message_status'] ?? '')) . "\n";
echo 'wa_id: ' . ($data['contacts'][0]['wa_id'] ?? '') . "\n";
```

## Why the cURL options look like this

`CURLOPT_POST` on its own sends "the `application/x-www-form-urlencoded` header". Pass an array to `CURLOPT_POSTFIELDS` and "the `Content-Type` header will be set to `multipart/form-data`" ([PHP cURL constants, accessed 2026-11-04](https://www.php.net/manual/en/curl.constants.php)). Meta expects JSON, so the script passes the encoded string and sets `Content-Type: application/json` itself.

`CURLOPT_TIMEOUT` defaults to `0`, "meaning that functions never time out during transfer", and the connect timeout defaults to 300 seconds. Meta documents no client timeout, so the 5 and 15 seconds are this script's choice.

`curl_exec` returns `false` only when the transfer fails. php.net warns that "response status codes which indicate errors (such as `404 Not found`) are not regarded as failure" ([curl_exec, accessed 2026-11-04](https://www.php.net/manual/en/function.curl-exec.php)). A 400 from Meta therefore comes back as a normal string. The script reads the status with `curl_getinfo($ch, CURLINFO_RESPONSE_CODE)` and checks the decoded body for an `error` object.

The script never calls `curl_close()`. It "has no effect" since PHP 8.0 and "has been _DEPRECATED_ as of PHP 8.5.0", so on 8.5 it only adds a deprecation notice ([curl_close, accessed 2026-11-04](https://www.php.net/manual/en/function.curl-close.php)).

`JSON_THROW_ON_ERROR` makes both JSON calls throw a `JsonException` "instead of setting the global error state" ([PHP JSON constants, accessed 2026-11-04](https://www.php.net/manual/en/json.constants.php)). The two `UNESCAPED` flags keep accents and URLs readable in your logs. Both encodings are valid JSON.

## Send a text inside the window

```bash
php send_whatsapp.php text +16505551234 "Your order shipped"
```

Free-form text goes through only inside the customer service window, which a message from the user opens. `body` takes up to 4096 characters. With `preview_url` set to `true`, the client tries to preview the first URL, which must start with `http://` or `https://` ([Meta text messages, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/text-messages)). Write `to` in E.164 with the country code; [the E.164 normalization guide](/academy/articles/whatsapp-phone-number-format-e164-normalization/) covers the edge cases.

Given Meta's documented response, the script prints:

```text
accepted: wamid.HBgLMTY0NjcwNDM1OTUVAgARGBI1RjQyNUE3NEYxMzAzMzQ5MkEA
wa_id: 16505551234
```

## Send a template outside the window

"Template messages are the only type of message that can be sent to WhatsApp users outside of a customer service window" ([Meta template fundamentals, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/overview)). This command rebuilds Meta's `order_confirmation` example with two named body parameters. Swap in one of your own approved templates and its language code:

```bash
php send_whatsapp.php template +16505551234 order_confirmation en_US first_name=Jessica order_number=SKBUP2-4CPIG9
```

Each `name=value` argument becomes an entry with `parameter_name`. Bare values (`Jessica SKBUP2-4CPIG9`) fill positional `{{1}}` variables. `explode('=', $p, 2)` splits on the first `=` only, but a positional value that contains `=` is still read as named. With no parameters, the script leaves `components` out, so `json_encode` never writes an empty `[]` for it. [Template variables](/academy/articles/whatsapp-template-variables-named-parameters/) covers header and button parameters.

## Read the response and handle errors

Store `messages[0].id`. Each status webhook for that message carries the same ID, so you can match `sent`, `delivered`, `read` and `failed` to your record ([status webhooks](/academy/articles/whatsapp-message-status-webhooks-sent-delivered-read-failed/)). The script prints `message_status` only when the response includes it; the Python guide lists its values. Keep `wa_id` next to the number you sent, since Meta says the WhatsApp ID "may not always match" the phone number ([Meta text webhook, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text)).

Meta tells you to "build your app's error handling logic around `code` values and `details` payload properties" ([Meta error codes, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes)). The same page marks `error_subcode` as "Deprecated. Will not be returned in v16.0+ responses." The script branches on `code`, prints `details` and logs `fbtrace_id`.

| Code | Meta's details | What the script does |
|---|---|---|
| 130429 | "Cloud API message throughput has been reached." | Retries after 1, 2 and 4 s |
| 131056 | "Too many messages sent from the sender phone number to the same recipient phone number in a short period of time." | Retries after 1, 4 and 16 s |
| 131047 | "More than 24 hours have passed since the recipient last replied to the sender number." | Stops and tells you to send a template |
| 190 | "Your access token has expired." | Stops and tells you to get a new token |
| Any other | Varies by code | Stops and prints code, message and details |

The 131056 waits follow Meta's pair-rate advice ([Meta about the platform, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/about-the-platform)). Meta says to "retry after 4^X seconds (starting with X=0 and increasing X by 1 after each failure)". Meta's throughput page gives no backoff schedule for 130429, so the 1, 2 and 4 seconds there are this script's choice. For steady volume, pace sends before you hit the limit, as in [the outbound send queue guide](/academy/articles/whatsapp-outbound-send-queue-rate-limiter/). [Cloud API rate limits](/academy/articles/whatsapp-cloud-api-rate-limits-throughput-pair-rate/) explains both limits.

Some errors never reach this script. Meta returns Cloud API errors "either synchronously as a Graph API response" or asynchronously by webhook ([Meta error codes, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes)). So some errors arrive only in a `failed` status webhook. Handle the same codes in your webhook consumer and look up the rest in [the Cloud API error codes reference](/academy/articles/whatsapp-cloud-api-error-codes-reference/).

## Test the retry path against a mock

PHP's built-in server can stand in for Meta. This router answers every request with Meta's 130429 error example. The 400 status is the mock's choice, because Meta doesn't document an HTTP status per error code.

```php
<?php
// mock.php
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => [
    'message' => '(#130429) Rate limit hit',
    'type' => 'OAuthException',
    'code' => 130429,
    'error_data' => ['messaging_product' => 'whatsapp', 'details' => 'Cloud API message throughput has been reached.'],
    'fbtrace_id' => 'Az8or2yhqkZfEZ-_4Qn_Bam',
]]);
```

Start it in one terminal and run the script in another:

```bash
php -S localhost:9000 mock.php
GRAPH_BASE=http://localhost:9000 php send_whatsapp.php text +16505551234 "test"
```

After about seven seconds the script gives up and prints:

```text
code 130429, retrying in 1s
code 130429, retrying in 2s
code 130429, retrying in 4s
HTTP 400, code 130429: (#130429) Rate limit hit Cloud API message throughput has been reached.
fbtrace_id: Az8or2yhqkZfEZ-_4Qn_Bam
```

Change `130429` to `131056` in `mock.php` to see the 1, 4 and 16 second waits, or to `131047` to see the script stop on the first call.

*Z-API Omni team*
