const API = require("../../lib/API.js") const db = require("../../plugin/DataBase/db.js") const Redis = require('../../plugin/DataBase/Redis') const { BaseStdResponse } = require("../../BaseStdResponse.js") const AccessControl = require("../../lib/AccessControl.js") const crypto = require('crypto') const config = require('../../config.json') const { validateCoupon, recordUsage, roundMoney } = require('../../lib/CouponService') const { normalizePayBaseUrl } = require('../../lib/PaymentClient') const { enqueueOrderPaymentCheck } = require('../../plugin/mq/orderPaymentWorker') function generateOrderId() { const now = new Date() const pad = (n, w = 2) => n.toString().padStart(w, '0') return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}` + `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}` + `${pad(now.getMilliseconds(), 3)}` } function generatePaymentSign(params, key) { const sorted = Object.keys(params).sort() const query = sorted.map(k => `${k}=${params[k]}`).join('&') + key return crypto.createHash('md5').update(query, 'utf8').digest('hex') } async function acquireCouponUsageLock(couponId) { const lockKey = `coupon:usage:${couponId}` const rows = await db.query('SELECT GET_LOCK(?, 5) AS ok', [lockKey]) return { lockKey, ok: Number(rows?.[0]?.ok || 0) === 1 } } async function releaseCouponUsageLock(lockKey) { if (!lockKey) return try { await db.query('SELECT RELEASE_LOCK(?)', [lockKey]) } catch (e) { // 释放失败仅记录,不影响主流程 } } class CreateOrder extends API { constructor() { super() this.setPath('/Order/CreateOrder') this.setMethod('POST') } async onRequest(req, res) { const { uuid, session, goods_id, pay_type, coupon_code } = req.body if ([uuid, session, goods_id, pay_type].some(v => v === '' || v === null || v === undefined)) { return res.json({ ...BaseStdResponse.MISSING_PARAMETER }) } const sessionValid = await AccessControl.checkSession(uuid, session) if (!sessionValid) { return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED }) } let couponLockKey = null try { const goodsSql = 'SELECT name, price, num, state FROM goods WHERE id = ?' const goodsRows = await db.query(goodsSql, [goods_id]) if (!goodsRows || goodsRows.length !== 1) { return res.json({ ...BaseStdResponse.ERR, msg: '商品不存在' }) } const goods = goodsRows[0] if (goods.num < 1 || goods.state !== 1) { return res.json({ ...BaseStdResponse.ERR, msg: '商品已下架或库存不足' }) } const createTime = Date.now() const orderId = generateOrderId() const originalPrice = roundMoney(goods.price) let finalPrice = originalPrice let discountAmount = 0 let couponId = null let appliedCouponCode = null if (coupon_code && String(coupon_code).trim()) { let couponResult = await validateCoupon({ code: coupon_code, userUuid: uuid, goodsId: goods_id, goodsPrice: goods.price }) if (!couponResult.ok) { return res.json({ ...BaseStdResponse.ERR, msg: couponResult.msg }) } finalPrice = couponResult.finalPrice discountAmount = couponResult.discountAmount couponId = couponResult.couponId appliedCouponCode = couponResult.code const lockRet = await acquireCouponUsageLock(couponId) if (!lockRet.ok) { return res.json({ ...BaseStdResponse.ERR, msg: '优惠码校验繁忙,请稍后重试' }) } couponLockKey = lockRet.lockKey couponResult = await validateCoupon({ code: coupon_code, userUuid: uuid, goodsId: goods_id, goodsPrice: goods.price }) if (!couponResult.ok) { return res.json({ ...BaseStdResponse.ERR, msg: couponResult.msg }) } finalPrice = couponResult.finalPrice discountAmount = couponResult.discountAmount couponId = couponResult.couponId appliedCouponCode = couponResult.code } const insertSql = ` INSERT INTO orders ( orderId, create_user, create_time, goods_id, price, pay_type, original_price, discount_amount, coupon_id, coupon_code ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ` const result = await db.query(insertSql, [ orderId, uuid, createTime, goods_id, finalPrice, pay_type, originalPrice, discountAmount, couponId, appliedCouponCode ]) const updateSql = 'UPDATE goods SET num = num - 1 WHERE id = ?' await db.query(updateSql, [goods_id]) if (result && result.affectedRows > 0) { if (couponId) { await recordUsage(couponId, orderId, uuid, discountAmount) } const paymentConfig = config.pay || {} if (!paymentConfig.pid || !paymentConfig.url || !paymentConfig.key || !paymentConfig.return_url) { return res.json({ ...BaseStdResponse.ERR, msg: '支付配置错误,请联系管理员' }) } const payBaseUrl = normalizePayBaseUrl(paymentConfig.url) const deviceType = req.headers['device-type'] ?? '浏览器' let return_url if (deviceType === 'RunForge Uniapp Client') return_url = paymentConfig.uni_return_url + orderId else return_url = paymentConfig.return_url + orderId const payParams = { pid: paymentConfig.pid, type: pay_type, out_trade_no: orderId, notify_url: `${config.url}/Order/CallBack`, return_url, name: goods.name, money: String(finalPrice) } const sign = generatePaymentSign(payParams, paymentConfig.key) payParams.sign = sign payParams.sign_type = 'MD5' await Redis.set(`payData:${orderId}`, JSON.stringify(payParams), { EX: 300 }) try { await enqueueOrderPaymentCheck(orderId) } catch (error) { this.logger.error(`推送订单支付检查消息到 MQ 失败,订单号:${orderId},错误:${error.stack || error}`) } res.json({ ...BaseStdResponse.OK, id: orderId, pay: { payUrl: `${payBaseUrl}/submit.php`, payData: payParams } }) } else { return res.json({ ...BaseStdResponse.ERR, msg: '创建订单失败' }) } } catch (err) { this.logger.error(`创建订单失败!${err.stack}`) return res.json({ ...BaseStdResponse.ERR, msg: "创建订单异常,请联系管理员" }) } finally { await releaseCouponUsageLock(couponLockKey) } } } module.exports.CreateOrder = CreateOrder