Want to connect ChatGPT to WhatsApp for intelligent, AI-powered automatic replies? Imagine having OpenAI's GPT respond to your WhatsApp messages automatically with contextual, human-like responses.
In this comprehensive guide, I'll show you exactly how to integrate ChatGPT with WhatsApp using AutoReply Mate's Server API — complete with code examples, setup instructions, and real-world use cases.
🤖 What You'll Build
By the end of this guide, you'll have:
- ✅ WhatsApp messages automatically forwarded to your server
- ✅ OpenAI ChatGPT generating intelligent replies
- ✅ AI-generated responses sent back automatically
- ✅ Full control over prompts, context, and behavior
How ChatGPT + WhatsApp Integration Works
Here's the flow:
- Message arrives on WhatsApp → AutoReply Mate detects it
- AutoReply Mate forwards message to your server (HTTP POST)
- Your server sends message to OpenAI ChatGPT API
- ChatGPT generates intelligent reply
- Your server returns reply to AutoReply Mate
- AutoReply Mate sends AI response back to WhatsApp sender
Why this approach?
- ✅ Your phone doesn't need internet access to OpenAI (server does the API call)
- ✅ You control the prompts and behavior
- ✅ Can add custom logic (database lookups, business rules, etc.)
- ✅ Your OpenAI API key stays on your server (not on phone)
Prerequisites
You'll need:
- ✅ AutoReply Mate PRO subscription (Server API is PRO feature)
- ✅ OpenAI API key from platform.openai.com
- ✅ A server (Node.js, Python, PHP, etc.) - can use free hosting like Vercel, Railway, or Render
- ✅ Basic programming knowledge
Step 1: Get OpenAI API Key
- Go to platform.openai.com/api-keys
- Sign in or create an account
- Click "Create new secret key"
- Name it (e.g., "WhatsApp AutoReply")
- Copy the key (starts with
sk-...) - Store it securely - you'll need it for your server
Note: OpenAI charges per token used. GPT-3.5-turbo is inexpensive (~$0.002 per 1K tokens). GPT-4 is more expensive but produces better results.
Step 2: Create Your Server Endpoint
You need a server that receives WhatsApp messages and returns ChatGPT-generated replies. Here are examples in multiple languages:
Option A: Node.js + Express (Recommended)
// server.js
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
const OPENAI_API_KEY = 'sk-YOUR_API_KEY_HERE';
const API_SECRET = 'your-secret-key-123'; // For authentication
app.post('/whatsapp-reply', async (req, res) => {
// Verify API key
const apiKey = req.headers['x-api-key'];
if (apiKey !== API_SECRET) {
return res.status(401).json({ error: 'Unauthorized' });
}
try {
const { sender, message, type } = req.body;
// Call OpenAI ChatGPT API
const completion = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'You are a helpful WhatsApp assistant. Respond concisely and naturally.'
},
{
role: 'user',
content: message
}
],
max_tokens: 150,
temperature: 0.7
},
{
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
const reply = completion.data.choices[0].message.content.trim();
// Return response in AutoReply Mate format
res.json({
text: reply,
status: 'success'
});
} catch (error) {
console.error('Error:', error.response?.data || error.message);
res.json({
text: "Sorry, I encountered an error. Please try again.",
status: 'error'
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Install dependencies:
npm install express axiosRun server:
node server.jsOption B: Python + Flask
# app.py
from flask import Flask, request, jsonify
import openai
import os
app = Flask(__name__)
OPENAI_API_KEY = 'sk-YOUR_API_KEY_HERE'
API_SECRET = 'your-secret-key-123'
openai.api_key = OPENAI_API_KEY
@app.route('/whatsapp-reply', methods=['POST'])
def whatsapp_reply():
# Verify API key
api_key = request.headers.get('X-API-Key')
if api_key != API_SECRET:
return jsonify({'error': 'Unauthorized'}), 401
try:
data = request.json
sender = data.get('sender')
message = data.get('message')
# Call OpenAI ChatGPT
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": "You are a helpful WhatsApp assistant. Respond concisely."
},
{
"role": "user",
"content": message
}
],
max_tokens=150,
temperature=0.7
)
reply = completion.choices[0].message.content.strip()
return jsonify({
'text': reply,
'status': 'success'
})
except Exception as e:
print(f"Error: {e}")
return jsonify({
'text': 'Sorry, I encountered an error.',
'status': 'error'
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)
Install dependencies:
pip install flask openaiOption C: PHP (Shared Hosting)
<?php
// whatsapp-reply.php
header('Content-Type: application/json');
$OPENAI_API_KEY = 'sk-YOUR_API_KEY_HERE';
$API_SECRET = 'your-secret-key-123';
// Verify API key
$headers = getallheaders();
$apiKey = $headers['X-API-Key'] ?? '';
if ($apiKey !== $API_SECRET) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit;
}
// Get request data
$data = json_decode(file_get_contents('php://input'), true);
$sender = $data['sender'] ?? '';
$message = $data['message'] ?? '';
try {
// Call OpenAI API
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $OPENAI_API_KEY,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'model' => 'gpt-3.5-turbo',
'messages' => [
[
'role' => 'system',
'content' => 'You are a helpful WhatsApp assistant.'
],
[
'role' => 'user',
'content' => $message
]
],
'max_tokens' => 150
]));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
$reply = $result['choices'][0]['message']['content'];
echo json_encode([
'text' => trim($reply),
'status' => 'success'
]);
} catch (Exception $e) {
echo json_encode([
'text' => 'Sorry, I encountered an error.',
'status' => 'error'
]);
}
?>
Step 3: Deploy Your Server
You need to host your server on a public URL. Options:
Free Hosting Options:
- Vercel: Great for Node.js (free tier)
- Railway: Easy deployment for Node.js/Python (free $5 credit)
- Render: Supports Node.js, Python, PHP (free tier)
- Heroku: Classic option (paid plans)
- Your own server: VPS like DigitalOcean, AWS, etc.
Once deployed, you'll get a public URL like:
https://your-app.vercel.app/whatsapp-reply
Step 4: Configure AutoReply Mate
1. Open AutoReply Mate App
Make sure you have PRO subscription (Server API is PRO feature)
2. Go to Server API Settings
- Open AutoReply Mate
- Tap Settings → Server API
- Find WhatsApp configuration
3. Configure WhatsApp API
Enter your server details:
- API Endpoint URL:
https://your-app.vercel.app/whatsapp-reply - X-API-Key:
your-secret-key-123(same as in your server code) - Enabled: Toggle ON
4. Test the Integration
- Tap "Test API" in AutoReply Mate
- Send a test message
- Check if you get a ChatGPT-generated response
- If successful, you'll see ✅ "API Test Successful"
Step 5: Go Live!
Once testing passes:
- Make sure Server API is enabled for WhatsApp
- Ask a friend to send you a WhatsApp message
- They should receive an AI-generated reply from ChatGPT
- Monitor your server logs to see requests
Advanced Customization
1. Custom System Prompts
Change the ChatGPT behavior by modifying the system message:
'system': 'You are a friendly customer support agent for [Your Business].
Answer questions about our products, pricing, and hours.
Be concise and helpful. If you don't know, say so.'
2. Context & Conversation History
To make ChatGPT remember previous messages, store conversation history in a database:
// Pseudo-code
const conversation = await getConversationHistory(sender);
const messages = [
{ role: 'system', content: '...' },
...conversation, // Previous messages
{ role: 'user', content: message }
];
3. Business Logic Integration
Add custom logic before calling ChatGPT:
// Check if message is about pricing
if (message.includes('price') || message.includes('cost')) {
return res.json({
text: 'Our pricing starts at $99. View details: https://yoursite.com/pricing',
status: 'success'
});
}
// Otherwise, use ChatGPT
const reply = await callChatGPT(message);
4. Use GPT-4 for Better Results
Change model to GPT-4 (more expensive but smarter):
model: 'gpt-4' // Instead of 'gpt-3.5-turbo'
Real-World Use Cases
1. Customer Support
Automatically answer product questions, pricing inquiries, and FAQs with intelligent, context-aware responses.
2. Personal Assistant
Have ChatGPT handle your personal messages when you're busy, summarizing important information.
3. Lead Qualification
ChatGPT asks qualifying questions to potential customers and saves responses to your database.
4. Appointment Scheduling
AI handles appointment requests and integrates with your calendar API.
Cost Estimation
OpenAI ChatGPT API Pricing (as of 2026):
- GPT-3.5-turbo: ~$0.002 per 1,000 tokens
- GPT-4: ~$0.03 per 1,000 tokens
Example cost calculation:
- Average message: 100 tokens input + 150 tokens output = 250 tokens
- 100 messages/day × 250 tokens = 25,000 tokens/day
- Cost with GPT-3.5: 25,000 × $0.002 / 1,000 = $0.05/day
- Monthly: ~$1.50/month for 100 messages/day
Very affordable for most use cases!
Troubleshooting
Error: "API Test Failed"
- Check your server URL is correct and publicly accessible
- Verify X-API-Key matches between app and server
- Check server logs for errors
- Test your endpoint with curl or Postman
ChatGPT replies are slow
- Reduce
max_tokensto 100 or less - Use GPT-3.5-turbo instead of GPT-4
- Optimize your server's network connection
Getting rate limited
- Add rate limiting on your server
- Use AutoReply Mate's cooldown feature
- Upgrade your OpenAI plan
Alternative: Claude AI Integration
You can also use Anthropic's Claude AI instead of ChatGPT:
// Using Claude API
const response = await axios.post(
'https://api.anthropic.com/v1/messages',
{
model: 'claude-3-sonnet-20240229',
messages: [{ role: 'user', content: message }],
max_tokens: 150
},
{
headers: {
'x-api-key': CLAUDE_API_KEY,
'anthropic-version': '2023-06-01'
}
}
);
Ready to Build AI-Powered Auto Replies?
Get AutoReply Mate PRO and start integrating ChatGPT today
Get AutoReply Mate PRO →Summary
Integrating ChatGPT with WhatsApp for automated replies involves:
- Get OpenAI API key
- Create server endpoint (Node.js, Python, or PHP)
- Deploy server to public URL
- Configure AutoReply Mate's Server API
- Test and go live
The result? Intelligent, AI-powered automatic WhatsApp replies that understand context and respond naturally.
Next steps: