Fix E2EE decryption issue and duplicate webhook insertion
This commit is contained in:
@@ -202,19 +202,40 @@ class WhatsAppController extends BaseController
|
||||
|
||||
$msgData = $body['message'];
|
||||
|
||||
// 0. Check if this message has already been processed (deduplication)
|
||||
if (!empty($msgData['id'])) {
|
||||
$alreadyLogged = \App\Core\Database::selectOne(
|
||||
"SELECT id FROM messages_log WHERE whatsapp_message_id = ? LIMIT 1",
|
||||
[$msgData['id']]
|
||||
);
|
||||
if ($alreadyLogged) {
|
||||
// Message already processed, return 200 immediately to prevent duplicate replies & DB errors
|
||||
$response->status(200)->json([
|
||||
'status' => 'success',
|
||||
'message' => 'Message already processed (duplicate detected)'
|
||||
]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Find or create the contact in the CRM
|
||||
$contact = \App\Models\Contact::findByPhone($session['company_id'], $msgData['phone']);
|
||||
if (!$contact) {
|
||||
|
||||
|
||||
// Determine a fallback name
|
||||
$contactName = !empty($msgData['name']) ? $msgData['name'] : 'WA-' . substr($msgData['phone'], -4);
|
||||
\App\Models\Contact::createSecure([
|
||||
'company_id' => $session['company_id'],
|
||||
'name' => $contactName,
|
||||
'phone' => $msgData['phone'],
|
||||
'notes' => 'Auto-created via incoming WhatsApp message'
|
||||
]);
|
||||
try {
|
||||
\App\Models\Contact::createSecure([
|
||||
'company_id' => $session['company_id'],
|
||||
'name' => $contactName,
|
||||
'phone' => $msgData['phone'],
|
||||
'notes' => 'Auto-created via incoming WhatsApp message'
|
||||
]);
|
||||
} catch (\PDOException $e) {
|
||||
// Ignore duplicate contact error if another thread created it concurrently
|
||||
if ($e->getCode() !== '23000' && strpos($e->getMessage(), '1062') === false) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Log the incoming message in history log
|
||||
|
||||
Reference in New Issue
Block a user