55 lines
1.8 KiB
PHP
55 lines
1.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
require_once __DIR__ . '/../includes/bootstrap.php';
|
|
require_once __DIR__ . '/../includes/twilio.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$payload = json_decode((string)file_get_contents('php://input'), true);
|
|
$conversationId = (int)($payload['conversation_id'] ?? 0);
|
|
$body = trim($payload['body'] ?? '');
|
|
|
|
if ($conversationId <= 0 || $body === '') {
|
|
echo json_encode(['success' => false, 'error' => '会话与内容不能为空。']);
|
|
exit;
|
|
}
|
|
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("
|
|
SELECT c.id, ct.phone, t.account_sid, t.auth_token, t.from_number, t.label, t.is_active
|
|
FROM conversations c
|
|
JOIN contacts ct ON ct.id = c.contact_id
|
|
JOIN twilio_numbers t ON t.id = c.twilio_number_id
|
|
WHERE c.id = :cid
|
|
");
|
|
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
$twilio = $stmt->fetch();
|
|
|
|
if (!$twilio) {
|
|
echo json_encode(['success' => false, 'error' => '找不到会话。']);
|
|
exit;
|
|
}
|
|
|
|
$status = 'stored';
|
|
if ((int)$twilio['is_active'] === 1 && $twilio['account_sid'] && $twilio['auth_token']) {
|
|
$sendResult = twilio_send_sms($twilio, $twilio['phone'], $body);
|
|
if (!empty($sendResult['success'])) {
|
|
$status = 'sent';
|
|
} else {
|
|
$status = 'failed';
|
|
}
|
|
}
|
|
|
|
$stmt = $pdo->prepare("INSERT INTO messages (conversation_id, direction, body, status) VALUES (:cid, 'outbound', :body, :status)");
|
|
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
|
|
$stmt->bindValue(':body', $body);
|
|
$stmt->bindValue(':status', $status);
|
|
$stmt->execute();
|
|
|
|
$stmt = $pdo->prepare("UPDATE conversations SET last_message_at = NOW() WHERE id = :cid");
|
|
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
|
|
echo json_encode(['success' => true, 'status' => $status]);
|