useRecharge.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import { computed, onBeforeUnmount } from 'vue'
  2. import { storeToRefs } from 'pinia'
  3. import { closeToast, showLoadingToast } from 'vant'
  4. import { useWalletRechargeStore } from '~/stores/walletRecharge'
  5. import { walletApi } from '~/api/wallet'
  6. import { useAuth } from './useAuth'
  7. import { useTopupPopup } from './useTopupPopup'
  8. import { formatNumber } from '~/utils/helpers'
  9. // 充值流程组合式函数
  10. // - 从后端加载充值配置并缓存在 Pinia
  11. // - 把后端字段映射到 Topup 弹窗所需的档位结构
  12. // - 统一通过 useTopupPopup 打开充值弹窗
  13. export const useRecharge = () => {
  14. const walletRechargeStore = useWalletRechargeStore()
  15. const { items, loading } = storeToRefs(walletRechargeStore)
  16. const route = useRoute()
  17. const router = useRouter()
  18. const { t } = useI18n()
  19. const { wallet, refreshUser } = useAuth()
  20. const { open: openTopupPopup } = useTopupPopup()
  21. const { handleTopupOpen: handlePaybackResultTopupOpen } = usePaybackResultPopup()
  22. const hasConfig = computed(() => items.value.length > 0)
  23. let topupPollTimer: ReturnType<typeof setInterval> | null = null
  24. const stopTopupPolling = () => {
  25. if (topupPollTimer) {
  26. clearInterval(topupPollTimer)
  27. topupPollTimer = null
  28. }
  29. }
  30. onBeforeUnmount(() => {
  31. stopTopupPolling()
  32. })
  33. const ensureConfig = async (force = false) => {
  34. if (!force && walletRechargeStore.initialized && items.value.length > 0)
  35. return
  36. await walletRechargeStore.loadConfig(force)
  37. }
  38. /**
  39. * 提交充值并打开收银台页面
  40. * - 将选中的 package.id 传给后端
  41. * - 使用返回的 result 字符串作为收银台链接新开页面
  42. */
  43. const submitRecharge = async (packageId: string | number, redirect?: string) => {
  44. const id = String(packageId)
  45. try {
  46. const res = await walletApi.submitRecharge(id, redirect || '')
  47. const url = res?.result
  48. if (!url) {
  49. console.error('Recharge submit response has no result url')
  50. return
  51. }
  52. if (import.meta.client) {
  53. window.location.href = url
  54. }
  55. }
  56. catch (error) {
  57. console.error('Failed to submit wallet recharge:', error)
  58. }
  59. }
  60. /**
  61. * 打开充值弹窗:
  62. * - 确保已经加载充值配置
  63. * - 按照 Topup 弹窗要求的结构构建档位数据
  64. */
  65. const openRecharge = async () => {
  66. await ensureConfig()
  67. const configItems = items.value
  68. if (!configItems || configItems.length === 0) {
  69. console.warn('Wallet recharge config is empty')
  70. return
  71. }
  72. const balance = wallet.value?.goldCoin ?? 0
  73. const packages = configItems.map(item => ({
  74. id: item.id,
  75. coins: item.coinRechargeAmount,
  76. priceLabel: formatNumber(item.amount),
  77. }))
  78. // 支付方式目前前端写死;如果后端后续下发支付方式,可以从接口映射
  79. const methods = [
  80. { id: 'dukpay', name: 'DukPay', icon: '/vendor/dukpay-logo.png' },
  81. ]
  82. openTopupPopup({
  83. balance,
  84. packages,
  85. methods,
  86. defaultPackageId: packages[0]?.id,
  87. defaultMethodId: methods[0]?.id,
  88. })
  89. }
  90. const normalizeCreateTime = (value: number) => {
  91. // Backend docs say int64 timestamp; some envs may return seconds.
  92. if (!value) return 0
  93. return value < 1e12 ? value * 1000 : value
  94. }
  95. const finalizeTopupResult = (success: boolean, coins: number) => {
  96. stopTopupPolling()
  97. closeToast()
  98. handlePaybackResultTopupOpen({
  99. status: success,
  100. coins,
  101. })
  102. refreshUser()
  103. }
  104. const startTopupPolling = async (orderNo: string, coins: number) => {
  105. stopTopupPolling()
  106. let finished = false
  107. let inFlight = false
  108. const requestOnce = async () => {
  109. try {
  110. return await walletApi.checkRechargeOrderState(orderNo)
  111. }
  112. catch (error) {
  113. console.error('Failed to check recharge order state:', error)
  114. return null
  115. }
  116. }
  117. const first = await requestOnce()
  118. if (!first) return
  119. if (first.status === 2) {
  120. finalizeTopupResult(true, coins)
  121. return
  122. }
  123. if (first.status === 0 || first.status === 3 || first.status === 4) {
  124. finalizeTopupResult(false, coins)
  125. return
  126. }
  127. // status === 1 => start polling
  128. const createTime = normalizeCreateTime(first.createTime)
  129. const deadline = (createTime || Date.now()) + 30 * 1000
  130. const tick = async () => {
  131. if (finished || inFlight) return
  132. inFlight = true
  133. try {
  134. if (Date.now() >= deadline) {
  135. finished = true
  136. finalizeTopupResult(false, coins)
  137. return
  138. }
  139. const res = await requestOnce()
  140. if (!res) return
  141. if (res.status === 2) {
  142. finished = true
  143. finalizeTopupResult(true, coins)
  144. }
  145. else if (res.status === 0 || res.status === 3 || res.status === 4) {
  146. finished = true
  147. finalizeTopupResult(false, coins)
  148. }
  149. }
  150. finally {
  151. inFlight = false
  152. }
  153. }
  154. // Poll every 1 seconds for up to 30 seconds from createTime.
  155. topupPollTimer = setInterval(() => {
  156. void tick()
  157. }, 1 * 1000)
  158. }
  159. const handleTopupResult = (rechargeData: string) => {
  160. try {
  161. const rechargeStr = window.atob(rechargeData)
  162. const rechargeJson = JSON.parse(rechargeStr)
  163. const query = { ...route.query }
  164. delete query.rechargeCallback
  165. router.replace({
  166. path: route.path,
  167. query,
  168. })
  169. if (rechargeJson.loopState && rechargeJson.orderNo) {
  170. const orderNo = rechargeJson.orderNo
  171. const coins = rechargeJson.coinRechargeAmount || 0
  172. showLoadingToast({
  173. message: t('payback.titles.topupPending'),
  174. duration: 30 * 1000,
  175. forbidClick: true,
  176. })
  177. void startTopupPolling(orderNo, coins)
  178. }
  179. else {
  180. handlePaybackResultTopupOpen({
  181. status: rechargeJson.status,
  182. coins: rechargeJson.coinRechargeAmount || 0,
  183. })
  184. refreshUser()
  185. }
  186. }
  187. catch (error) {
  188. console.error('Failed to parse recharge data:', error)
  189. }
  190. }
  191. const handleRechargeCallback = () => {
  192. const rechargeCallback = route.query.rechargeCallback as string | undefined
  193. if (rechargeCallback) {
  194. handleTopupResult(rechargeCallback)
  195. }
  196. }
  197. return {
  198. // state
  199. loading,
  200. items,
  201. hasConfig,
  202. // actions
  203. ensureConfig,
  204. openRecharge,
  205. submitRecharge,
  206. handleRechargeCallback,
  207. }
  208. }