先看效果:
接着在/system里面创建api_generate_ai.php文件,见下面代码写入保存
header('Content-Type: application/json');
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
// 错误处理配置
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'ai_errors.log');
// 智谱AI配置
define('ZHIPUAI_API_KEY', 'API_KEY');
define('ZHIPUAI_API_URL', 'https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_pro/invoke');
// 速率限制配置
$rateLimit = 10; // 每分钟最大请求数
$rateLimitWindow = 60; // 秒
// 速率限制检查
function checkRateLimit() {
$redis = new Redis();
try {
$redis->connect('127.0.0.1', 6379, 1);
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$key = "rate_limit:{$ip}";
$current = $redis->incr($key);
if ($current === 1) {
$redis->expire($key, $GLOBALS['rateLimitWindow']);
}
if ($current > $GLOBALS['rateLimit']) {
http_response_code(429);
echo json_encode([
'success' => false,
'message' => '请求过于频繁,请稍后再试',
'retry_after' => $redis->ttl($key)
]);
exit;
}
} catch (Exception $e) {
error_log("Redis连接失败: " . $e->getMessage());
}
}
// 主处理流程
try {
// 检查速率限制
checkRateLimit();
// 获取输入数据
$jsonInput = file_get_contents('php://input');
$input = json_decode($jsonInput, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException('无效的JSON输入');
}
// 验证输入
if (empty($input['url']) || empty($input['intro']) || empty($input['tags'])) {
throw new InvalidArgumentException('缺少必要参数');
}
// 构建提示词
$prompt = "你是一个专业的网站内容优化助手,请根据以下信息生成HTML格式的网站简介:nn";
$prompt .= "# 网站地址n{$input['url']}nn";
$prompt .= "# 当前描述n{$input['intro']}nn";
$prompt .= "# 相关标签n{$input['tags']}nn";
$prompt .= "# 生成要求n";
$prompt .= "1. 输出600字左右的HTML内容n";
$prompt .= "2. 使用
$prompt .= "3. 包含SEO关键词但保持自然n";
$prompt .= "5. 符合中文阅读习惯nn";
$prompt .= "请直接输出HTML代码(无需解释):";
// 调用智谱AI API
$payload = [
'prompt' => [
[
'role' => 'user',
'content' => $prompt
]
],
'temperature' => 0.7,
'max_tokens' => 1000,
'top_p' => 0.9,
'request_id' => uniqid('zhipu_', true)
];
$headers = [
'Content-Type: application/json',
'Authorization: ' . ZHIPUAI_API_KEY
];
$options = [
'http' => [
'header' => implode("rn", $headers),
'method' => 'POST',
'content' => json_encode($payload),
'timeout' => 15
]
];
$context = stream_context_create($options);
$response = @file_get_contents(ZHIPUAI_API_URL, false, $context);
if ($response === false) {
throw new RuntimeException("API请求失败");
}
$decoded = json_decode($response, true);
if (!isset($decoded['code']) || $decoded['code'] !== 200) {
throw new RuntimeException("API返回错误: " . ($decoded['msg'] ?? '未知错误'));
}
$content = $decoded['data']['choices'][0]['content'] ?? '';
// 返回成功响应
echo json_encode([
'success' => true,
'content' => $content,
'usage' => [
'model' => $decoded['data']['model'] ?? 'chatglm_pro',
'tokens' => $decoded['data']['usage']['total_tokens'] ?? 0
]
]);
} catch (InvalidArgumentException $e) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => $e->getMessage(),
'error_code' => 'INVALID_INPUT'
]);
} catch (RuntimeException $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => $e->getMessage(),
'error_code' => 'API_ERROR'
]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => '服务器内部错误',
'error_code' => 'INTERNAL_ERROR'
]);
}
?>