PHP运行之后无法正常显示页面 New
2025/07/03 20:53:59
- <?php if(!defined('IN_DISCUZ')) { exit('Access Denied'); } global $_G; class plugin_w0504_ym { protected $config; protected $api_key; protected $api_url; protected $api_model; public function __construct() { // 从插件配置获取环境变量 $this->config = C::t('common_setting')->fetch('w0504_ym_config'); $this->api_key = $this->config['OPENAI_API_KEY'] ?? ''; $this->api_url = $this->config['OPENAI_API_BASE_URL'] ?? 'https://openrouter.ai/api/v1'; $this->api_model = $this->config['OPENAI_API_MODEL'] ?? 'deepseek/deepseek-r1:free'; } // 公共方法供全局作用域调用 public function check_api_key() { return !empty($this->api_key); } // 发送消息处理 public function send_message() { $message = dhtmlspecialchars(trim($_POST['message'])); if (empty($message)) { $this->ajax_error('消息不能为空'); } $post_data = json_encode([ 'model' => $this->api_model, 'messages' => [ ['role' => 'user', 'content' => $message] ] ]); $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $this->api_url . '/chat/completions', CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . $this->api_key, 'Content-Type: application/json' ], CURLOPT_POSTFIELDS => $post_data, CURLOPT_TIMEOUT => 30 ]); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (curl_errno($ch)) { $this->ajax_error('API请求失败: ' . curl_error($ch)); } curl_close($ch); if ($http_code != 200) { $this->ajax_error('API返回错误: HTTP ' . $http_code); } $data = json_decode($response, true); $reply = $data['choices'][0]['message']['content'] ?? '未收到有效回复'; // 返回JSON响应 header('Content-Type: application/json'); echo json_encode(['reply' => $reply]); } // 错误处理函数 protected function ajax_error($message) { header('Content-Type: application/json'); echo json_encode(['error' => $message]); exit(); } } // === 全局作用域代码开始 === $plugin = new plugin_w0504_ym(); // 检查API密钥配置 if (empty($plugin->api_key)) { die('管理员未配置API密钥,请联系管理员'); } // 处理消息发送 if ($_GET['action'] == 'send' && $_POST['message']) { $plugin->send_message(); exit(); } // 显示聊天界面 include template('w0504_ym:chat'); return; // === 全局作用域代码结束 ===
我知道答案 回答被采纳将会获得1 贡献 已有1人回答