PHP Examples
Complete examples for integrating the WhatsApp API with PHP.
Installation
No special libraries required. Uses native PHP cURL.
<?php
// config.php
define('API_BASE_URL', 'http://localhost:3000');
define('API_KEY', 'wask_your_api_key_here');
define('SESSION_ID', 'your-session-id');
Helper Class
<?php
// WhatsAppAPI.php
class WhatsAppAPI {
private $baseUrl;
private $apiKey;
private $sessionId;
public function __construct($baseUrl, $apiKey, $sessionId) {
$this->baseUrl = rtrim($baseUrl, '/');
$this->apiKey = $apiKey;
$this->sessionId = $sessionId;
}
private function request($method, $endpoint, $data = null) {
$url = $this->baseUrl . $endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $this->apiKey,
'Content-Type: application/json'
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);
if ($httpCode >= 400) {
throw new Exception($result['error'] ?? 'API request failed');
}
return $result;
}
// Session Management
public function getStatus() {
return $this->request('GET', "/sessions/{$this->sessionId}/status");
}
public function getQR() {
return $this->request('GET', "/sessions/{$this->sessionId}/qr");
}
// Messaging
public function sendText($to, $text, $quotedMessageId = null) {
$data = [
'to' => $to,
'text' => $text
];
if ($quotedMessageId) {
$data['quotedMessageId'] = $quotedMessageId;
}
return $this->request('POST', "/sessions/{$this->sessionId}/send", $data);
}
public function sendImage($to, $image, $caption = null, $filename = null) {
$data = [
'to' => $to,
'image' => $image
];
if ($caption) $data['caption'] = $caption;
if ($filename) $data['filename'] = $filename;
return $this->request('POST', "/sessions/{$this->sessionId}/send/image", $data);
}
public function sendDocument($to, $document, $filename, $caption = null) {
$data = [
'to' => $to,
'document' => $document,
'filename' => $filename
];
if ($caption) $data['caption'] = $caption;
return $this->request('POST', "/sessions/{$this->sessionId}/send/document", $data);
}
public function sendVideo($to, $video, $caption = null) {
$data = [
'to' => $to,
'video' => $video
];
if ($caption) $data['caption'] = $caption;
return $this->request('POST', "/sessions/{$this->sessionId}/send/video", $data);
}
public function sendLocation($to, $latitude, $longitude, $description = null) {
$data = [
'to' => $to,
'latitude' => $latitude,
'longitude' => $longitude
];
if ($description) $data['description'] = $description;
return $this->request('POST', "/sessions/{$this->sessionId}/send/location", $data);
}
// Utilities
public function checkNumber($phone) {
return $this->request('GET', "/sessions/{$this->sessionId}/check-number/{$phone}");
}
public function getContacts() {
return $this->request('GET', "/sessions/{$this->sessionId}/contacts");
}
public function getChats() {
return $this->request('GET', "/sessions/{$this->sessionId}/chats");
}
// Groups
public function createGroup($name, $participants) {
return $this->request('POST', "/sessions/{$this->sessionId}/groups/create", [
'name' => $name,
'participants' => $participants
]);
}
public function getGroupInfo($groupId) {
return $this->request('GET', "/sessions/{$this->sessionId}/groups/{$groupId}");
}
public function addParticipants($groupId, $participants) {
return $this->request('POST', "/sessions/{$this->sessionId}/groups/{$groupId}/participants/add", [
'participants' => $participants
]);
}
}
Basic Usage
Send Text Message
<?php
require_once 'config.php';
require_once 'WhatsAppAPI.php';
$whatsapp = new WhatsAppAPI(API_BASE_URL, API_KEY, SESSION_ID);
try {
$result = $whatsapp->sendText('919876543210', 'Hello from PHP! 🚀');
echo "Message sent successfully!\n";
echo "Message ID: " . $result['messageId'] . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Send Image
<?php
$whatsapp = new WhatsAppAPI(API_BASE_URL, API_KEY, SESSION_ID);
try {
$result = $whatsapp->sendImage(
'919876543210',
'https://example.com/image.jpg',
'Check out this image!',
'photo.jpg'
);
echo "Image sent successfully!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Send Document
<?php
$whatsapp = new WhatsAppAPI(API_BASE_URL, API_KEY, SESSION_ID);
try {
$result = $whatsapp->sendDocument(
'919876543210',
'https://example.com/report.pdf',
'Monthly Report.pdf',
'Here is your monthly report'
);
echo "Document sent successfully!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Advanced Examples
Bulk Message Sender
<?php
require_once 'WhatsAppAPI.php';
class BulkMessageSender {
private $whatsapp;
private $delaySeconds;
public function __construct($whatsapp, $delaySeconds = 2) {
$this->whatsapp = $whatsapp;
$this->delaySeconds = $delaySeconds;
}
public function sendToMultiple($recipients, $message) {
$results = [];
foreach ($recipients as $recipient) {
try {
$result = $this->whatsapp->sendText($recipient, $message);
$results[$recipient] = [
'success' => true,
'messageId' => $result['messageId']
];
echo "✓ Sent to {$recipient}\n";
} catch (Exception $e) {
$results[$recipient] = [
'success' => false,
'error' => $e->getMessage()
];
echo "✗ Failed to send to {$recipient}: {$e->getMessage()}\n";
}
// Delay between messages
if ($recipient !== end($recipients)) {
sleep($this->delaySeconds);
}
}
return $results;
}
}
// Usage
$whatsapp = new WhatsAppAPI(API_BASE_URL, API_KEY, SESSION_ID);
$bulkSender = new BulkMessageSender($whatsapp, 2);
$recipients = [
'919876543210',
'919876543211',
'919876543212'
];
$message = "Hello! This is a bulk message.";
$results = $bulkSender->sendToMultiple($recipients, $message);
// Summary
$successful = count(array_filter($results, fn($r) => $r['success']));
$failed = count($results) - $successful;
echo "\nSummary:\n";
echo "Successful: {$successful}\n";
echo "Failed: {$failed}\n";
Auto-Reply Bot
<?php
// webhook.php
require_once 'WhatsAppAPI.php';
// Get webhook payload
$payload = json_decode(file_get_contents('php://input'), true);
if (!$payload) {
http_response_code(400);
exit('Invalid JSON');
}
$event = $payload['event'] ?? null;
if ($event === 'message') {
$message = $payload['message'];
// Ignore messages from self
if ($message['fromMe']) {
http_response_code(200);
exit(json_encode(['success' => true]));
}
$from = $message['from'];
$body = strtolower(trim($message['body']));
// Auto-reply logic
$reply = null;
if (strpos($body, 'hello') !== false || strpos($body, 'hi') !== false) {
$reply = "Hello! How can I help you today?";
} elseif (strpos($body, 'help') !== false) {
$reply = "Available commands:\n- hello - Greeting\n- help - Show this message\n- status - Check status";
} elseif (strpos($body, 'status') !== false) {
$reply = "System is operational! ✅";
}
// Send reply
if ($reply) {
$whatsapp = new WhatsAppAPI(API_BASE_URL, API_KEY, SESSION_ID);
try {
$whatsapp->sendText($from, $reply);
error_log("Auto-reply sent to {$from}");
} catch (Exception $e) {
error_log("Failed to send auto-reply: {$e->getMessage()}");
}
}
}
// Always respond with 200 OK
http_response_code(200);
echo json_encode(['success' => true]);
Message Queue System
<?php
// MessageQueue.php
class MessageQueue {
private $whatsapp;
private $queueFile;
public function __construct($whatsapp, $queueFile = 'message_queue.json') {
$this->whatsapp = $whatsapp;
$this->queueFile = $queueFile;
}
public function add($to, $message, $type = 'text', $media = null) {
$queue = $this->loadQueue();
$queue[] = [
'id' => uniqid(),
'to' => $to,
'message' => $message,
'type' => $type,
'media' => $media,
'status' => 'pending',
'createdAt' => date('c'),
'attempts' => 0
];
$this->saveQueue($queue);
}
public function process($maxAttempts = 3) {
$queue = $this->loadQueue();
$processed = 0;
foreach ($queue as &$item) {
if ($item['status'] !== 'pending') {
continue;
}
try {
if ($item['type'] === 'text') {
$result = $this->whatsapp->sendText($item['to'], $item['message']);
} elseif ($item['type'] === 'image') {
$result = $this->whatsapp->sendImage($item['to'], $item['media'], $item['message']);
}
$item['status'] = 'sent';
$item['messageId'] = $result['messageId'];
$item['sentAt'] = date('c');
echo "✓ Sent message {$item['id']} to {$item['to']}\n";
$processed++;
} catch (Exception $e) {
$item['attempts']++;
if ($item['attempts'] >= $maxAttempts) {
$item['status'] = 'failed';
$item['error'] = $e->getMessage();
echo "✗ Failed message {$item['id']}: {$e->getMessage()}\n";
} else {
echo "⚠ Retry {$item['attempts']}/{$maxAttempts} for message {$item['id']}\n";
}
}
// Delay between messages
sleep(2);
}
$this->saveQueue($queue);
return $processed;
}
private function loadQueue() {
if (!file_exists($this->queueFile)) {
return [];
}
$content = file_get_contents($this->queueFile);
return json_decode($content, true) ?: [];
}
private function saveQueue($queue) {
file_put_contents($this->queueFile, json_encode($queue, JSON_PRETTY_PRINT));
}
public function getStats() {
$queue = $this->loadQueue();
$stats = [
'total' => count($queue),
'pending' => 0,
'sent' => 0,
'failed' => 0
];
foreach ($queue as $item) {
$stats[$item['status']]++;
}
return $stats;
}
}
// Usage
$whatsapp = new WhatsAppAPI(API_BASE_URL, API_KEY, SESSION_ID);
$queue = new MessageQueue($whatsapp);
// Add messages to queue
$queue->add('919876543210', 'Message 1');
$queue->add('919876543211', 'Message 2');
$queue->add('919876543212', 'Message 3');
// Process queue
$processed = $queue->process();
echo "\nProcessed {$processed} messages\n";
// Get stats
$stats = $queue->getStats();
print_r($stats);
Check Number Before Sending
<?php
function sendSafe($whatsapp, $phone, $message) {
try {
// Check if number exists
$check = $whatsapp->checkNumber($phone);
if (!$check['exists']) {
echo "Number {$phone} is not on WhatsApp\n";
return false;
}
// Send message
$result = $whatsapp->sendText($phone, $message);
echo "Message sent to {$phone}\n";
return true;
} catch (Exception $e) {
echo "Error: {$e->getMessage()}\n";
return false;
}
}
// Usage
$whatsapp = new WhatsAppAPI(API_BASE_URL, API_KEY, SESSION_ID);
sendSafe($whatsapp, '919876543210', 'Hello!');
Database Integration
Store Messages in MySQL
<?php
// Database.php
class MessageDatabase {
private $pdo;
public function __construct($host, $dbname, $username, $password) {
$dsn = "mysql:host={$host};dbname={$dbname};charset=utf8mb4";
$this->pdo = new PDO($dsn, $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function saveOutgoingMessage($to, $message, $messageId, $type = 'text') {
$stmt = $this->pdo->prepare("
INSERT INTO messages (message_id, direction, recipient, body, type, status, created_at)
VALUES (:message_id, 'outgoing', :recipient, :body, :type, 'sent', NOW())
");
$stmt->execute([
'message_id' => $messageId,
'recipient' => $to,
'body' => $message,
'type' => $type
]);
}
public function saveIncomingMessage($messageId, $from, $body, $type) {
$stmt = $this->pdo->prepare("
INSERT INTO messages (message_id, direction, sender, body, type, created_at)
VALUES (:message_id, 'incoming', :sender, :body, :type, NOW())
ON DUPLICATE KEY UPDATE message_id = message_id
");
$stmt->execute([
'message_id' => $messageId,
'sender' => $from,
'body' => $body,
'type' => $type
]);
}
public function updateMessageStatus($messageId, $status) {
$stmt = $this->pdo->prepare("
UPDATE messages SET status = :status, updated_at = NOW()
WHERE message_id = :message_id
");
$stmt->execute([
'message_id' => $messageId,
'status' => $status
]);
}
}
// webhook.php with database
$db = new MessageDatabase('localhost', 'whatsapp', 'user', 'password');
$payload = json_decode(file_get_contents('php://input'), true);
if ($payload['event'] === 'message') {
$message = $payload['message'];
$db->saveIncomingMessage(
$message['id'],
$message['from'],
$message['body'],
$message['type']
);
}
if ($payload['event'] === 'message_status') {
$status = $payload['statusUpdate'];
$db->updateMessageStatus($status['messageId'], $status['status']);
}
Error Handling
<?php
class WhatsAppException extends Exception {}
function sendWithRetry($whatsapp, $to, $message, $maxRetries = 3) {
$attempt = 0;
while ($attempt < $maxRetries) {
try {
return $whatsapp->sendText($to, $message);
} catch (Exception $e) {
$attempt++;
if ($attempt >= $maxRetries) {
throw new WhatsAppException(
"Failed after {$maxRetries} attempts: {$e->getMessage()}"
);
}
// Exponential backoff
sleep(pow(2, $attempt));
}
}
}