Back to blogWhatsApp Business

WhatsApp API with PHP: Complete Integration Tutorial [2026]

Víctor Mollá
WhatsApp API con PHP: editor de código enviando mensajes mediante cURL y Cloud API

If you develop in PHP and need to connect your application to WhatsApp, the Cloud API from Meta provides direct access to the entire WhatsApp Business ecosystem through REST requests. In this tutorial, you will learn how to send messages, receive notifications via webhook, manage templates, and build the foundation of a functional chatbot -- all with native PHP, cURL, and Guzzle. This is not about copying snippets: it is about understanding the architecture so you can adapt it to your project. If you are still unclear about what the API is or how it fits into the ecosystem, start with the WhatsApp API guide for developers.

What Is WhatsApp API PHP {#what-is-whatsapp-api-php}

The WhatsApp API PHP is the combination of the official WhatsApp Cloud API from Meta with the PHP language as an HTTP client to consume it. There is no official Meta SDK for PHP -- unlike Python or Node.js --, which means the integration is done directly against the REST API through HTTP requests.

This has a clear advantage: you do not depend on third-party abstractions. You work directly against the endpoints from Meta, with full control over headers, timeouts, retries, and error handling. In 2026, with the Cloud API at its stable version v21.0, PHP remains one of the strongest options for integrating WhatsApp into Laravel, Symfony, WordPress, or any custom backend applications.

The API allows you to send text messages, approved templates, images, documents, locations, and interactive messages with buttons. It also allows receiving incoming messages via webhooks and checking the delivery status of each sent message. If you want to fully understand what the WhatsApp API is and how it works, check out what is WhatsApp API.

Prerequisites for Integration {#prerequisites}

Before writing code, you need to have the following ready:

  • PHP 7.4 or higher. 8.1+ recommended to take advantage of enums, fibers, and performance improvements.
  • The cURL extension enabled in your PHP installation. This is the native HTTP engine you will use for requests to the API.
  • Composer installed to manage dependencies. You will need it if you opt for Guzzle instead of native cURL.
  • A verified Meta Business account with access to the Meta Developer panel.
  • A valid access token. For development, you will use the temporary sandbox token; for production, you will need a permanent system token.
  • A phone number registered on the WhatsApp Business API, either the test number from Meta or your verified business number.
  • A server with HTTPS for the endpoint of the webhook. Meta does not accept connections without SSL.

For step-by-step Meta account setup and obtaining credentials, check out how to set up the WhatsApp API.

Sending Messages with Native cURL {#send-messages-curl}

The most straightforward way to send a message from PHP is to use the cURL extension. No external dependencies, no Composer, no libraries. The endpoint of the Cloud API is https://graph.facebook.com/v21.0/{phone_number_id}/messages.

To send a plain text message, you build the JSON payload with four required fields: messaging_product as "whatsapp", recipient_type as "individual", to with the number in international format (for example, 34612345678), and a text object with the body field.

Enviar Mensajes con cURL Nativo {#enviar-mensajes-curl}

To send an approved template -- required when you initiate the conversation without the user writing first -- you change the type to "template" and include the name, language, and dynamic components:

Para enviar un mensaje de texto plano, construis el payload JSON con cuatro campos obligatorios: messaging_product como "whatsapp", recipient_type como "individual", to con el número en formato internacional (por ejemplo, 34612345678) y un objeto text con el campo body.

The API response returns a message_id to track delivery status. The most common error codes: 131047 (invalid number), 131026 (user does not have WhatsApp), 130429 (you have exceeded the rate limit).

Sending Messages with Guzzle HTTP {#send-messages-guzzle}

If your project uses Composer -- especially in Laravel or Symfony -- Guzzle offers a cleaner interface with automatic exception handling, middlewares, and async request support.

Install Guzzle with Composer:

Si vuestro proyecto usa Composer -- especialmente en Laravel o Symfony --, Guzzle ofrece una interfaz más limpia con gestión automática de excepciones, middlewares y soporte para peticiones asíncronas.

The same message sending with Guzzle:

composer require guzzlehttp/guzzle

The advantage of Guzzle over native cURL goes beyond syntax. You can create middlewares for automatic logging of each request, retries with exponential backoff for 429 errors, and centralized authentication management. In a Laravel project, this integrates directly with the service container to inject the configured client into any service.

Receiving Messages with Webhooks in PHP {#receive-webhooks}

Sending messages is only half the story. To receive what your users write, you need a webhook server -- an HTTP endpoint that Meta sends POST notifications to every time an event occurs.

The setup has two phases. First, the webhook verification:

Enviar mensajes es solo la mitad. Para recibir lo que vuestros usuarios escriben, necesitais un servidor de webhook -- un endpoint HTTP al que Meta envía notificaciones POST cada vez que ocurre un evento.

Second, receiving incoming events. Each message arrives as a POST with a structured JSON payload:

Critical point: respond with HTTP 200 before processing business logic. If it takes longer than 20 seconds, Meta retries the delivery and you end up with duplicate messages. Delegate heavy processing to a queue -- Redis + worker, RabbitMQ, or even a database table with a cron job that processes pending items.

For security, verify the X-Hub-Signature-256 signature that Meta includes in every request:

Punto critico: responded con HTTP 200 antes de procesar la lógica de negocio. Si tardais más de 20 segundos, Meta reintenta el envío y acabais con mensajes duplicados. Delegad el procesamiento pesado a una cola -- Redis + worker, RabbitMQ, o incluso una tabla de base de datos con un cron que procese pendientes.

Best Practices and Common Mistakes {#best-practices}

After working with multiple WhatsApp API integrations in PHP, these are the patterns that make the difference between a prototype and a production system:

Token management. Do not hardcode the access token. Use environment variables ($_ENV or getenv()) and rotate tokens periodically. In Laravel, the .env file with the config() facade is the correct approach.

Rate limiting. The Cloud API allows 80 messages per second on the standard tier. If you are doing bulk messaging, implement a queue with rate control. A simple pattern: insert each message into a table with pending status, and a cron job that processes N records per minute.

Error management. Do not just capture the HTTP status. The API returns specific error codes in the response JSON. Map them to specific actions: retry for temporary errors (429, 500), alert for permanent errors (131047, 131026), and log everything.

Templates. WhatsApp templates require prior approval from Meta. The process takes between 1 and 48 hours. Plan your templates in advance and always have approved alternatives. If you want to dive deeper into template creation, review the guide on WhatsApp API message templates.

Idempotency. If a webhook fails and Meta resends the notification, you may process the same message twice. Store the message_id of each processed message and verify before executing business logic.

Practical Examples by Use Case {#practical-examples}

E-commerce: Order Confirmation

E-commerce: Confirmación de Pedido

Support: Automatic Response with Escalation

Soporte: Respuesta Automática con Derivación

SaaS: Event Notification with Interactive Buttons

SaaS: Notificación de Evento con Botones Interactivos

These examples cover the three fundamental patterns: sending templates for proactive notifications, routing logic for support, and interactive messages for engagement. If you want to compare the integration with other languages, check out the WhatsApp API with Python tutorial. To understand the differences between standard WhatsApp Business and the API, review WhatsApp Business vs API.

Frequently Asked Questions {#faq}

Can you use the WhatsApp API with PHP without external libraries?

Yes. The cURL extension in PHP allows making HTTP requests directly against the Cloud API from Meta without needing Composer or libraries like Guzzle. It is the lightest way to integrate WhatsApp into any PHP project, although for production Guzzle offers better error handling and middlewares.

What is Ultramsg and how does it relate to WhatsApp API PHP?

Ultramsg is a third-party gateway provider that offers a simplified REST API for sending messages via WhatsApp. It does not use the official API from Meta, but rather an unofficial connection based on WhatsApp Web. It is easier to set up but has limitations in stability, volume, and compliance with Meta policies. For professional projects, the official Cloud API is the recommended option.

How much does it cost to use the WhatsApp Business API with PHP?

The Cloud API from Meta is free in terms of access. The cost comes per conversation: each 24-hour window with a user has a price that depends on the category (marketing, utility, authentication, or service) and the country. In Spain, a service conversation initiated by the user costs approximately 0.0477 euros. For a complete breakdown, check the guide on WhatsApp API pricing.

Is it better to use cURL or Guzzle to integrate WhatsApp API in PHP?

It depends on the context. Native cURL works without dependencies and is ideal for simple scripts or environments without Composer. Guzzle is superior for enterprise applications: it offers automatic retries, logging middlewares, async requests, and integrates natively with Laravel and Symfony. If your project already uses Composer, Guzzle is the logical choice.

How do I receive WhatsApp messages on my PHP server?

You need to set up a webhook -- an HTTPS endpoint on your server that Meta calls every time a user writes to you. The endpoint must pass the initial verification (GET with challenge) and process POST notifications with the JSON payload of incoming messages. It is essential to respond with HTTP 200 immediately and process the logic asynchronously.

How GuruSup Simplifies Your WhatsApp Integration {#gurusup-cta}

Everything you have seen in this tutorial -- sending messages, receiving webhooks, managing templates, building routing logic -- is the technical foundation. But taking this to production involves maintaining servers, managing queues, implementing analytics, building a multi-agent inbox, and designing human escalation.

Key GuruSup Features

GuruSup turns all this architecture into a production-ready platform. Instead of maintaining your own webhooks server and writing hundreds of lines of PHP, you get:

  • AI Agents connected directly to WhatsApp Business API that automatically resolve support queries, understanding natural language and accessing your knowledge base.
  • Multi-agent inbox where your team manages conversations that require human intervention, with full history context.
  • Native integrations with CRM, databases, and business tools, without writing connection code.
  • Real-time analytics on response times, resolution rate, and customer satisfaction.

How to Get Started with GuruSup

If what you are looking for is to learn the mechanics of the API, this tutorial gives you the foundation. If what you need is automated WhatsApp customer support working this week, GuruSup solves in minutes what building from scratch takes weeks.

Try GuruSup for free: automate your customer support with AI agents on WhatsApp. No server setup, no webhook management, no code maintenance.

Related articles