You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网站集成ChatGPT(OpenAI) API无响应问题求助

问题排查与修复:ChatGPT集成后返回Null无响应

核心问题分析

你的代码存在三个关键问题导致返回Null:

  1. 请求数据解析错误:前端发送JSON格式POST请求,但后端用$_POST['message']读取,无法获取JSON数据
  2. API请求缺少必填参数:OpenAI Chat Completions API必须指定model字段(如gpt-3.5-turbo)
  3. 无错误处理机制:API请求失败、JSON解析失败等情况未捕获,直接访问数组键导致报错返回Null

修复后的代码

index.php(仅补充容错逻辑)

<!DOCTYPE html>
<html>
<head>
    <title>ChatGPT Example</title>
</head>
<body>
    <h1>Chat with ChatGPT</h1>

    <div id="chat-container">
        <div id="chat-history">
            <!-- Chat messages will be displayed here -->
        </div>
        <div id="user-input">
            <input type="text" id="user-message" placeholder="Type your message..." />
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <script>
        async function sendMessage() {
            const userMessage = document.getElementById('user-message').value;
            if (userMessage.trim() === '') return;

            appendMessage('You', userMessage);

            const response = await fetch('get_response.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message: userMessage }),
            });

            const responseData = await response.json();
            const chatGptResponse = responseData.response || '抱歉,无法获取回复';
            appendMessage('ChatGPT', chatGptResponse);
        }

        function appendMessage(sender, message) {
            const chatHistory = document.getElementById('chat-history');
            const messageDiv = document.createElement('div');
            messageDiv.innerHTML = `<strong>${sender}:</strong> ${message}`;
            chatHistory.appendChild(messageDiv);

            // Scroll to the bottom of the chat history
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }
    </script>
</body>
</html>

get_response.php(关键修复)

<?php
// 调试阶段启用错误提示,上线后关闭
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 替换为你的OpenAI API密钥
$apiKey = 'YOUR_OPENAI_API_KEY';

// 读取JSON格式的请求数据
$input = file_get_contents('php://input');
$requestData = json_decode($input, true);

// 验证用户消息有效性
if (!isset($requestData['message']) || trim($requestData['message']) === '') {
    header('Content-Type: application/json');
    echo json_encode(['response' => '请输入有效消息']);
    exit;
}

$userMessage = $requestData['message'];

// OpenAI API请求配置(添加必填model字段)
$apiUrl = 'https://api.openai.com/v1/chat/completions';
$data = [
    'model' => 'gpt-3.5-turbo', // 必填参数,可替换为gpt-4等其他模型
    'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user', 'content' => $userMessage],
    ],
];

$options = [
    'http' => [
        'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
        'method' => 'POST',
        'content' => json_encode($data),
        'timeout' => 30, // 设置超时避免请求挂起
    ],
];

$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);

// 检查API请求是否成功
if ($response === false) {
    $error = error_get_last();
    header('Content-Type: application/json');
    echo json_encode(['response' => '请求OpenAI API失败:' . $error['message']]);
    exit;
}

$decodedResponse = json_decode($response, true);

// 验证API返回结构
if (!isset($decodedResponse['choices'][0]['message']['content'])) {
    $errorMsg = isset($decodedResponse['error']['message']) ? $decodedResponse['error']['message'] : '无法解析API返回数据';
    header('Content-Type: application/json');
    echo json_encode(['response' => '获取回复失败:' . $errorMsg]);
    exit;
}

$assistantReply = $decodedResponse['choices'][0]['message']['content'];

// 返回响应
header('Content-Type: application/json');
echo json_encode(['response' => $assistantReply]);
?>

额外调试建议

  • 确认API密钥正确且账户有可用额度
  • 检查服务器是否允许file_get_contents访问外部HTTPS链接(若受限,可改用cURL实现请求)
  • 调试时可直接打印$response和$decodedResponse查看具体错误信息

内容的提问来源于stack exchange,提问作者Daniel Dessler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 05:30:17