Paramclasses Academy - Blog

Tutorials Details

←
Post 15 of 20
→

WhatsApp API Integration with PHP and MySQL: A Practical Guide

 WhatsApp API Integration with PHP and MySQL: A Practical Guide

November 27, 2026

 

WhatsApp API Integration with PHP and MySQL: A Practical Guide

Introduction

Businesses often need more than the ability to send a WhatsApp message. They need a complete system to manage customer details, send notifications, receive replies, store conversations and track message delivery.

This is where PHP, MySQL and the WhatsApp Business Platform (Cloud API) work together.

PHP handles the server-side logic, MySQL stores customer and message information, and the WhatsApp Cloud API connects your application with WhatsApp.

For example, imagine an educational institute receives course enquiries through its website. When a student submits an enquiry, the system can save the student's details in MySQL and send an automated WhatsApp confirmation using PHP. When the student replies, a webhook can receive the message and store it in the database.

In this practical guide by Param Classes, we will understand the architecture and learn how to build the basic integration step by step.

1. Understanding the Integration Architecture

Before writing code, understand the role of each technology.

  • PHP: Processes website requests, communicates with the WhatsApp API and handles webhook events.

  • MySQL: Stores customer information, outgoing messages, incoming replies and delivery statuses.

  • WhatsApp Cloud API: Sends messages through your registered WhatsApp Business phone number.

  • Webhooks: Notify your PHP application when customers send messages or message statuses change.

How the complete system works

  1. A customer submits a form or interacts with your business.

  2. PHP validates the information.

  3. Customer details are saved in MySQL.

  4. PHP sends a request to the WhatsApp Cloud API.

  5. WhatsApp processes the message.

  6. Meta sends message updates to your webhook.

  7. PHP receives the updates and stores them in MySQL.

This architecture can be used for educational institutes, online stores, hospitals, service companies and other businesses.

2. Requirements Before Starting

Prepare these items before beginning development:

  1. PHP 8.0 or a compatible supported PHP version.

  2. MySQL database.

  3. Apache or another PHP-compatible web server.

  4. A Meta developer application with the WhatsApp product configured.

  5. A WhatsApp Business Account and configured phone number.

  6. A suitable access token with the required permissions.

  7. WhatsApp Phone Number ID.

  8. Meta App Secret for webhook signature verification.

  9. A public HTTPS URL for your webhook endpoint.

You can begin testing with the available Meta developer test setup. For production, configure the business assets and credentials properly.

Important: Use the currently supported Graph API version shown in Meta's documentation. The examples below use vXX.X as a placeholder, not an actual API version.

3. Create a MySQL Database

The first step is to create a database for customer and message information.

For example, create a database named:

whatsapp_business

You can use phpMyAdmin or the MySQL command line.

Create a customers table

CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(150) NOT NULL,
    phone VARCHAR(25) NOT NULL UNIQUE,
    opt_in TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This table stores customer names, phone numbers and messaging permission status.

Create a messages table

CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT NULL,
    whatsapp_message_id VARCHAR(255) UNIQUE,
    direction ENUM('incoming','outgoing') NOT NULL,
    message_type VARCHAR(50),
    message_text TEXT,
    status VARCHAR(50) DEFAULT 'received',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (customer_id)
        REFERENCES customers(id)
        ON DELETE SET NULL
);

The messages table stores both incoming and outgoing messages. The unique WhatsApp message ID also helps prevent duplicate records when webhook notifications are retried.

4. Connect PHP with MySQL Using PDO

PDO is a PHP database access method that supports prepared statements. Prepared statements help protect database queries from SQL injection.

Create a file named db.php:

<?php

$host = "localhost";
$dbname = "whatsapp_business";
$username = "root";
$password = "";

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    error_log($e->getMessage());
    exit("Database connection failed.");
}

These credentials are only illustrative for a local development environment. On a live server, use your actual database credentials and keep them outside publicly accessible files.

5. Store WhatsApp API Credentials Securely

Your PHP application needs credentials to communicate with Meta.

Typical configuration values include:

  • WHATSAPP_ACCESS_TOKEN

  • WHATSAPP_PHONE_NUMBER_ID

  • WHATSAPP_API_VERSION

  • META_APP_SECRET

  • WHATSAPP_VERIFY_TOKEN

Store these values in environment variables or a properly protected .env configuration managed by your application.

For example, PHP can read an environment variable like this:

$accessToken = getenv('WHATSAPP_ACCESS_TOKEN');
$phoneNumberId = getenv('WHATSAPP_PHONE_NUMBER_ID');
$apiVersion = getenv('WHATSAPP_API_VERSION');

Do not place real access tokens or app secrets directly in publicly accessible PHP files, HTML, JavaScript or Git repositories.

6. Create a PHP Function to Send WhatsApp Messages

Now let's connect PHP with the WhatsApp Cloud API.

The API uses an HTTP request to the Graph API messages endpoint. The request includes your phone number ID, access token and message details.

Create a file named send-message.php:

<?php

function sendWhatsAppMessage($to, $message) {

    $accessToken = getenv('WHATSAPP_ACCESS_TOKEN');
    $phoneNumberId = getenv('WHATSAPP_PHONE_NUMBER_ID');
    $apiVersion = getenv('WHATSAPP_API_VERSION');

    if (!$accessToken || !$phoneNumberId || !$apiVersion) {
        throw new RuntimeException("WhatsApp configuration is missing.");
    }

    $url = "https://graph.facebook.com/"
         . $apiVersion . "/"
         . $phoneNumberId . "/messages";

    $payload = [
        "messaging_product" => "whatsapp",
        "recipient_type" => "individual",
        "to" => $to,
        "type" => "text",
        "text" => [
            "body" => $message
        ]
    ];

    $ch = curl_init($url);

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

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);

    curl_close($ch);

    if ($response === false) {
        throw new RuntimeException("API request failed: " . $error);
    }

    $result = json_decode($response, true);

    if ($httpCode < 200 || $httpCode >= 300) {
        error_log("WhatsApp API error: " . $response);
        throw new RuntimeException("WhatsApp API returned an error.");
    }

    return $result;
}

This is an illustrative text-message function. It assumes the recipient and message are valid and that the account is permitted to send this type of message.

Understand the important parameters

  • messaging_product: Identifies WhatsApp as the messaging product.

  • to: The recipient's WhatsApp phone number in the required international format.

  • type: Defines the message type.

  • text.body: Contains the message content.

  • Authorization: Carries the access token required for the API request.

The API response can contain a WhatsApp message ID. Save that ID in your database so you can connect later delivery and read-status notifications with the original message.

7. Save Customers and Outgoing Messages

Before sending a message, your application should verify that the customer exists and is eligible to receive the communication.

For example:

<?php

require "db.php";
require "send-message.php";

$phone = "919876543210";
$message = "Hello! Thank you for contacting our institute.";

$stmt = $pdo->prepare(
    "SELECT id, opt_in FROM customers WHERE phone = ?"
);
$stmt->execute([$phone]);

$customer = $stmt->fetch();

if (!$customer || !$customer['opt_in']) {
    exit("Customer not found or permission not available.");
}

$result = sendWhatsAppMessage($phone, $message);

$whatsappMessageId =
    $result['messages'][0]['id'] ?? null;

if ($whatsappMessageId) {

    $stmt = $pdo->prepare(
        "INSERT INTO messages
        (customer_id, whatsapp_message_id, direction,
         message_type, message_text, status)
        VALUES (?, ?, 'outgoing', 'text', ?, 'accepted')"
    );

    $stmt->execute([
        $customer['id'],
        $whatsappMessageId,
        $message
    ]);
}

The phone number and message are sample values. In a real application, receive them through a validated form or a trusted backend workflow. Never assume that a successful API request means the message has already been delivered.

8. Receive Incoming Messages Using PHP Webhooks

Sending messages is only one part of the integration. Businesses also need to receive customer replies.

A webhook is a publicly accessible HTTPS endpoint that receives event notifications from Meta.

For example, when a student replies to an institute's WhatsApp message, Meta can send a webhook notification to your PHP application.

Create a file named webhook.php.

Step 1: Verify the webhook endpoint

Meta sends a GET request containing verification parameters when you configure the callback URL.

<?php

$verifyToken = getenv('WHATSAPP_VERIFY_TOKEN');

if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    $mode = $_GET['hub_mode'] ?? '';
    $token = $_GET['hub_verify_token'] ?? '';
    $challenge = $_GET['hub_challenge'] ?? '';

    if ($mode === 'subscribe' && hash_equals($verifyToken, $token)) {
        http_response_code(200);
        echo $challenge;
        exit;
    }

    http_response_code(403);
    exit;
}

PHP converts dots in incoming query parameter names into underscores, which is why the example reads hub_mode and hub_challenge.

Step 2: Receive and validate POST notifications

For production, verify the signature using your Meta App Secret before trusting the notification.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $rawBody = file_get_contents('php://input');

    $appSecret = getenv('META_APP_SECRET');

    $signature = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';

    $expected = 'sha256=' . hash_hmac(
        'sha256',
        $rawBody,
        $appSecret
    );

    if (!$appSecret || !hash_equals($expected, $signature)) {
        http_response_code(401);
        exit;
    }

    $data = json_decode($rawBody, true);

    if (!is_array($data)) {
        http_response_code(400);
        exit;
    }

    // Process and store valid WhatsApp webhook events.
    http_response_code(200);
    echo "EVENT_RECEIVED";
    exit;
}

This is the signature-validation foundation. Add the actual event-processing logic before deploying it. Also handle unexpected payload structures and log failures safely.

9. Store Incoming Messages in MySQL

WhatsApp webhook payloads can contain incoming messages and status updates. Your application should inspect the event structure and process the relevant fields.

A simplified incoming-message extraction looks like this:

$messages = $data['entry'][0]['changes'][0]['value']['messages'] ?? [];

foreach ($messages as $item) {

    $messageId = $item['id'] ?? null;
    $sender = $item['from'] ?? null;
    $messageText = $item['text']['body'] ?? '';

    if (!$messageId || !$sender) {
        continue;
    }

    // Find the customer by phone number.
    // Insert the incoming message using a prepared statement.
    // Use the WhatsApp message ID to prevent duplicates.
}

This snippet illustrates the payload fields for a text message; other message types, such as images, documents, audio and interactive replies, need their own handling.

Use a database uniqueness constraint and safe insert logic to avoid processing the same webhook event more than once.

10. Track Message Delivery Status

The WhatsApp platform can send status notifications such as:

  • Sent: The message has been accepted and sent for processing.

  • Delivered: The message has been delivered to the recipient.

  • Read: The recipient has read the message, when read information is available.

  • Failed: The message could not be delivered.

Your webhook should extract status events and update the matching message record using the WhatsApp message ID.

This helps businesses understand whether their notifications are reaching customers and identify failed messages that may need investigation.

11. Understand Customer Service Windows and Templates

WhatsApp messaging is subject to platform rules.

When a customer messages your business, a customer service window applies. During that window, businesses can respond using permitted free-form messages. Business-initiated messages outside the applicable window generally require an approved message template.

For example, a student asks about a programming course. Your institute can respond to that enquiry within the applicable service window. If the institute later wants to send a course announcement outside that window, it should use an appropriate approved template and follow the relevant messaging requirements.

Always check the current WhatsApp Business Messaging Policy and template rules before launching a messaging workflow.

12. Real-World Example: An Educational Institute

Imagine Param Classes wants to automate its course enquiry process.

A student visits the website and submits:

  • Name

  • Phone number

  • Interested course

  • WhatsApp communication permission

The PHP application validates the form and stores the details in MySQL. It then sends an appropriate WhatsApp confirmation through the Cloud API.

When the student replies, the webhook receives the message and stores it in the database. The institute's team can view the conversation, follow up with the student and update the enquiry status.

This creates a connected workflow instead of managing every enquiry manually.

13. Best Practices for a Production-Ready Integration

Before launching your application, follow these practices:

  1. Protect credentials: Keep tokens and secrets in secure environment configuration.

  2. Use HTTPS: Your webhook must use a valid HTTPS endpoint.

  3. Validate input: Check phone numbers, message content and form submissions.

  4. Use prepared statements: Avoid building SQL queries by joining untrusted input.

  5. Verify webhook signatures: Check X-Hub-Signature-256 using your App Secret.

  6. Prevent duplicates: Store and check unique WhatsApp message IDs.

  7. Log errors: Record API and database errors without exposing private credentials.

  8. Use queues: For larger workloads, process outgoing messages through background jobs.

  9. Handle retries: Retry temporary failures carefully and avoid duplicate sends.

  10. Respect customer permission: Maintain opt-in records and honor opt-out requests.

14. Common Integration Problems

Problem Possible reason
Invalid access token Token expired or incorrect
API permission error Required permission is missing
Message not delivered Recipient or account restrictions
Webhook verification failed Callback URL or verify token mismatch
Database insert failed Incorrect schema or database credentials
Duplicate messages Webhook or application retry not handled
cURL error Server connection or SSL configuration problem

Check the API response, server logs and Meta developer dashboard when troubleshooting.

Frequently Asked Questions (FAQs)

Q1. Can I integrate WhatsApp API with PHP?

Yes. PHP can send HTTP requests to the WhatsApp Cloud API and process webhook notifications.

Q2. Why is MySQL needed?

MySQL can store customer information, communication permissions, message history and delivery statuses.

Q3. Can PHP send automatic WhatsApp messages?

Yes. A PHP application can trigger messages based on website forms, orders, appointments and other business events, subject to WhatsApp's messaging rules.

Q4. Can I receive customer replies in my database?

Yes. Configure a webhook endpoint, validate notifications and write the relevant incoming message data to MySQL.

Q5. Is this integration free?

PHP and MySQL can be used without separate software licence fees in many setups, but WhatsApp Business Platform messaging charges, hosting and other infrastructure costs may apply. Check current Meta pricing for your account and market.

Conclusion

Integrating WhatsApp API with PHP and MySQL allows businesses to build a connected communication system. PHP manages the application logic, MySQL stores customer and message records, the WhatsApp Cloud API sends messages, and webhooks bring customer replies and delivery updates back into the application.

Start with a small test integration, secure your credentials, validate webhook events and test the complete message lifecycle before using the system with real customers.

At Param Classes, learners can strengthen their practical development skills by understanding how APIs, PHP, databases and automation work together in real-world applications.

←
Post 15 of 20
→