CreateOrder.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. const API = require("../../lib/API.js")
  2. const db = require("../../plugin/DataBase/db.js")
  3. const Redis = require('../../plugin/DataBase/Redis')
  4. const { BaseStdResponse } = require("../../BaseStdResponse.js")
  5. const AccessControl = require("../../lib/AccessControl.js")
  6. const crypto = require('crypto')
  7. const axios = require('axios')
  8. const config = require('../../config.json')
  9. function generateOrderId() {
  10. const now = new Date()
  11. const pad = (n, w = 2) => n.toString().padStart(w, '0')
  12. return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}` +
  13. `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}` +
  14. `${pad(now.getMilliseconds(), 3)}`
  15. }
  16. function generatePaymentSign(params, key) {
  17. const sorted = Object.keys(params).sort()
  18. const query = sorted.map(k => `${k}=${params[k]}`).join('&') + key
  19. return crypto.createHash('md5').update(query, 'utf8').digest('hex')
  20. }
  21. // async function getPayStatus(order_no) {
  22. // const endpoint = config.pay.url + '/api/findorder'
  23. // try {
  24. // const res = await axios.post(endpoint, {order_no, type: 1})
  25. // } catch (error) {
  26. // }
  27. // }
  28. class CreateOrder extends API {
  29. constructor() {
  30. super()
  31. this.setPath('/Order/CreateOrder')
  32. this.setMethod('POST')
  33. }
  34. async onRequest(req, res) {
  35. const { uuid, session, goods_id, pay_type } = req.body
  36. if ([uuid, session, goods_id, pay_type].some(v => v === '' || v === null || v === undefined)) {
  37. return res.json({
  38. ...BaseStdResponse.MISSING_PARAMETER,
  39. endpoint: 1513126
  40. })
  41. }
  42. const sessionValid = await AccessControl.checkSession(uuid, session)
  43. if (!sessionValid) {
  44. return res.status(401).json({
  45. ...BaseStdResponse.ACCESS_DENIED
  46. })
  47. }
  48. try {
  49. const goodsSql = 'SELECT name, price, num, state FROM goods WHERE id = ?'
  50. const goodsRows = await db.query(goodsSql, [goods_id])
  51. if (!goodsRows || goodsRows.length !== 1) {
  52. return res.json({
  53. ...BaseStdResponse.ERR,
  54. msg: '商品不存在',
  55. endpoint: 1513126
  56. })
  57. }
  58. const goods = goodsRows[0]
  59. if (goods.num < 1 || goods.state !== 1) {
  60. return res.json({
  61. ...BaseStdResponse.ERR,
  62. msg: '商品已下架或库存不足',
  63. endpoint: 1513126
  64. })
  65. }
  66. const createTime = Date.now()
  67. const orderId = generateOrderId()
  68. const insertSql = `
  69. INSERT INTO orders (orderId, create_user, create_time, goods_id, price, pay_type)
  70. VALUES (?, ?, ?, ?, ?, ?)
  71. `
  72. const result = await db.query(insertSql, [
  73. orderId, uuid, createTime, goods_id, goods.price, pay_type
  74. ])
  75. const updateSql = 'UPDATE goods SET num = num - 1 WHERE id = ?'
  76. await db.query(updateSql, [goods_id])
  77. if (result && result.affectedRows > 0) {
  78. const paymentConfig = config.pay || {}
  79. if (!paymentConfig.pid || !paymentConfig.url || !paymentConfig.key || !paymentConfig.return_url) {
  80. return res.json({
  81. ...BaseStdResponse.ERR,
  82. msg: '支付配置错误,请联系管理员'
  83. })
  84. }
  85. let notify_url = config.url + '/Order/CallBack'
  86. const payParams = {
  87. pid: paymentConfig.pid,
  88. type: pay_type,
  89. out_trade_no: orderId,
  90. notify_url,
  91. return_url: paymentConfig.return_url + orderId,
  92. name: goods.name,
  93. money: goods.price
  94. }
  95. const sign = generatePaymentSign(payParams, paymentConfig.key)
  96. payParams.sign = sign
  97. payParams.sign_type = 'MD5'
  98. await Redis.set(`payData:${orderId}`, JSON.stringify(payParams), {
  99. EX: 300
  100. })
  101. let payUrl = paymentConfig.url + '/submit.php'
  102. return res.json({
  103. ...BaseStdResponse.OK,
  104. id: orderId,
  105. pay: {
  106. payUrl,
  107. payData: payParams
  108. }
  109. })
  110. // 定时器轮询订单状态
  111. } else {
  112. return res.json({
  113. ...BaseStdResponse.ERR,
  114. msg: '创建订单失败',
  115. endpoint: 7894378
  116. })
  117. }
  118. } catch (err) {
  119. this.logger.error(`创建订单失败!${err.stack}`)
  120. return res.json({
  121. ...BaseStdResponse.ERR,
  122. msg: "创建订单异常,请联系管理员"
  123. })
  124. }
  125. }
  126. }
  127. module.exports.CreateOrder = CreateOrder