A versatile PHP implementation of a WhatsApp AI Chatbot that's easy to customize 🎨, business-specific 🏢, general-purpose OpenAI GPT4o-powered 🤖 and Multimodal 🎭 that works with Wassenger WhatsApp API 📱.
Now supports GPT-4o with text + audio + image input 📝🎵🖼️, audio responses 🔊, and improved RAG with MCP tools 🛠️ and external functions for external API calls support 🌐
This PHP implementation is based on the Node.js WhatsApp ChatGPT Bot, providing full feature parity while following modern PHP best practices. If you prefer to use Node.js, check out the other implementation.
🚀 Get started for free with Wassenger WhatsApp API in minutes by connecting your existing WhatsApp number and obtain your API key ✨
This PHP implementation provides a complete ChatGPT-powered AI chatbot that:
- 🤖 Fully featured chatbot for your WhatsApp number connected to Wassenger
- 💬 Automatic replies to incoming messages from users
- 🌍 Multi-language support - understands and replies in 90+ different languages
- 🎤 Audio input/output - transcription and text-to-speech capabilities
- 🖼️ Image processing - can analyze and understand images
- 👥 Human handoff - allows users to request human assistance
- ⚙️ Customizable AI behavior and instructions
- 🔧 Function calling capabilities for external data integration
- 📊 Memory management with conversation history and rate limiting
- 🚦 Smart routing with webhook handling and error management
- 🔒 Secure with proper error handling and logging
- Features
- Quick Start
- Requirements
- Configuration
- Usage
- Architecture
- Testing
- Development
- Customization
- API Endpoints
- Troubleshooting
- API Documentation
- Production Deployment
- Resources
- Contributing
- License
- Clone the repository:
git clone https://github.com/wassengerhq/whatsapp-chatgpt-bot-php.git
cd whatsapp-chatgpt-bot-php- Install PHP dependencies:
composer install- Configure environment:
cp .env.example .env
# Edit .env file with your API keys (see Configuration section)- Test the configuration:
php tests/config-test.php- Run the bot:
# Development mode (with Ngrok tunnel)
composer run dev
# Or directly with PHP
php public/index.php
# Production mode (optionally set WEBHOOK_URL in .env first)
WEBHOOK_URL=https://my.server.com/webhook php public/index.php- PHP 8.1 or higher
- Composer package manager
- WhatsApp Personal or Business number
- Wassenger API key - Sign up for free
- OpenAI API key - Sign up for free
- Ngrok account (for local development) - Sign up for free
Edit the .env file with your API credentials:
# Required: Wassenger API key
# Get it from: https://app.wassenger.com/developers/apikeys
API_KEY=your_wassenger_api_key_here
# Required: OpenAI API key
# Get it from: https://platform.openai.com/account/api-keys
OPENAI_API_KEY=your_openai_api_key_here
# OpenAI model to use (gpt-4o, gpt-4, gpt-3.5-turbo)
OPENAI_MODEL=gpt-4o
# Required for local development: Ngrok auth token
# Get it from: https://ngrok.com/signup
NGROK_TOKEN=your_ngrok_token_here
# Optional: Specific WhatsApp device ID
DEVICE=
# Optional: Webhook URL for production deployment
WEBHOOK_URL=https://yourdomain.com/webhook
# Server configuration
PORT=8080
LOG_LEVEL=info# Required: Wassenger API key - See instructions below
# Get it here: https://app.wassenger.com/developers/apikeys
API_KEY=your_wassenger_api_key_here
# Required: OpenAI API key - See instructions below
OPENAI_API_KEY=your_openai_api_key_here
# Required for local development: Ngrok auth token - See instructions below
NGROK_TOKEN=your_ngrok_token_here
# Optional: Specific WhatsApp device ID - only if you have multiple numbers in your Wassenger account
DEVICE=1234
# Optional: Webhook URL for production if you run the bot program on a cloud hosted server with a public URL
WEBHOOK_URL=-
Wassenger API Key:
-
OpenAI API Key:
-
Ngrok Token (for local development):
- Sign up at Ngrok
- Get your auth token from the dashboard
- Copy it to
NGROK_TOKENin.env
Edit src/Config/BotConfig.php to customize:
- Bot instructions and personality
- Welcome and help messages
- Supported features (audio, images, etc.)
- Rate limits and quotas
- Whitelisted/blacklisted numbers
- Labels and metadata settings
- Start the development server:
composer run dev-
The bot will:
- Start a local HTTP server on port 8080
- Create an Ngrok tunnel automatically
- Register the webhook with Wassenger
- Begin processing WhatsApp messages
-
Send a message to your WhatsApp number connected to Wassenger to test the bot.
- Set environment variables on your server:
export WEBHOOK_URL=https://yourdomain.com/webhook
export API_KEY=your_wassenger_api_key
export OPENAI_API_KEY=your_openai_api_key-
Deploy to your web server (Apache/Nginx) with document root pointing to
public/ -
Make sure your server can receive POST requests at
/webhook
For production deployment, you can use various cloud platforms. Here are detailed instructions for popular hosting services:
- Create a new Web Service on Render:
- Connect your GitHub repository
- Set build command:
composer install --no-dev --optimize-autoloader - Set start command:
php -S 0.0.0.0:$PORT public/index.php
- Configure environment variables in Render dashboard:
API_KEY=your_wassenger_api_key
OPENAI_API_KEY=your_openai_api_key
WEBHOOK_URL=https://your-app-name.onrender.com/webhook
- Add
render.yamlto your project root:
services:
- type: web
name: whatsapp-chatgpt-bot
env: php
buildCommand: composer install --no-dev --optimize-autoloader
startCommand: php -S 0.0.0.0:$PORT public/index.php
envVars:
- key: ENV
value: production- Install Heroku CLI and login:
heroku login- Create Heroku app:
heroku create your-whatsapp-bot- Add
Procfileto your project root:
web: php -S 0.0.0.0:$PORT public/index.php
- Configure environment variables:
heroku config:set API_KEY=your_wassenger_api_key
heroku config:set OPENAI_API_KEY=your_openai_api_key
heroku config:set WEBHOOK_URL=https://your-whatsapp-bot.herokuapp.com/webhook- Deploy:
git add .
git commit -m "Deploy to Heroku"
git push heroku main- Connect repository at Railway:
- Import your GitHub repository
- Railway auto-detects PHP projects
- Set environment variables in Railway dashboard:
API_KEY=your_wassenger_api_key
OPENAI_API_KEY=your_openai_api_key
WEBHOOK_URL=https://your-app.railway.app/webhook
- Add
nixpacks.toml(optional, for custom configuration):
[phases.build]
cmds = ["composer install --no-dev --optimize-autoloader"]
[phases.start]
cmd = "php -S 0.0.0.0:$PORT public/index.php"- Create new app on DigitalOcean App Platform:
- Connect your GitHub repository
- Choose PHP as runtime
- Configure app spec:
name: whatsapp-chatgpt-bot
services:
- name: web
source_dir: /
github:
repo: your-username/your-repo
branch: main
run_command: php -S 0.0.0.0:$PORT public/index.php
environment_slug: php
instance_count: 1
instance_size_slug: basic-xxs
envs:
- key: API_KEY
value: your_wassenger_api_key
type: SECRET
- key: OPENAI_API_KEY
value: your_openai_api_key
type: SECRET- Set webhook URL after deployment:
WEBHOOK_URL=https://your-app-name.ondigitalocean.app/webhook
- Install Vercel CLI:
npm i -g vercel- Add
vercel.jsonto project root:
{
"functions": {
"public/index.php": {
"runtime": "vercel-php@0.6.0"
}
},
"routes": [
{ "src": "/(.*)", "dest": "/public/index.php" }
],
"env": {
"ENV": "production"
}
}- Deploy:
vercel --prod- Set environment variables:
vercel env add API_KEY
vercel env add OPENAI_API_KEY
vercel env add WEBHOOK_URL- For Netlify, add
netlify.toml:
[build]
command = "composer install --no-dev"
publish = "public"
[[redirects]]
from = "/*"
to = "/index.php"
status = 200- Set environment variables in Netlify dashboard and configure webhook URL accordingly.
After deploying to any platform:
- Test the webhook URL:
curl -X POST https://your-deployed-app.com/webhook \
-H "Content-Type: application/json" \
-d '{"test": true}'-
Monitor logs for any errors during initial deployment
-
Update Wassenger webhook to point to your production URL
-
Test with a real WhatsApp message to ensure end-to-end functionality
-
Set up monitoring and alerts for your production environment
The PHP implementation follows a modern, object-oriented architecture:
src/
├── Api/ # API clients
│ ├── OpenAIClient.php # OpenAI API integration
│ └── WassengerClient.php # Wassenger API integration
├── Bot/ # Core bot logic
│ ├── ChatBot.php # Main bot processing
│ └── FunctionHandler.php # Function calling system
├── Config/ # Configuration management
│ └── BotConfig.php # Centralized configuration
├── Http/ # HTTP layer
│ ├── Router.php # Request routing
│ └── WebhookHandler.php # Webhook processing
├── Storage/ # Data storage
│ └── MemoryStore.php # In-memory caching
└── Utils/ # Utilities
├── AppLogger.php # Logging system
└── NgrokTunnel.php # Development tunneling
The project includes several test utilities to validate your setup:
php tests/config-test.phpValidates that all configuration files load correctly and dependencies are installed.
php tests/api-test.phpTests connectivity to Wassenger and OpenAI APIs with your configured keys.
php tests/webhook-test.phpSimulates a webhook request to test the message processing pipeline.
You can also test individual components:
# Test basic setup
php -r "require 'vendor/autoload.php'; echo 'PHP setup OK';"
# Check API keys
php -r "require 'vendor/autoload.php'; use Dotenv\Dotenv; Dotenv::createImmutable(__DIR__)->load(); echo 'API Key: ' . (\$_ENV['API_KEY'] ?? 'not set');"chatgpt-php/
├── public/
│ └── index.php # Main entry point
├── src/
│ ├── Api/ # API integrations
│ ├── Bot/ # Core bot logic
│ ├── Config/ # Configuration
│ ├── Http/ # HTTP handling
│ ├── Storage/ # Data storage
│ └── Utils/ # Utility classes
├── tests/ # Test utilities
├── vendor/ # Composer dependencies
├── .env.example # Environment template
├── composer.json # PHP dependencies
└── README.md
ChatBot- Main bot processing logicOpenAIClient- OpenAI API integration with chat, audio, and image supportWassengerClient- Wassenger API integration for WhatsApp messagingRouter- HTTP request routing and webhook handlingBotConfig- Centralized configuration managementMemoryStore- In-memory caching and conversation state management
Edit the AI behavior in src/Config/BotConfig.php:
public const BOT_INSTRUCTIONS = 'You are a helpful assistant...';Add custom functions in src/Bot/FunctionHandler.php:
public function getBusinessHours(): array {
return [
'monday' => '9:00 AM - 6:00 PM',
'tuesday' => '9:00 AM - 6:00 PM',
// ... more days
];
}Adjust limits in src/Config/BotConfig.php:
public const LIMITS = [
'maxInputCharacters' => 1000,
'maxOutputTokens' => 1000,
'chatHistoryLimit' => 20,
// ... more limits
];whatsapp-chatgpt-chatbot-php/
├── composer.json # Dependencies and autoloading
├── .env.example # Environment configuration template
├── README.md # This file
├── public/
│ └── index.php # Web server entry point
└── src/
├── Api/
│ ├── OpenAIClient.php # OpenAI API client
│ └── WassengerClient.php # Wassenger API client
├── Bot/
│ ├── ChatBot.php # Main bot logic
│ ├── MessageProcessor.php # Message processing
│ └── FunctionHandler.php # AI function calling
├── Config/
│ └── BotConfig.php # Bot configuration
├── Http/
│ ├── Router.php # HTTP routing
│ └── WebhookHandler.php # Webhook processing
├── Storage/
│ └── MemoryStore.php # In-memory storage
└── Utils/
├── Logger.php # Logging utility
└── NgrokTunnel.php # Ngrok integration
Edit the bot's personality and instructions in src/Config/BotConfig.php:
public const BOT_INSTRUCTIONS = 'You are a helpful customer support assistant...';Add custom functions in src/Bot/FunctionHandler.php to integrate with external APIs, databases, or services:
private function getPlanPrices(): string
{
// Your custom logic here
return 'Plan pricing information...';
}Configure message limits and quotas in src/Config/BotConfig.php:
public const LIMITS = [
'maxInputCharacters' => 1000,
'maxOutputTokens' => 1000,
'maxMessagesPerChat' => 500,
// ...
];GET /- Bot information and statusPOST /webhook- Webhook for incoming WhatsApp messagesPOST /message- Send message endpointGET /sample- Send sample messageGET /files/{id}- Temporary file downloads
-
"No active WhatsApp numbers"
- Verify your Wassenger API key
- Check that you have a connected WhatsApp device in Wassenger
-
"WhatsApp number is not online"
- Ensure your WhatsApp device is connected and online in Wassenger dashboard
-
Webhook not receiving messages
- Check that your webhook URL is accessible from the internet
- Verify Ngrok tunnel is running (development mode)
- Check firewall settings
-
OpenAI API errors
- Verify your OpenAI API key is valid
- Check your OpenAI account has sufficient credits
- Ensure the model name is correct
Enable detailed logging by setting in .env:
LOG_LEVEL=debugThen check the logs in your configured log directory.
This bot integrates with:
- Wassenger API - WhatsApp messaging
- OpenAI API - AI chat completions, audio transcription, text-to-speech
- Ngrok - Development tunneling
- Document Root: Point to the
public/directory - URL Rewriting: Configure rewrite rules to route all requests to
index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}# Set your production webhook URL
WEBHOOK_URL=https://yourdomain.com/webhook
# Use production logging
LOG_LEVEL=error- Keep
.envfile outside the web root or protect it via web server configuration - Use HTTPS for all webhook endpoints
- Implement rate limiting at the web server level
- Monitor logs for suspicious activity
- Keep dependencies updated:
composer update
- Enable OPcache in production
- Use a proper web server (Apache/Nginx) instead of PHP's built-in server
- Consider using Redis or Memcached for session storage
- Implement proper caching strategies
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
MIT License - see LICENSE file for details.
Built with ❤️ using PHP and the Wassenger API.