A practical guide to creating a simple ecommerce chatbot with WhatsApp Cloud API, PHP, and MySQL
WhatsApp has become one of the most powerful communication channels for online businesses. Customers already use it every day to ask…
A practical guide to creating a simple ecommerce chatbot with WhatsApp Cloud API, PHP, and MySQL
WhatsApp has become one of the most powerful communication channels for online businesses. Customers already use it every day to ask questions, check prices, confirm orders, and talk to support teams. Because of that, adding a WhatsApp-based ecommerce chatbot can make the buying process faster, easier, and more personal.
In this article, we will build a simple WhatsApp ecommerce chatbot using PHP. The chatbot will allow customers to view products, choose an item, enter quantity, place an order, and track order status.
This is not a full enterprise ecommerce system, but it gives you a strong foundation that you can expand into a real business solution.

What We Are Going to Build
The chatbot will follow a simple shopping flow.
A customer sends a message like:
Hi
The bot replies:
Welcome to ABC Store 🛒
Reply with:
1. View Products
2. Track Order
3. Talk to Support
The customer chooses an option, selects a product, enters quantity, and receives an order confirmation.
Example:
Customer: Hi
Bot: Welcome to ABC Store. Reply with 1, 2, or 3.
Customer: 1
Bot: Here are our products:
101 - T-shirt - $20
102 - Shoes - $50
Customer: 101
Bot: You selected T-shirt. Please enter quantity.
Customer: 2
Bot: Order confirmed. Total: $40.
This type of automation is useful for small stores, D2C brands, local retailers, service businesses, and ecommerce startups.
How the System Works
The architecture is simple.
Customer on WhatsApp
↓
WhatsApp Cloud API
↓
PHP Webhook
↓
Bot Logic
↓
MySQL Database
↓
WhatsApp Reply
When a customer sends a WhatsApp message, Meta sends that message to your webhook URL. Your PHP script receives the message, checks the customer’s current step, processes the request, and sends a reply using the WhatsApp Cloud API.
Requirements
Before starting, you need:
- PHP 8 or higher
- MySQL or MariaDB
- HTTPS hosting
- Meta Developer account
- WhatsApp Business Cloud API access
- A WhatsApp phone number connected to your Meta app
- A webhook URL
For local testing, you can use tools like ngrok to expose your local PHP server over HTTPS. For production, use a real domain with SSL.
Database Design
We will use three tables:
products— stores product detailscustomers— stores customer state and selected productorders— stores order information
Create a database:
CREATE DATABASE whatsapp_shop;
USE whatsapp_shop;
Now create the products table:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
stock INT DEFAULT 0
);
Create the customers table:
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
phone VARCHAR(30) UNIQUE NOT NULL,
current_step VARCHAR(50) DEFAULT 'start',
selected_product_id INT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Create the orders table:
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_phone VARCHAR(30) NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
total DECIMAL(10,2) NOT NULL,
status VARCHAR(50) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Add a few sample products:
INSERT INTO products (name, price, stock) VALUES
('T-shirt', 20.00, 100),
('Shoes', 50.00, 50),
('Watch', 75.00, 30);
Project Structure
Create a project folder like this:
whatsapp-ecommerce-bot/
│
├── config.php
├── db.php
├── webhook.php
├── send-message.php
└── bot.php
Each file has a specific role:
config.phpstores API credentialsdb.phpconnects to MySQLwebhook.phpreceives WhatsApp messagessend-message.phpsends replies to WhatsAppbot.phpcontains the chatbot logic
Step 1: Configuration File
Create config.php:
<?php
define('VERIFY_TOKEN', 'my_secret_verify_token');
define('WHATSAPP_TOKEN', 'YOUR_ACCESS_TOKEN');
define('PHONE_NUMBER_ID', 'YOUR_PHONE_NUMBER_ID');
define('GRAPH_API_VERSION', 'v20.0');
define(
'WHATSAPP_API_URL',
'https://graph.facebook.com/' . GRAPH_API_VERSION . '/' . PHONE_NUMBER_ID . '/messages'
);
Replace these values:
YOUR_ACCESS_TOKEN
YOUR_PHONE_NUMBER_ID
The verify token can be any secure random string. You will use the same value when setting up the webhook in Meta Developer Dashboard.
In production, do not hardcode tokens directly in your files. Use environment variables instead.
Step 2: Connect PHP to MySQL
Create db.php:
<?php
$host = 'localhost';
$dbname = 'whatsapp_shop';
$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('Database connection failed: ' . $e->getMessage());
http_response_code(500);
exit('Database error');
}
This file creates a reusable PDO connection. We will include it wherever database access is needed.
Step 3: Create a Function to Send WhatsApp Messages
Create send-message.php:
<?php
require_once 'config.php';
function sendWhatsAppMessage(string $to, string $message): bool
{
$payload = [
'messaging_product' => 'whatsapp',
'to' => $to,
'type' => 'text',
'text' => [
'body' => $message
]
];
$ch = curl_init(WHATSAPP_API_URL);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . WHATSAPP_TOKEN,
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode($payload)
]);
$response = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($error || $httpCode >= 400) {
error_log('WhatsApp send error: ' . $error . ' Response: ' . $response);
return false;
}
return true;
}
This function sends a text message to a WhatsApp user using the Cloud API.
Step 4: Create the Webhook
The webhook has two jobs:
- Verify the webhook when Meta sends a verification request
- Receive incoming WhatsApp messages
Create webhook.php:
<?php
require_once 'config.php';
require_once 'bot.php';
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$mode = $_GET['hub_mode'] ?? $_GET['hub.mode'] ?? null;
$token = $_GET['hub_verify_token'] ?? $_GET['hub.verify_token'] ?? null;
$challenge = $_GET['hub_challenge'] ?? $_GET['hub.challenge'] ?? null;
if ($mode === 'subscribe' && $token === VERIFY_TOKEN) {
http_response_code(200);
echo $challenge;
exit;
}
http_response_code(403);
echo 'Forbidden';
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = file_get_contents('php://input');
$data = json_decode($input, true);
error_log('Webhook payload: ' . $input);
if (!empty($data['entry'][0]['changes'][0]['value']['messages'][0])) {
$messageData = $data['entry'][0]['changes'][0]['value']['messages'][0];
$from = $messageData['from'] ?? '';
$text = $messageData['text']['body'] ?? '';
if ($from && $text) {
handleIncomingMessage($from, trim($text));
}
}
http_response_code(200);
echo 'EVENT_RECEIVED';
exit;
}
http_response_code(405);
echo 'Method not allowed';
Once this file is uploaded to your server, your webhook URL will look like this:
https://yourdomain.com/whatsapp-ecommerce-bot/webhook.php
Step 5: Create the Chatbot Logic
Now create bot.php.
This file controls the conversation flow.
<?php
require_once 'db.php';
require_once 'send-message.php';
function handleIncomingMessage(string $phone, string $message): void
{
global $pdo;
$customer = getOrCreateCustomer($phone);
$step = $customer['current_step'];
$messageLower = strtolower($message);
if (in_array($messageLower, ['hi', 'hello', 'menu', 'start'])) {
updateCustomerStep($phone, 'main_menu');
sendMainMenu($phone);
return;
}
switch ($step) {
case 'main_menu':
case 'start':
handleMainMenu($phone, $message);
break;
case 'waiting_product_id':
handleProductSelection($phone, $message);
break;
case 'waiting_quantity':
handleQuantity($phone, $message);
break;
case 'waiting_order_id':
handleOrderTracking($phone, $message);
break;
default:
updateCustomerStep($phone, 'main_menu');
sendMainMenu($phone);
break;
}
}
The bot checks the customer’s current step and decides what to do next.
Step 6: Create or Load a Customer
Add this function to bot.php:
function getOrCreateCustomer(string $phone): array
{
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM customers WHERE phone = ?");
$stmt->execute([$phone]);
$customer = $stmt->fetch();
if ($customer) {
return $customer;
}
$stmt = $pdo->prepare("INSERT INTO customers (phone, current_step) VALUES (?, 'start')");
$stmt->execute([$phone]);
return [
'phone' => $phone,
'current_step' => 'start',
'selected_product_id' => null
];
}
This function checks if the customer already exists. If not, it creates a new customer record.
Step 7: Update Customer State
Add these helper functions:
function updateCustomerStep(string $phone, string $step): void
{
global $pdo;
$stmt = $pdo->prepare("UPDATE customers SET current_step = ? WHERE phone = ?");
$stmt->execute([$step, $phone]);
}
function updateSelectedProduct(string $phone, int $productId): void
{
global $pdo;
$stmt = $pdo->prepare("UPDATE customers SET selected_product_id = ? WHERE phone = ?");
$stmt->execute([$productId, $phone]);
}
A chatbot needs memory. These functions help the bot remember where the customer is in the buying process.
Step 8: Send the Main Menu
Add this function:
function sendMainMenu(string $phone): void
{
$message = "Welcome to ABC Store 🛒\n\n";
$message .= "Reply with:\n";
$message .= "1. View Products\n";
$message .= "2. Track Order\n";
$message .= "3. Talk to Support";
sendWhatsAppMessage($phone, $message);
}
This is the first menu most users will see.
Step 9: Handle Menu Options
Add this function:
function handleMainMenu(string $phone, string $message): void
{
if ($message === '1') {
sendProductList($phone);
updateCustomerStep($phone, 'waiting_product_id');
return;
}
if ($message === '2') {
sendWhatsAppMessage($phone, "Please enter your order ID.");
updateCustomerStep($phone, 'waiting_order_id');
return;
}
if ($message === '3') {
sendWhatsAppMessage($phone, "A support agent will contact you soon.");
updateCustomerStep($phone, 'main_menu');
return;
}
sendWhatsAppMessage($phone, "Invalid option. Please reply with 1, 2, or 3.");
sendMainMenu($phone);
}
This function handles the customer’s menu choice.
Step 10: Show Products
Add this function:
function sendProductList(string $phone): void
{
global $pdo;
$stmt = $pdo->query("SELECT id, name, price, stock FROM products WHERE stock > 0");
$products = $stmt->fetchAll();
if (!$products) {
sendWhatsAppMessage($phone, "Sorry, no products are available right now.");
return;
}
$message = "Available Products:\n\n";
foreach ($products as $product) {
$message .= $product['id'] . ". " . $product['name'];
$message .= " - $" . number_format($product['price'], 2);
$message .= "\n";
}
$message .= "\nReply with the product ID to order.";
sendWhatsAppMessage($phone, $message);
}
The bot fetches available products from the database and sends them as a simple text list.
For a production chatbot, you may want to use interactive buttons, product images, or catalog messages.
Step 11: Handle Product Selection
Add this function:
function handleProductSelection(string $phone, string $message): void
{
global $pdo;
if (!ctype_digit($message)) {
sendWhatsAppMessage($phone, "Please enter a valid product ID.");
return;
}
$productId = (int) $message;
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND stock > 0");
$stmt->execute([$productId]);
$product = $stmt->fetch();
if (!$product) {
sendWhatsAppMessage($phone, "Product not found or out of stock. Please enter another product ID.");
return;
}
updateSelectedProduct($phone, $productId);
updateCustomerStep($phone, 'waiting_quantity');
$reply = "You selected: {$product['name']}\n";
$reply .= "Price: $" . number_format($product['price'], 2) . "\n\n";
$reply .= "Please enter quantity.";
sendWhatsAppMessage($phone, $reply);
}
The bot validates the product ID, stores it in the customer record, and asks for quantity.
Step 12: Create an Order
Add this function:
function handleQuantity(string $phone, string $message): void
{
global $pdo;
if (!ctype_digit($message) || (int)$message <= 0) {
sendWhatsAppMessage($phone, "Please enter a valid quantity.");
return;
}
$quantity = (int) $message;
$stmt = $pdo->prepare("SELECT selected_product_id FROM customers WHERE phone = ?");
$stmt->execute([$phone]);
$customer = $stmt->fetch();
if (!$customer || !$customer['selected_product_id']) {
updateCustomerStep($phone, 'main_menu');
sendWhatsAppMessage($phone, "Something went wrong. Please start again.");
sendMainMenu($phone);
return;
}
$productId = (int) $customer['selected_product_id'];
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$productId]);
$product = $stmt->fetch();
if (!$product) {
sendWhatsAppMessage($phone, "Product not found.");
updateCustomerStep($phone, 'main_menu');
return;
}
if ($quantity > (int)$product['stock']) {
sendWhatsAppMessage($phone, "Sorry, only {$product['stock']} items are available.");
return;
}
$total = $quantity * (float)$product['price'];
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare("
INSERT INTO orders (customer_phone, product_id, quantity, total)
VALUES (?, ?, ?, ?)
");
$stmt->execute([$phone, $productId, $quantity, $total]);
$orderId = $pdo->lastInsertId();
$stmt = $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
$stmt->execute([$quantity, $productId]);
$stmt = $pdo->prepare("
UPDATE customers
SET current_step = 'main_menu', selected_product_id = NULL
WHERE phone = ?
");
$stmt->execute([$phone]);
$pdo->commit();
$reply = "Order confirmed ✅\n\n";
$reply .= "Order ID: {$orderId}\n";
$reply .= "Product: {$product['name']}\n";
$reply .= "Quantity: {$quantity}\n";
$reply .= "Total: $" . number_format($total, 2) . "\n\n";
$reply .= "Thank you for shopping with us.";
sendWhatsAppMessage($phone, $reply);
} catch (Exception $e) {
$pdo->rollBack();
error_log('Order error: ' . $e->getMessage());
sendWhatsAppMessage($phone, "Sorry, we could not create your order. Please try again.");
}
}
This function does several important things:
- Validates quantity
- Checks stock
- Calculates total
- Creates the order
- Reduces inventory
- Resets the customer step
- Sends confirmation
The database transaction ensures that the order and stock update happen safely together.
Step 13: Track an Order
Add this function:
function handleOrderTracking(string $phone, string $message): void
{
global $pdo;
if (!ctype_digit($message)) {
sendWhatsAppMessage($phone, "Please enter a valid order ID.");
return;
}
$orderId = (int) $message;
$stmt = $pdo->prepare("
SELECT orders.*, products.name AS product_name
FROM orders
JOIN products ON products.id = orders.product_id
WHERE orders.id = ? AND orders.customer_phone = ?
");
$stmt->execute([$orderId, $phone]);
$order = $stmt->fetch();
if (!$order) {
sendWhatsAppMessage($phone, "Order not found.");
return;
}
$reply = "Order Status 📦\n\n";
$reply .= "Order ID: {$order['id']}\n";
$reply .= "Product: {$order['product_name']}\n";
$reply .= "Quantity: {$order['quantity']}\n";
$reply .= "Total: $" . number_format($order['total'], 2) . "\n";
$reply .= "Status: {$order['status']}";
sendWhatsAppMessage($phone, $reply);
updateCustomerStep($phone, 'main_menu');
}
This allows customers to check their order status by entering their order ID.
Setting Up the Webhook in Meta
After uploading your files to the server, go to your Meta Developer Dashboard.
Set your callback URL:
https://yourdomain.com/whatsapp-ecommerce-bot/webhook.php
Set your verify token:
my_secret_verify_token
Then subscribe to WhatsApp message events.
Once verified, send a WhatsApp message to your business number. If everything is configured correctly, the chatbot should respond.
Testing the Bot
Try the following messages:
Hi
Then:
1
Then choose a product ID:
1
Then enter quantity:
2
You should receive an order confirmation message.
To track the order, go back to the menu and choose:
2
Then enter the order ID.
Important Production Notes
The code above is simple and useful for learning, but a production chatbot needs more work.
You should add:
- Webhook signature verification
- Environment variables for API tokens
- Better error handling
- Logging system
- Message history table
- Admin dashboard
- Payment integration
- Address collection
- Product images
- Customer opt-in tracking
- Template messages
- Live agent handoff
You also need to respect WhatsApp’s messaging rules. In many cases, businesses can reply freely only inside the customer service window. Outside that window, approved message templates are usually required.
Useful Features to Add Next
Once the basic chatbot works, you can improve it with:
Product Categories
Instead of showing all products at once, let customers choose a category first.
1. Men
2. Women
3. Accessories
Cart System
Allow customers to add multiple products before checkout.
Payment Links
Generate payment links from Stripe, PayPal, Razorpay, or another payment provider.
Delivery Address Collection
Ask the customer for name, address, city, and postal code before creating the final order.
Admin Panel
Create a dashboard to manage products, stock, orders, and customers.
Live Support Handoff
If the customer types “support,” forward the conversation to a human agent.
Final Thoughts
Building a WhatsApp ecommerce chatbot with PHP is a practical way to automate customer conversations and simplify online selling. With the WhatsApp Cloud API, a PHP webhook, and a MySQL database, you can create a bot that handles product browsing, order placement, and order tracking.
The version in this article is intentionally simple. It gives you the core structure: receive a message, understand the customer’s step, process the action, store data, and reply.
From here, you can add payments, product images, delivery workflows, CRM integration, and live support.
A good ecommerce chatbot does not just answer questions. It helps customers buy faster, reduces manual support work, and creates a smoother shopping experience inside an app they already use every day.
메타데이터
- post_id
- 17fe5155db4e
- slug
- a-practical-guide-to-creating-a-simple-ecommerce-chatbot-with-whatsapp-cloud-api-php-and-mysql-17fe5155db4e
- url
- https://medium.com/@new2026/a-practical-guide-to-creating-a-simple-ecommerce-chatbot-with-whatsapp-cloud-api-php-and-mysql-17fe5155db4e
- canonical_url
- https://medium.com/@new2026/a-practical-guide-to-creating-a-simple-ecommerce-chatbot-with-whatsapp-cloud-api-php-and-mysql-17fe5155db4e
- author_url
- https://medium.com/@new2026
- status
- ok
- fetched_at
- 2026-06-15 20:49:13