109 lines
2.7 KiB
TypeScript
109 lines
2.7 KiB
TypeScript
/**
|
|
* 检查用户是否已购买指定章节/全书
|
|
* 用于支付前校验,避免重复购买
|
|
*
|
|
* GET /api/user/check-purchased?userId=xxx&type=section&productId=xxx
|
|
*/
|
|
|
|
import { NextRequest, NextResponse } from 'next/server'
|
|
import { query } from '@/lib/db'
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const { searchParams } = new URL(request.url)
|
|
const userId = searchParams.get('userId')
|
|
const type = searchParams.get('type') // 'section' | 'fullbook'
|
|
const productId = searchParams.get('productId')
|
|
|
|
if (!userId) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: '缺少 userId 参数'
|
|
}, { status: 400 })
|
|
}
|
|
|
|
// 1. 查询用户是否购买全书
|
|
const userRows = await query(`
|
|
SELECT has_full_book FROM users WHERE id = ?
|
|
`, [userId]) as any[]
|
|
|
|
if (userRows.length === 0) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: '用户不存在'
|
|
}, { status: 404 })
|
|
}
|
|
|
|
const hasFullBook = userRows[0].has_full_book || false
|
|
|
|
// 如果已购全书,直接返回已购买
|
|
if (hasFullBook) {
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
isPurchased: true,
|
|
reason: 'has_full_book'
|
|
}
|
|
})
|
|
}
|
|
|
|
// 2. 如果是购买全书,检查是否已有全书订单
|
|
if (type === 'fullbook') {
|
|
const orderRows = await query(`
|
|
SELECT COUNT(*) as count
|
|
FROM orders
|
|
WHERE user_id = ?
|
|
AND product_type = 'fullbook'
|
|
AND status = 'paid'
|
|
`, [userId]) as any[]
|
|
|
|
const hasPaid = orderRows[0].count > 0
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
isPurchased: hasPaid,
|
|
reason: hasPaid ? 'fullbook_order_exists' : null
|
|
}
|
|
})
|
|
}
|
|
|
|
// 3. 如果是购买章节,检查是否已有该章节订单
|
|
if (type === 'section' && productId) {
|
|
const orderRows = await query(`
|
|
SELECT COUNT(*) as count
|
|
FROM orders
|
|
WHERE user_id = ?
|
|
AND product_type = 'section'
|
|
AND product_id = ?
|
|
AND status = 'paid'
|
|
`, [userId, productId]) as any[]
|
|
|
|
const hasPaid = orderRows[0].count > 0
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
isPurchased: hasPaid,
|
|
reason: hasPaid ? 'section_order_exists' : null
|
|
}
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
isPurchased: false,
|
|
reason: null
|
|
}
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('[CheckPurchased] 查询失败:', error)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: '查询购买状态失败'
|
|
}, { status: 500 })
|
|
}
|
|
}
|