2025-12-11 11:30:18 +08:00

78 lines
2.1 KiB
TypeScript
Raw 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.

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { sendMsg } from '@/lib/qqbot';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { name, phone, email, description } = body;
// 验证必填字段
if (!name || !phone || !email || !description) {
return NextResponse.json(
{ error: '所有字段都是必填的' },
{ status: 400 }
);
}
// 验证邮箱格式
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return NextResponse.json(
{ error: '邮箱格式不正确' },
{ status: 400 }
);
}
// 验证手机号格式(中国手机号)
const phoneRegex = /^1[3-9]\d{9}$/;
if (!phoneRegex.test(phone)) {
return NextResponse.json(
{ error: '手机号格式不正确' },
{ status: 400 }
);
}
// 保存到数据库
const message = await prisma.message.create({
data: {
name,
phone,
email,
description,
},
});
// 发送 QQ 消息通知管理员
const qqBotUrl = process.env.QQ_BOT_URL;
const qqBotTargetId = process.env.QQ_BOT_TARGET_ID;
if (qqBotUrl && qqBotTargetId) {
const notificationMsg = `【新留言通知】\n姓名${name}\n电话${phone}\n邮箱${email}\n需求描述${description}\n时间${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}`;
try {
await sendMsg(notificationMsg, qqBotTargetId, qqBotUrl);
} catch (qqError) {
console.error('QQ消息发送失败:', qqError);
// QQ消息发送失败不影响留言保存
}
}
return NextResponse.json(
{
success: true,
message: '留言提交成功,我们会尽快与您联系!',
data: { id: message.id }
},
{ status: 201 }
);
} catch (error) {
console.error('留言提交失败:', error);
return NextResponse.json(
{ error: '服务器错误,请稍后再试' },
{ status: 500 }
);
}
}