Files
crm.clientright.ru/aiassist/typebot_proxy.php

144 lines
4.6 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Typebot Proxy - обход CORS для интеграции с Typebot
*/
// Включаем отображение ошибок для отладки
error_reporting(E_ALL);
ini_set('display_errors', 0); // Отключаем вывод в браузер
ini_set('log_errors', 1);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
// Обработка preflight запросов
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// Проверяем метод запроса
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit();
}
// Получаем данные из запроса
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!$data) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON data']);
exit();
}
// Определяем тип запроса
$action = $data['action'] ?? 'startChat';
$sessionId = $data['sessionId'] ?? null;
$message = $data['message'] ?? '';
$context = $data['context'] ?? [];
// Логируем запрос
error_log("Typebot Proxy: Action={$action}, SessionId={$sessionId}, Message={$message}");
try {
// Проверяем доступность cURL
if (!function_exists('curl_init')) {
throw new Exception('cURL extension is not available');
}
if ($action === 'startChat') {
// Создаем новую сессию
$url = 'https://bot.klientprav.tech/api/v1/typebots/my-typebot-lezm06l/startChat';
$payload = [
'message' => $message,
'prefilledVariables' => [
'projectId' => $context['projectId'] ?? '',
'module' => $context['module'] ?? '',
'view' => $context['view'] ?? '',
'userId' => $context['userId'] ?? '',
'input' => $message // Передаем сообщение как переменную input
],
'isStreamEnabled' => false
];
} elseif ($action === 'continueChat' && $sessionId) {
// Продолжаем существующую сессию
$url = "https://bot.klientprav.tech/api/v1/sessions/{$sessionId}/continueChat";
$payload = [
'message' => $message
];
} else {
throw new Exception('Invalid action or missing sessionId');
}
// Выполняем запрос к Typebot
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'User-Agent: CRM-Integration/1.0'
],
CURLOPT_TIMEOUT => 60,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_FOLLOWLOCATION => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("cURL error: {$error}");
}
if ($httpCode !== 200) {
if ($httpCode === 504 || strpos($response, 'Gateway Timeout') !== false) {
throw new Exception("Typebot server timeout. Please try again later.");
}
throw new Exception("HTTP error: {$httpCode}");
}
$responseData = json_decode($response, true);
if (!$responseData) {
throw new Exception('Invalid JSON response from Typebot');
}
// Логируем ответ
error_log("Typebot Proxy: Response received, SessionId=" . ($responseData['sessionId'] ?? 'N/A'));
error_log("Typebot Proxy: Messages count=" . (isset($responseData['messages']) ? count($responseData['messages']) : 0));
error_log("Typebot Proxy: ClientSideActions count=" . (isset($responseData['clientSideActions']) ? count($responseData['clientSideActions']) : 0));
error_log("Typebot Proxy: Has input=" . (isset($responseData['input']) ? 'yes' : 'no'));
// Возвращаем ответ
echo json_encode([
'success' => true,
'data' => $responseData,
'timestamp' => date('Y-m-d H:i:s')
]);
} catch (Exception $e) {
error_log("Typebot Proxy Error: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage(),
'timestamp' => date('Y-m-d H:i:s')
]);
}
?>