Send a WhatsApp message with PHP
By the end, you will have a PHP script that sends a text message through the Nigora Zap API and prints the response.
Prerequisites
Section titled “Prerequisites”- A connected instance. If you have not connected one yet, see Connection.
- The instance ID and token, as in Getting started.
- PHP 8 or newer, with the cURL extension enabled. Check with
php -m.
1. Keep the credentials in the environment
Section titled “1. Keep the credentials in the environment”Do not write the token in the code. Read it from environment variables:
export NIGORA_INSTANCIA_ID="cole-aqui-o-id-da-instancia"export NIGORA_TOKEN="cole-aqui-o-token"2. Create the script
Section titled “2. Create the script”Save it as enviar.php:
<?php$instanciaId = getenv('NIGORA_INSTANCIA_ID');$token = getenv('NIGORA_TOKEN');if (!$instanciaId || !$token) { fwrite(STDERR, "Defina NIGORA_INSTANCIA_ID e NIGORA_TOKEN.\n"); exit(1);}
$url = "https://api.zap.nigora.com.br/v1/instances/{$instanciaId}/messages/text";$corpo = json_encode([ 'to' => '5511999999999', 'text' => 'Olá! Esta mensagem saiu pela API.',], JSON_UNESCAPED_UNICODE);
$curl = curl_init($url);curl_setopt_array($curl, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $corpo, CURLOPT_HTTPHEADER => [ "Authorization: Bearer {$token}", 'Content-Type: application/json', ], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15,]);
$resposta = curl_exec($curl);if ($resposta === false) { fwrite(STDERR, 'Falha de rede: ' . curl_error($curl) . "\n"); exit(1);}$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);curl_close($curl);
echo "Status HTTP: {$status}\n{$resposta}\n";exit($status < 300 ? 0 : 1);Replace 5511999999999 with the phone of the person who will receive the message, with country and area codes. The API ignores everything that is not a digit and adds the 55 when the number has 10 or 11 digits.
3. Run it
Section titled “3. Run it”php enviar.phpExpected result:
Status HTTP: 202{"id":"…","status":"queued"}The 202 means the message entered the queue. It has not been delivered yet. Keep the id: it is how you match the response to the message.sent and message.status events, which arrive by webhook.
If something goes wrong
Section titled “If something goes wrong”| Status | Code | What to do |
|---|---|---|
400 |
invalid_phone |
Fix the phone: it must have 12 or 13 digits including the 55 |
401 |
invalid_token |
Check the token and the instance ID |
402 |
instance_suspended |
The instance is suspended or has a pending payment |
422 |
contact_opted_out |
The contact asked not to receive messages |
Next steps
Section titled “Next steps”- Sending messages: replies, queue and tracking the result.
- Receive messages by webhook: see the replies arrive in your system.
- Sending media: image, video, audio and document.