52 lines
1.8 KiB
PHP
52 lines
1.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
require_once __DIR__ . '/../includes/bootstrap.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$name = trim($_POST['name'] ?? '');
|
|
$phone = trim($_POST['phone'] ?? '');
|
|
$twilioId = (int)($_POST['twilio_number_id'] ?? 0);
|
|
|
|
if ($phone === '' || $twilioId <= 0) {
|
|
echo json_encode(['success' => false, 'error' => '号码与发送账号不能为空。']);
|
|
exit;
|
|
}
|
|
|
|
$pdo = db();
|
|
$pdo->beginTransaction();
|
|
try {
|
|
$stmt = $pdo->prepare("SELECT id FROM contacts WHERE phone = :phone");
|
|
$stmt->bindValue(':phone', $phone);
|
|
$stmt->execute();
|
|
$contactId = (int)($stmt->fetchColumn() ?: 0);
|
|
|
|
if ($contactId === 0) {
|
|
$stmt = $pdo->prepare("INSERT INTO contacts (name, phone) VALUES (:name, :phone)");
|
|
$stmt->bindValue(':name', $name !== '' ? $name : null);
|
|
$stmt->bindValue(':phone', $phone);
|
|
$stmt->execute();
|
|
$contactId = (int)$pdo->lastInsertId();
|
|
}
|
|
|
|
$stmt = $pdo->prepare("SELECT id FROM conversations WHERE contact_id = :cid AND twilio_number_id = :tid");
|
|
$stmt->bindValue(':cid', $contactId, PDO::PARAM_INT);
|
|
$stmt->bindValue(':tid', $twilioId, PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
$conversationId = (int)($stmt->fetchColumn() ?: 0);
|
|
|
|
if ($conversationId === 0) {
|
|
$stmt = $pdo->prepare("INSERT INTO conversations (contact_id, twilio_number_id) VALUES (:cid, :tid)");
|
|
$stmt->bindValue(':cid', $contactId, PDO::PARAM_INT);
|
|
$stmt->bindValue(':tid', $twilioId, PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
$conversationId = (int)$pdo->lastInsertId();
|
|
}
|
|
|
|
$pdo->commit();
|
|
echo json_encode(['success' => true, 'conversation_id' => $conversationId]);
|
|
} catch (Throwable $e) {
|
|
$pdo->rollBack();
|
|
echo json_encode(['success' => false, 'error' => '保存失败,请稍后再试。']);
|
|
}
|