This commit is contained in:
2026-02-06 13:49:04 +01:00
parent 73f47b161c
commit 371c3da66c
2 changed files with 56 additions and 17 deletions

View File

@@ -541,19 +541,29 @@ function handleChatMessage($data) {
sendResponse(false, 'Nachricht darf nicht leer sein', null, 400);
}
// Format data for n8n webhook - use 'chatInput' as the message field name
// which is commonly expected by n8n AI chat workflows
$chatData = [
'type' => 'chat_message',
'session_id' => $sessionId,
'message' => $message,
'chatInput' => $message, // Alternative field name for n8n
'query' => $message, // Another common n8n field name
'timestamp' => date('c'),
'source' => 'website_chat',
'ip_address' => getClientIP(),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
];
// Log the outgoing request for debugging
error_log('KI Chat Request - URL: ' . KI_CHAT_WEBHOOK_URL . ' - Data: ' . json_encode($chatData));
// Send to KI Chat webhook
$webhookResult = sendToWebhook($chatData, KI_CHAT_WEBHOOK_URL);
// Log the response for debugging
error_log('KI Chat Response: ' . json_encode($webhookResult));
$debugData = DEBUG_MODE ? [
'session_id' => $sessionId,
'webhook_result' => $webhookResult,
@@ -561,9 +571,32 @@ function handleChatMessage($data) {
] : null;
if ($webhookResult['success']) {
// Try to parse response from webhook
// Try to parse response from webhook - handle various n8n response formats
$response = json_decode($webhookResult['response'], true);
$aiResponse = $response['message'] ?? $response['output'] ?? 'Vielen Dank für Ihre Nachricht. Ich melde mich so schnell wie möglich bei Ihnen.';
$aiResponse = null;
// Check common n8n response field names
if ($response) {
$aiResponse = $response['message']
?? $response['output']
?? $response['text']
?? $response['response']
?? $response['answer']
?? $response['result']
?? (is_array($response) && isset($response[0]['output']) ? $response[0]['output'] : null)
?? (is_array($response) && isset($response[0]['message']) ? $response[0]['message'] : null)
?? null;
}
// If still no response, use the raw response if it's a string
if (!$aiResponse && is_string($webhookResult['response']) && !empty($webhookResult['response'])) {
$aiResponse = $webhookResult['response'];
}
// Fallback message
if (!$aiResponse) {
$aiResponse = 'Vielen Dank für Ihre Nachricht. Ich melde mich so schnell wie möglich bei Ihnen.';
}
sendResponse(true, 'Nachricht gesendet', array_merge($debugData ?? [], [
'session_id' => $sessionId,