CRM-backed WhatsApp workflows

WhatsApp Business API integration in PHP with source code

Build a practical PHP integration for WhatsApp Business API: configure Meta assets, verify webhooks, send approved templates, process delivery statuses, and store every event against CRM contacts, deals, tasks, and reports.

PHP webhook receiver Template send function CRM activity logging
Response Time
-38% Faster
Lead Assignment
Auto-Routed
Active Chats (4)
John Doe (Lead)
Pricing inquiry...
John Doe
High Priority
Hi, I'm interested in the Enterprise plan for WhatsApp API.
Hello John. I've assigned your inquiry to our Enterprise team. They will share the details shortly.
Bot: Ticket #4029 Created in CRM

Implementation overview

A reliable WhatsApp Business API PHP integration has four parts: Meta setup, a secure webhook receiver, outbound message sending, and durable storage of every inbound, outbound, delivery and failure event. Treat WhatsApp message IDs as idempotency keys and design every handler for retries.

Once events are normalized, connect them to CRM records and trigger workflow actions such as owner assignment, follow-up tasks, callback reminders, lead-source attribution and failed-send alerts. ZniCRM supports reusable Webhooks, Workflows, WhatsApp logs and campaign reports for this operating layer.

Faster handoffs

Route new WhatsApp leads to the right owner with contact context, source, campaign and next action.

CRM alignment

Map every WhatsApp exchange to contacts, deals, reminders, follow-up alerts and reports.

At a Glance

Implementation plan with PHP =

  • Store WABA ID, phone number ID, access token, verify token and app secret securely.
  • Build one webhook endpoint for GET verification and POST message/status events.
  • Send approved templates outside the customer service window and session replies inside it.
  • Log message IDs, statuses, contact matches, errors and retries in CRM.
Use the four steps below as the build checklist before connecting production traffic.
Workflow

Step-by-step guide

Four steps you can follow from prerequisites to a stable, measurable workflow.

1

Set up Meta assets

Create the app, connect the WhatsApp product, select the phone number, and keep production credentials outside the codebase.

2

Build the PHP webhook

Respond to Meta verification, validate POST signatures, return 200 quickly, and queue CRM work outside the request.

3

Send templates and sessions

Use approved templates for business-initiated outreach and session messages only when the user has opened the window.

4

Store in CRM and secure access

Link chats to CRM contacts, deals, tasks, templates and reports; monitor failed sends, stale tokens and missing webhooks.

PHP source code

Starter blueprint for WhatsApp Cloud API in PHP

Use these snippets as a production-minded starting point. Replace placeholders with environment variables and route CRM writes through your own models, queue or ZniCRM integration layer.

1. Environment values

Never hard-code access tokens or app secrets in PHP files. Keep these values in your server environment, secret manager, or deployment config.

WHATSAPP_GRAPH_VERSION=vXX.X
WHATSAPP_PHONE_NUMBER_ID=1234567890
WHATSAPP_WABA_ID=1234567890
WHATSAPP_ACCESS_TOKEN=EAAB...
WHATSAPP_VERIFY_TOKEN=choose-a-private-random-token
META_APP_SECRET=app-secret-from-meta

2. Webhook verification endpoint

The same endpoint should handle the GET challenge and POST events. Keep the verification response plain and fast.

<?php
// public/whatsapp-webhook.php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $mode = $_GET['hub_mode'] ?? $_GET['hub.mode'] ?? '';
    $token = $_GET['hub_verify_token'] ?? $_GET['hub.verify_token'] ?? '';
    $challenge = $_GET['hub_challenge'] ?? $_GET['hub.challenge'] ?? '';

    if ($mode === 'subscribe' && hash_equals(getenv('WHATSAPP_VERIFY_TOKEN'), $token)) {
        header('Content-Type: text/plain');
        echo $challenge;
        exit;
    }

    http_response_code(403);
    exit;
}

3. POST handler with signature check

Verify the signature, acknowledge quickly, then queue CRM work. Use message IDs to avoid duplicate activity when Meta retries a webhook.

<?php
$raw = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $raw, getenv('META_APP_SECRET'));

if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    exit;
}

$payload = json_decode($raw, true);
http_response_code(200);

foreach (($payload['entry'] ?? []) as $entry) {
    foreach (($entry['changes'] ?? []) as $change) {
        $value = $change['value'] ?? [];
        foreach (($value['messages'] ?? []) as $message) {
            queueCrmActivity([
                'message_id' => $message['id'] ?? null,
                'phone' => $message['from'] ?? null,
                'type' => $message['type'] ?? 'unknown',
                'direction' => 'inbound',
                'payload' => $message,
            ]);
        }
        foreach (($value['statuses'] ?? []) as $status) {
            updateCrmMessageStatus($status['id'] ?? null, $status['status'] ?? null, $status);
        }
    }
}

4. Send an approved template

Use templates for business-initiated messages. Store the returned message ID so delivery webhooks can update the same CRM activity row.

<?php
function sendWhatsAppTemplate(string $to, string $template, string $language = 'en_US'): array
{
    $url = sprintf(
        'https://graph.facebook.com/%s/%s/messages',
        getenv('WHATSAPP_GRAPH_VERSION'),
        getenv('WHATSAPP_PHONE_NUMBER_ID')
    );

    $body = [
        'messaging_product' => 'whatsapp',
        'to' => $to,
        'type' => 'template',
        'template' => [
            'name' => $template,
            'language' => ['code' => $language],
        ],
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . getenv('WHATSAPP_ACCESS_TOKEN'),
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode($body),
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    $decoded = json_decode($response ?: '{}', true);
    logWhatsAppApiAttempt($to, $template, $httpCode, $decoded);
    return ['http_code' => $httpCode, 'body' => $decoded];
}
Capabilities

Engineering checklist

A production-ready integration needs reliable event ingestion, safe outbound messaging, monitoring, contact matching and CRM follow-up automation. Review Webhooks and Workflows for event-driven patterns.

Key takeaways

  • Use one HTTPS PHP webhook route for verification, messages and statuses.
  • Store message IDs and delivery states as CRM activity records.
  • Handle token rotation, failed sends and retry queues cleanly.

API Safety

  • Validate phone numbers and template names before sending
  • Map API error codes to retry, alert or manual review actions
  • Store request and response summaries without exposing tokens

Observability

  • Structured logs by message ID, contact, template and owner
  • Alerts for failed sends, missing delivery statuses and expired credentials
  • Replay queues for idempotent retries

Security

  • Webhook signature verification with the Meta app secret
  • Least-privilege access tokens stored outside the repository
  • PII controls for message body, phone number and contact history

Data Mapping

  • Contact match rules by WhatsApp phone and CRM owner
  • Deal, task and reminder updates from inbound intent
  • Message-to-activity sync for reports and audits

Template Ops

  • Template mapping inside WhatsApp integration settings
  • Approval status checks before campaign or follow-up sends
  • Fallback tasks when a template fails or a user replies

Where this PHP integration performs best

Use this setup when WhatsApp messages need to become CRM records, not just API responses in a log file.

Sales: faster lead-to-deal movement

Capture inbound WhatsApp enquiries, match them to contacts, create follow-up tasks, and keep deal movement visible to managers.

Inbound lead capture
Convert webhook payloads into CRM contacts with source, campaign and message context.
Follow-up workflow
Create owner tasks, callbacks and reminders from the same PHP webhook event.

Support: Context-rich help

Keep response times low and quality high with assignments, internal notes, and customer context right in the chat window.

  • Route incoming messages to the right support owner.
  • Conversation history + customer profile
  • SLA alerts and escalations

Ops: standardized webhook workflows

Reduce manual work with queue-based delivery, reusable webhook definitions, reminders and reporting that match your process.

  • Store message IDs and delivery status against CRM activity.
  • Auto tasks, reminders, and stage updates
  • Reporting to optimize staffing

Connect your WhatsApp stack

Bring lead sources, reporting, customer history and automation together so the PHP webhook flow stays consistent across sales, support and operations. Handle token rotation, failed sends and retries cleanly.

WhatsApp API
Gmail
Slack
Zapier
Connect WhatsApp with the rest of your stack

Use WhatsApp integration to connect the channel, map templates, verify sends, and review WhatsApp logs before campaigns or automated follow-ups go live.

Connect WhatsApp to your stack

Launch a WhatsApp workflow faster

Set up a compliant WhatsApp workflow with webhook ingestion, template mapping, CRM routing, task creation, logs and reports that fit PHP developers.

Free trial Automation rules Reporting

Talk to a specialist

Validate the workflow before you roll it out to the team.

Start Free Trial Talk to Sales

Why a CRM-backed workflow wins

If your team relies on WhatsApp daily, a CRM-backed PHP integration keeps ownership clear, makes webhook outcomes measurable, and creates a usable audit trail for every message.

Capability Plain PHP script PHP + spreadsheet log ZniCRM (API)
Inbound message handling Webhook code only Manual import or copy-paste Contact, owner and task context
Ownership and accountability Custom logic required Manual Assigned with reminders
Template and status logs Custom database tables Easy to miss retries WhatsApp logs and reports
Pipeline tracking Needs custom CRM work Hard to trust at scale Deals, tasks and revenue reports
A structured CRM workflow keeps WhatsApp activity visible, accountable, and tied to measurable outcomes. That is the difference between a code sample and an operational sales channel.

FAQ

Short, practical answers for buyers and implementers.

Ask a specific question

Yes. A PHP application can call the WhatsApp Cloud API directly over HTTPS when you have the phone number ID, WhatsApp Business Account ID, access token, webhook verify token, and app secret. A BSP can still be useful for onboarding, billing, support, and managed template operations.

Start with two files: one webhook endpoint that handles Meta's GET verification and POST events, and one send function that posts approved templates or session messages to the phone-number messages endpoint. Keep credentials in environment variables, not in source code.

Store the WhatsApp message ID, contact phone, message type, direction, status, timestamp, related contact or deal ID, payload summary, and error details. Use the message ID as an idempotency key so webhook retries do not create duplicate CRM activity.

Test webhook verification, signature validation, inbound messages, delivery statuses, failed sends, template sends outside the session window, free-form replies inside the customer service window, CRM contact matching, queue retries, and alerting for expired credentials.
Popular searches

Teams researching this topic typically look for compliance guidance, cost clarity, and automation patterns that match their scale.

Build a repeatable WhatsApp workflow

Use ZniCRM to connect WhatsApp with CRM data, automate routine steps, and keep every conversation accountable.

No credit card required for trial