PaymentClient.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. const axios = require('axios')
  2. const config = require('../config.json')
  3. function getPaymentConfig() {
  4. return config.pay || {}
  5. }
  6. function normalizePayBaseUrl(url) {
  7. return String(url || '').trim().replace(/\/+$/, '')
  8. }
  9. function buildPaymentApiUrl(act, params = {}) {
  10. const paymentConfig = getPaymentConfig()
  11. const baseUrl = normalizePayBaseUrl(paymentConfig.url)
  12. if (!baseUrl) {
  13. throw new Error('支付配置错误')
  14. }
  15. const url = new URL(`${baseUrl}/api.php`)
  16. url.searchParams.set('act', act)
  17. for (const [key, value] of Object.entries(params)) {
  18. if (value === undefined || value === null || value === '') continue
  19. url.searchParams.set(key, String(value))
  20. }
  21. return url.toString()
  22. }
  23. function parsePaymentResponseBody(data) {
  24. if (data && typeof data === 'object') return data
  25. if (typeof data !== 'string') return null
  26. const text = data.trim()
  27. if (!text) return null
  28. try {
  29. return JSON.parse(text)
  30. } catch (_) {
  31. return null
  32. }
  33. }
  34. function getAxiosPaymentOptions(extra = {}) {
  35. return {
  36. timeout: 15000,
  37. maxRedirects: 5,
  38. proxy: false,
  39. validateStatus: (status) => status >= 200 && status < 500,
  40. ...extra
  41. }
  42. }
  43. function formatPaymentHttpError(error, fallbackMessage) {
  44. if (error?.code === 'ECONNABORTED') {
  45. return '支付平台响应超时,请稍后重试'
  46. }
  47. if (error?.code === 'ERR_FR_TOO_MANY_REDIRECTS') {
  48. return '支付平台重定向异常,请检查 pay.url 配置或关闭系统代理后重试'
  49. }
  50. const status = Number(error?.response?.status || 0)
  51. const parsed = parsePaymentResponseBody(error?.response?.data)
  52. if (parsed?.msg) return String(parsed.msg)
  53. if (status === 503) return '支付平台暂时不可用,请稍后重试'
  54. if (status >= 500) return `支付平台异常(${status}),请稍后重试`
  55. return fallbackMessage || error?.message || '支付平台请求失败'
  56. }
  57. async function queryPaymentOrder(orderId, logger) {
  58. const paymentConfig = getPaymentConfig()
  59. if (!paymentConfig.pid || !paymentConfig.url || !paymentConfig.key) {
  60. throw new Error('支付配置错误')
  61. }
  62. const queryUrl = buildPaymentApiUrl('order', {
  63. pid: paymentConfig.pid,
  64. key: paymentConfig.key,
  65. out_trade_no: orderId
  66. })
  67. let response
  68. try {
  69. response = await axios.get(queryUrl, getAxiosPaymentOptions())
  70. } catch (error) {
  71. const message = formatPaymentHttpError(error, '查询支付状态失败')
  72. logger?.warn?.(`查询支付状态失败,订单号:${orderId},URL:${queryUrl},原因:${message}`)
  73. throw new Error(message)
  74. }
  75. const result = parsePaymentResponseBody(response.data)
  76. if (!result) {
  77. logger?.warn?.(`支付平台返回非 JSON,订单号:${orderId},HTTP ${response.status}`)
  78. throw new Error('支付平台响应异常')
  79. }
  80. return result
  81. }
  82. function formatPaymentRefundError(response, fallbackMessage) {
  83. return formatPaymentHttpError({ response }, fallbackMessage || '支付平台退款失败')
  84. }
  85. function isRefundResponseSuccess(result) {
  86. if (!result || typeof result !== 'object') return false
  87. const code = Number(result.code)
  88. // 标准易支付:code=1;部分平台(如 yaolipay):code=0 且带 refund_no
  89. if (code === 1) return true
  90. if (code === 0 && result.refund_no) return true
  91. return false
  92. }
  93. async function requestPaymentRefund({ orderId, tradeNo, money, logger }) {
  94. const paymentConfig = getPaymentConfig()
  95. if (!paymentConfig.url || !paymentConfig.pid || !paymentConfig.key) {
  96. throw new Error('支付配置错误')
  97. }
  98. const refundUrl = buildPaymentApiUrl('refund')
  99. const params = new URLSearchParams()
  100. params.append('pid', String(paymentConfig.pid))
  101. params.append('key', paymentConfig.key)
  102. if (tradeNo) {
  103. params.append('trade_no', tradeNo)
  104. } else {
  105. params.append('out_trade_no', orderId)
  106. }
  107. params.append('money', String(money))
  108. let response
  109. try {
  110. response = await axios.post(
  111. refundUrl,
  112. params.toString(),
  113. getAxiosPaymentOptions({
  114. timeout: 30000,
  115. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  116. validateStatus: () => true
  117. })
  118. )
  119. } catch (error) {
  120. logger?.error?.(`易支付退款请求失败 订单号:${orderId}:${error.stack || error}`)
  121. throw new Error(formatPaymentHttpError(error, '无法连接支付平台,请稍后重试'))
  122. }
  123. const result = parsePaymentResponseBody(response.data)
  124. logger?.info?.(`易支付退款响应 订单号:${orderId},HTTP ${response.status},结果:${JSON.stringify(result ?? response.data)}`)
  125. if (response.status >= 400) {
  126. throw new Error(formatPaymentRefundError(response, '支付平台退款失败'))
  127. }
  128. if (!isRefundResponseSuccess(result)) {
  129. throw new Error(result?.msg || '支付平台退款失败')
  130. }
  131. return result
  132. }
  133. module.exports = {
  134. normalizePayBaseUrl,
  135. buildPaymentApiUrl,
  136. getAxiosPaymentOptions,
  137. formatPaymentHttpError,
  138. formatPaymentRefundError,
  139. parsePaymentResponseBody,
  140. isRefundResponseSuccess,
  141. queryPaymentOrder,
  142. requestPaymentRefund
  143. }