Revolutionizing Conversations: Integrating a WhatsApp Chatbot with Meta and ChatGPT Turbo using PHP

Shadrack Kipkoech
4 min readFeb 13, 2024

--

Introduction:
In the fast-evolving world of conversational AI, we embarked on a journey to enhance user interactions through a fully integrated WhatsApp chatbot. This project leverages PHP for seamless integration with Meta (formerly Facebook) and the powerful ChatGPT Turbo for natural language processing.

Technologies Used:
Our tech stack includes PHP for server-side scripting, Meta API for WhatsApp integration, and ChatGPT Turbo for advanced language understanding.

Key Achievements:
Successful integration of Meta API for WhatsApp to enable interactive and dynamic conversations.
Seamless incorporation of ChatGPT Turbo to enhance the chatbot’s natural language processing capabilities.
Overcoming challenges in authentication, message handling, and ensuring a smooth user experience.
Features and Demonstrations:
Rich multimedia support: Sending images, videos, and other media through the chatbot.
Dynamic responses: The chatbot adapts its responses based on user input and context.
Multi-step conversations: Handling complex interactions through a series of messages.
User Experience and Feedback:
Users have reported a significantly improved experience, praising the chatbot’s ability to understand and respond contextually. Real-world scenarios demonstrate the effectiveness of the integrated solution.

Testing and Performance:
Rigorous testing was conducted to ensure the reliability and performance of the chatbot. Performance metrics reveal optimized response times and efficient resource utilization.

Future Developments:
Integration of additional features, such as personalized user interactions and third-party API integrations.
Continuous optimization of the chatbot’s language understanding and response generation.

FULL CODE

Configure webhook

// Set your verify token
$verifyToken = "YOUR_KEY"; // Replace with your actual verify token

// Get the hub challenge, mode, and verify token from the request
$hubChallenge = isset($_GET['hub_challenge']) ? $_GET['hub_challenge'] : null;
$hubMode = isset($_GET['hub_mode']) ? $_GET['hub_mode'] : null;
$hubVerifyToken = isset($_GET['hub_verify_token']) ? $_GET['hub_verify_token'] : null;

// Check if the hub mode is 'subscribe' and the verify token matches
if ($hubMode === 'subscribe' && $hubVerifyToken === $verifyToken) {
// Respond with the hub challenge to complete the verification
echo $hubChallenge;
} else {
// Respond with an error or log the issue
echo "Verification failed.";
}

// Exit the script after verification
exit();

Full PHP code

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Specify the path to the log file
$logFilePath = 'PATH/TO/LOG/FILE';

// Set the default timezone
date_default_timezone_set('Africa/Nairobi');

// Decode incoming JSON data from WhatsApp webhook
$data = json_decode(file_get_contents('php://input'), true);

// Check if the data is from a WhatsApp Business Account and contains messages
if ($data['object'] == 'whatsapp_business_account' && isset($data['entry'][0]['changes'][0]['value']['messages'])) {

// Decode JSON data again for better readability
$data_json = file_get_contents('php://input');
$data_array = json_decode($data_json, true);

// Extract relevant information from the incoming data
$entry = $data_array['entry'];
$message_id = $entry[0]['id'];

$from = $entry[0]['changes'][0]['value']['messages'][0]['from'];
$to = $entry[0]['changes'][0]['value']['metadata']['display_phone_number'];

$senderName = $entry[0]['changes'][0]['value']['contacts'][0]['profile']['name'];

$type = $entry[0]['changes'][0]['value']['messages'][0]['type'];

// Determine the message type and extract the text
if ($type == 'text') {
$text = $entry[0]['changes'][0]['value']['messages'][0]['text']['body'];
} else if ($type == 'interactive') {
$interactive = $entry[0]['changes'][0]['value']['messages'][0]['interactive'];
$interactive_type = $entry[0]['changes'][0]['value']['messages'][0]['interactive']['type'];

if ($interactive_type == 'button_reply') {
$button_reply = $interactive['button_reply'];
$text = $button_reply['title'];
} else {
$list_reply = $interactive['list_reply'];
$text = $list_reply['title'];
}
} else {
// Default message if type is neither 'text' nor 'interactive'
$text = "Hello";
}

// Check if products have already been fetched for this user
getChatGPTResponse($text, $from);
}

function getChatGPTResponse($inputText, $from) {
// Log the user's input
logMessage("GPT |: ", $inputText, $from);

// Load the conversation context from a file (you may replace this with a database or cache)
$conversationContext = loadConversationContext($from);

// Add the user's message to the conversation context
$conversationContext[] = ['role' => 'user', 'content' => $inputText];

// Set parameters for ChatGPT API request
$data = [
'messages' => $conversationContext,
'model' => 'CHAT_GPT_MODEL',
'temperature' => 'TEMPERATURE',
'max_tokens' => 'MAX_TOKENS'
];

// Set headers for the ChatGPT API request
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . 'CHAT_GPT_API_KEY'
];

// Use cURL to make a request to ChatGPT API
$ch = curl_init("https://api.openai.com/v1/chat/completions");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute the cURL session and fetch result
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Decode the API response
$responseArr = json_decode($response, true);

// Extract the model's reply
$reply = $responseArr['choices'][0]['message']['content'];

// Add the model's reply to the conversation context
$conversationContext[] = ['role' => 'system', 'content' => $reply];

// Save the updated conversation context to the file
saveConversationContext($from, $conversationContext);

// Send the WhatsApp message with the model's reply
sendWhatsAppMessage($from, $reply);

// Log the model's reply
logMessage("OUT |: ", $reply, $from);
}

// Load the conversation context from the specified directory for the given user
function loadConversationContext($userId) {
$filePath = "PATH/TO/conversations/$userId.json";
if (file_exists($filePath)) {
$contextJson = file_get_contents($filePath);
return json_decode($contextJson, true);
}
return [];
}

// Save the conversation context to the specified directory for the given user
function saveConversationContext($userId, $context) {
$filePath = "PATH?TO/conversations/$userId.json";
if (!file_exists(dirname($filePath))) {
mkdir(dirname($filePath), 0755, true);
}
file_put_contents($filePath, json_encode($context));
}

// Send a WhatsApp message
function sendWhatsAppMessage($recipientNumber, $message) {
$accessToken = 'META_ACCESS_TOKEN';
$url = 'https://graph.facebook.com/VERION_NUMBER/PHONE_NUMBER_ID/messages';

$_message = " *Ubuni AI*\n\n" . $message;

$data = [
'messaging_product' => 'whatsapp',
'to' => 'whatsapp:' . $recipientNumber,
'type' => 'text',
'text' => [
'body' => $_message,
],
];

$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken,
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

$responseData = json_decode($response, true);

// Print the message status
if (isset($responseData['messages'][0]['message_status'])) {
$messageStatus = $responseData['messages'][0]['message_status'];
echo 'Message Status: ' . $messageStatus;
} else {
echo 'Unable to retrieve message status.';
}
}

// Log a message with timestamp
function logMessage($type, $message, $phone_number) {
global $logFilePath;
$logMessage = date('Y-m-d H:i:s') . ' | ' . $type . ' | ' . $phone_number . ' | ' . $message . PHP_EOL;
file_put_contents($logFilePath, $logMessage, FILE_APPEND);
}

?>

Conclusion:
The successful integration of a WhatsApp chatbot with Meta and ChatGPT Turbo using PHP has opened new possibilities for interactive and engaging conversations. This journey showcases the potential of combining powerful technologies to create intelligent and user-friendly chatbot experiences.

To try it out chatting +254748406509 on WhatsApp

--

--

Shadrack Kipkoech

Mobile App Developer | Android | IOS | Java | Kotlin | Swift | Objective C | Jetpack Compose