This commit is contained in:
乘风
2026-02-05 11:35:57 +08:00
parent 8c2a6391af
commit b96acadf91
31 changed files with 2263 additions and 4933 deletions

View File

@@ -122,7 +122,31 @@ export async function POST(request: Request) {
}
}
const { productType, productId, userId } = attach
const { productType, productId, userId: attachUserId } = attach
// 买家身份必须以微信 openId 为准(不可伪造),避免客户端伪造 userId 导致错误归属/分佣
let buyerUserId: string | undefined = attachUserId
if (openId) {
try {
const usersByOpenId = await query('SELECT id FROM users WHERE open_id = ?', [openId]) as any[]
if (usersByOpenId.length > 0) {
const resolvedId = usersByOpenId[0].id
if (attachUserId && resolvedId !== attachUserId) {
console.warn('[PayNotify] 买家身份校验: attach.userId 与 openId 解析不一致,以 openId 为准', {
attachUserId,
resolvedId,
orderSn,
})
}
buyerUserId = resolvedId
}
} catch (e) {
console.error('[PayNotify] 按 openId 解析买家失败:', e)
}
}
if (!buyerUserId && attachUserId) {
buyerUserId = attachUserId
}
// 1. 更新订单状态为已支付
let orderExists = false
@@ -143,33 +167,55 @@ export async function POST(request: Request) {
INSERT INTO orders (
id, order_sn, user_id, open_id,
product_type, product_id, amount, description,
status, transaction_id, pay_time, referrer_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'paid', ?, CURRENT_TIMESTAMP, NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
status, transaction_id, pay_time, referrer_id, referral_code, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'paid', ?, CURRENT_TIMESTAMP, NULL, NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
`, [
orderSn, orderSn, userId || openId, openId,
orderSn, orderSn, buyerUserId || openId, openId,
productType || 'unknown', productId || '', totalAmount,
'支付回调补记订单', transactionId
])
console.log('[PayNotify] ✅ 订单补记成功:', orderSn)
orderExists = true
} catch (insertErr: any) {
if (insertErr?.message?.includes('referrer_id') || insertErr?.code === 'ER_BAD_FIELD_ERROR') {
const msg = insertErr?.message || ''
const code = insertErr?.code || ''
if (msg.includes('referrer_id') || msg.includes('referral_code') || code === 'ER_BAD_FIELD_ERROR') {
try {
await query(`
INSERT INTO orders (
id, order_sn, user_id, open_id,
product_type, product_id, amount, description,
status, transaction_id, pay_time, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'paid', ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
status, transaction_id, pay_time, referrer_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'paid', ?, CURRENT_TIMESTAMP, NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
`, [
orderSn, orderSn, userId || openId, openId,
orderSn, orderSn, buyerUserId || openId, openId,
productType || 'unknown', productId || '', totalAmount,
'支付回调补记订单', transactionId
])
console.log('[PayNotify] ✅ 订单补记成功(无 referrer_id):', orderSn)
console.log('[PayNotify] ✅ 订单补记成功(无 referral_code):', orderSn)
orderExists = true
} catch (e2) {
console.error('[PayNotify] ❌ 补记订单失败:', e2)
} catch (e2: any) {
if (e2?.message?.includes('referrer_id') || e2?.code === 'ER_BAD_FIELD_ERROR') {
try {
await query(`
INSERT INTO orders (
id, order_sn, user_id, open_id,
product_type, product_id, amount, description,
status, transaction_id, pay_time, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'paid', ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
`, [
orderSn, orderSn, buyerUserId || openId, openId,
productType || 'unknown', productId || '', totalAmount,
'支付回调补记订单', transactionId
])
console.log('[PayNotify] ✅ 订单补记成功(无 referrer_id/referral_code):', orderSn)
orderExists = true
} catch (e3) {
console.error('[PayNotify] ❌ 补记订单失败:', e3)
}
} else {
console.error('[PayNotify] ❌ 补记订单失败:', e2)
}
}
} else {
console.error('[PayNotify] ❌ 补记订单失败:', insertErr)
@@ -199,20 +245,7 @@ export async function POST(request: Request) {
console.error('[PayNotify] ❌ 处理订单失败:', e)
}
// 2. 获取用户信息
let buyerUserId = userId
if (!buyerUserId && openId) {
try {
const users = await query('SELECT id FROM users WHERE open_id = ?', [openId]) as any[]
if (users.length > 0) {
buyerUserId = users[0].id
}
} catch (e) {
console.error('[PayNotify] 获取用户信息失败:', e)
}
}
// 3. 更新用户购买记录(✅ 检查是否已有其他相同产品的已支付订单)
// 2. 更新用户购买记录buyerUserId 已在上面以 openId 为准解析)(✅ 检查是否已有其他相同产品的已支付订单)
if (buyerUserId && productType) {
try {
if (productType === 'fullbook') {
@@ -256,7 +289,7 @@ export async function POST(request: Request) {
console.error('[PayNotify] ❌ 更新用户购买记录失败:', e)
}
// 4. 清理相同产品的无效订单(未支付的订单)
// 3. 清理相同产品的无效订单(未支付的订单)
if (productType && (productType === 'fullbook' || productId)) {
try {
const deleteResult = await query(`
@@ -288,7 +321,7 @@ export async function POST(request: Request) {
}
}
// 5. 处理分销佣金90%给推广者)
// 4. 处理分销佣金90%给推广者)
await processReferralCommission(buyerUserId, totalAmount, orderSn)
}

View File

@@ -166,6 +166,17 @@ export async function POST(request: Request) {
} catch (e) {
console.warn('[MiniPay] 查询推荐人失败,继续创建订单:', e)
}
// 下单时使用的邀请码:优先用请求体,否则用推荐人当前邀请码(便于订单记录对账)
let orderReferralCode: string | null = body.referralCode ? String(body.referralCode).trim() || null : null
if (!orderReferralCode && referrerId) {
try {
const refRows = (await query(`SELECT referral_code FROM users WHERE id = ? LIMIT 1`, [referrerId]) as any[])
if (refRows.length > 0 && refRows[0].referral_code) {
orderReferralCode = refRows[0].referral_code
}
} catch (_) { /* 忽略 */ }
}
try {
// 检查是否已有相同产品的已支付订单
@@ -186,34 +197,55 @@ export async function POST(request: Request) {
})
}
// 插入订单(含 referrer_id便于分销归属与统计
// 插入订单(含 referrer_id、referral_code,便于分销归属与对账
try {
await query(`
INSERT INTO orders (
id, order_sn, user_id, open_id,
product_type, product_id, amount, description,
status, transaction_id, referrer_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
status, transaction_id, referrer_id, referral_code, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
`, [
orderSn, orderSn, userId, openId,
productType, productId || 'fullbook', amount, goodsBody,
'created', null, referrerId
'created', null, referrerId, orderReferralCode
])
} catch (insertErr: any) {
// 兼容:若表尚无 referrer_id 列,则用不含该字段的 INSERT
if (insertErr?.message?.includes('referrer_id') || insertErr?.code === 'ER_BAD_FIELD_ERROR') {
await query(`
INSERT INTO orders (
id, order_sn, user_id, open_id,
product_type, product_id, amount, description,
status, transaction_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
`, [
orderSn, orderSn, userId, openId,
productType, productId || 'fullbook', amount, goodsBody,
'created', null
])
console.log('[MiniPay] 订单已插入(未含 referrer_id请执行 scripts/add_orders_referrer_id.py)')
// 兼容:若表尚无 referrer_id 或 referral_code 列
const msg = (insertErr as any)?.message || ''
const code = (insertErr as any)?.code || ''
if (msg.includes('referrer_id') || msg.includes('referral_code') || code === 'ER_BAD_FIELD_ERROR') {
try {
await query(`
INSERT INTO orders (
id, order_sn, user_id, open_id,
product_type, product_id, amount, description,
status, transaction_id, referrer_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
`, [
orderSn, orderSn, userId, openId,
productType, productId || 'fullbook', amount, goodsBody,
'created', null, referrerId
])
console.log('[MiniPay] 订单已插入(未含 referral_code请执行 scripts/add_orders_referral_code.py)')
} catch (e2: any) {
if (e2?.message?.includes('referrer_id') || e2?.code === 'ER_BAD_FIELD_ERROR') {
await query(`
INSERT INTO orders (
id, order_sn, user_id, open_id,
product_type, product_id, amount, description,
status, transaction_id, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
`, [
orderSn, orderSn, userId, openId,
productType, productId || 'fullbook', amount, goodsBody,
'created', null
])
console.log('[MiniPay] 订单已插入(未含 referrer_id/referral_code请执行迁移脚本)')
} else {
throw e2
}
}
} else {
throw insertErr
}

View File

@@ -22,6 +22,8 @@ function rowToOrder(row: Record<string, unknown>) {
status: row.status,
transactionId: row.transaction_id,
payTime: row.pay_time,
referrerId: row.referrer_id ?? null,
referralCode: row.referral_code ?? null,
createdAt: row.created_at,
updatedAt: row.updated_at,
}