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_TOKEN
in.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.yaml
to 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
Procfile
to 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.json
to 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.php
Validates that all configuration files load correctly and dependencies are installed.
php tests/api-test.php
Tests connectivity to Wassenger and OpenAI APIs with your configured keys.
php tests/webhook-test.php
Simulates 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=debug
Then 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
.env
file 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.