34318-vm/api/webhook.php
Flatlogic Bot 64b701287d v1
2025-09-23 20:48:22 +00:00

48 lines
1.6 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
// Get the POST data
$json = file_get_contents('php://input');
$data = json_decode($json, true);
// Acknowledge the request immediately to prevent timeouts
http_response_code(200);
// Log the request for debugging
file_put_contents('webhook_log.txt', $json . "\n", FILE_APPEND);
// Check for the expected structure (this is a simplified example)
if (isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
$message_data = $data['entry'][0]['changes'][0]['value']['messages'][0];
$phone_number = $message_data['from'];
$message_body = $message_data['text']['body'];
$name = $data['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name'] ?? 'New Lead';
try {
$pdo = db();
// Check if lead exists
$stmt = $pdo->prepare("SELECT * FROM leads WHERE company = ?"); // Using company to store phone number for simplicity
$stmt->execute([$phone_number]);
$lead = $stmt->fetch();
if (!$lead) {
// Create new lead
$stmt = $pdo->prepare("INSERT INTO leads (name, company, status) VALUES (?, ?, 'New')");
$stmt->execute([$name, $phone_number]);
$lead_id = $pdo->lastInsertId();
} else {
$lead_id = $lead['id'];
}
// Save the message
$stmt = $pdo->prepare("INSERT INTO messages (lead_id, sender, message) VALUES (?, 'user', ?)");
$stmt->execute([$lead_id, $message_body]);
} catch (PDOException $e) {
// Log errors
file_put_contents('webhook_error_log.txt', $e->getMessage() . "\n", FILE_APPEND);
}
}