Skip to content

A featured, easy-to-use, multimodal WhatsApp AI GPT-4o Chatbot in PHP for your Business. Supports GPT-4o with text + audio + image input, audio responses, and improved RAG + MCP Tools 🀩

License

Notifications You must be signed in to change notification settings

wassengerhq/whatsapp-chatgpt-bot-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WhatsApp ChatGPT Multimodal AI Chatbot in PHP πŸ€–

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 ✨

Features

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

Contents

Quick Start

  1. Clone the repository:
git clone https://github.com/wassengerhq/whatsapp-chatgpt-bot-php.git
cd whatsapp-chatgpt-bot-php
  1. Install PHP dependencies:
composer install
  1. Configure environment:
cp .env.example .env
# Edit .env file with your API keys (see Configuration section)
  1. Test the configuration:
php tests/config-test.php
  1. 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

Requirements

Configuration

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=

Configuration

API Keys Setup

  1. Wassenger API Key:

    • Sign up at Wassenger
    • Go to API Keys
    • Create a new API key and copy it to API_KEY in .env
  2. OpenAI API Key:

    • Sign up at OpenAI
    • Go to API Keys
    • Create a new API key and copy it to OPENAI_API_KEY in .env
  3. Ngrok Token (for local development):

    • Sign up at Ngrok
    • Get your auth token from the dashboard
    • Copy it to NGROK_TOKEN in .env

Bot Customization

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

Usage

Local Development

  1. Start the development server:
composer run dev
  1. 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
  2. Send a message to your WhatsApp number connected to Wassenger to test the bot.

Production Deployment

  1. 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
  1. Deploy to your web server (Apache/Nginx) with document root pointing to public/

  2. Make sure your server can receive POST requests at /webhook

Deployment

For production deployment, you can use various cloud platforms. Here are detailed instructions for popular hosting services:

Deploy on Render

  1. 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
  1. 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
  1. 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

Deploy on Heroku

  1. Install Heroku CLI and login:
heroku login
  1. Create Heroku app:
heroku create your-whatsapp-bot
  1. Add Procfile to your project root:
web: php -S 0.0.0.0:$PORT public/index.php
  1. 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
  1. Deploy:
git add .
git commit -m "Deploy to Heroku"
git push heroku main

Deploy on Railway

  1. Connect repository at Railway:
  • Import your GitHub repository
  • Railway auto-detects PHP projects
  1. 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
  1. 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"

Deploy on DigitalOcean App Platform

  1. Create new app on DigitalOcean App Platform:
  • Connect your GitHub repository
  • Choose PHP as runtime
  1. 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
  1. Set webhook URL after deployment:
WEBHOOK_URL=https://your-app-name.ondigitalocean.app/webhook

Deploy on Vercel

  1. Install Vercel CLI:
npm i -g vercel
  1. 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"
  }
}
  1. Deploy:
vercel --prod
  1. Set environment variables:
vercel env add API_KEY
vercel env add OPENAI_API_KEY
vercel env add WEBHOOK_URL

Deploy on PlanetScale + Netlify

  1. For Netlify, add netlify.toml:
[build]
  command = "composer install --no-dev"
  publish = "public"

[[redirects]]
  from = "/*"
  to = "/index.php"
  status = 200
  1. Set environment variables in Netlify dashboard and configure webhook URL accordingly.

General Production Checklist

After deploying to any platform:

  1. Test the webhook URL:
curl -X POST https://your-deployed-app.com/webhook \
  -H "Content-Type: application/json" \
  -d '{"test": true}'
  1. Monitor logs for any errors during initial deployment

  2. Update Wassenger webhook to point to your production URL

  3. Test with a real WhatsApp message to ensure end-to-end functionality

  4. Set up monitoring and alerts for your production environment

Architecture

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

Testing

The project includes several test utilities to validate your setup:

Configuration Test

php tests/config-test.php

Validates that all configuration files load correctly and dependencies are installed.

API Connection Test

php tests/api-test.php

Tests connectivity to Wassenger and OpenAI APIs with your configured keys.

Webhook Test

php tests/webhook-test.php

Simulates a webhook request to test the message processing pipeline.

Manual Testing

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');"

Development

Project Structure

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

Key Classes

  • ChatBot - Main bot processing logic
  • OpenAIClient - OpenAI API integration with chat, audio, and image support
  • WassengerClient - Wassenger API integration for WhatsApp messaging
  • Router - HTTP request routing and webhook handling
  • BotConfig - Centralized configuration management
  • MemoryStore - In-memory caching and conversation state management

Customization

Bot Instructions

Edit the AI behavior in src/Config/BotConfig.php:

public const BOT_INSTRUCTIONS = 'You are a helpful assistant...';

Function Calling

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
    ];
}

Rate Limits

Adjust limits in src/Config/BotConfig.php:

public const LIMITS = [
    'maxInputCharacters' => 1000,
    'maxOutputTokens' => 1000,
    'chatHistoryLimit' => 20,
    // ... more limits
];

Project Structure

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

Customization

Bot Instructions

Edit the bot's personality and instructions in src/Config/BotConfig.php:

public const BOT_INSTRUCTIONS = 'You are a helpful customer support assistant...';

Function Calling

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...';
}

Rate Limiting

Configure message limits and quotas in src/Config/BotConfig.php:

public const LIMITS = [
    'maxInputCharacters' => 1000,
    'maxOutputTokens' => 1000,
    'maxMessagesPerChat' => 500,
    // ...
];

API Endpoints

  • GET / - Bot information and status
  • POST /webhook - Webhook for incoming WhatsApp messages
  • POST /message - Send message endpoint
  • GET /sample - Send sample message
  • GET /files/{id} - Temporary file downloads

Troubleshooting

Common Issues

  1. "No active WhatsApp numbers"

    • Verify your Wassenger API key
    • Check that you have a connected WhatsApp device in Wassenger
  2. "WhatsApp number is not online"

    • Ensure your WhatsApp device is connected and online in Wassenger dashboard
  3. Webhook not receiving messages

    • Check that your webhook URL is accessible from the internet
    • Verify Ngrok tunnel is running (development mode)
    • Check firewall settings
  4. OpenAI API errors

    • Verify your OpenAI API key is valid
    • Check your OpenAI account has sufficient credits
    • Ensure the model name is correct

Debug Mode

Enable detailed logging by setting in .env:

LOG_LEVEL=debug

Then check the logs in your configured log directory.

API Documentation

This bot integrates with:

Production Deployment

Apache/Nginx Setup

  1. Document Root: Point to the public/ directory
  2. URL Rewriting: Configure rewrite rules to route all requests to index.php

Apache (.htaccess)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

Nginx

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;
}

Environment Configuration

# Set your production webhook URL
WEBHOOK_URL=https://yourdomain.com/webhook

# Use production logging
LOG_LEVEL=error

Security Considerations

  • 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

Performance Optimization

  • 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

Resources

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

License

MIT License - see LICENSE file for details.


Built with ❀️ using PHP and the Wassenger API.

About

A featured, easy-to-use, multimodal WhatsApp AI GPT-4o Chatbot in PHP for your Business. Supports GPT-4o with text + audio + image input, audio responses, and improved RAG + MCP Tools 🀩

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published