useRecharge.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { computed } from 'vue'
  2. import { storeToRefs } from 'pinia'
  3. import { useWalletRechargeStore } from '~/stores/walletRecharge'
  4. import { walletApi } from '~/api/wallet'
  5. import { useAuth } from './useAuth'
  6. import { useTopupPopup } from './useTopupPopup'
  7. import { formatNumber } from '~/utils/helpers'
  8. // 充值流程组合式函数
  9. // - 从后端加载充值配置并缓存在 Pinia
  10. // - 把后端字段映射到 Topup 弹窗所需的档位结构
  11. // - 统一通过 useTopupPopup 打开充值弹窗
  12. export const useRecharge = () => {
  13. const walletRechargeStore = useWalletRechargeStore()
  14. const { items, loading } = storeToRefs(walletRechargeStore)
  15. const { wallet } = useAuth()
  16. const { open: openTopupPopup } = useTopupPopup()
  17. const hasConfig = computed(() => items.value.length > 0)
  18. const ensureConfig = async (force = false) => {
  19. if (!force && walletRechargeStore.initialized && items.value.length > 0)
  20. return
  21. await walletRechargeStore.loadConfig(force)
  22. }
  23. /**
  24. * 提交充值并打开收银台页面
  25. * - 将选中的 package.id 传给后端
  26. * - 使用返回的 result 字符串作为收银台链接新开页面
  27. */
  28. const submitRecharge = async (packageId: string | number, redirect?: string) => {
  29. const id = String(packageId)
  30. try {
  31. const res = await walletApi.submitRecharge(id, redirect || '')
  32. const url = res?.result
  33. if (!url) {
  34. console.error('Recharge submit response has no result url')
  35. return
  36. }
  37. if (import.meta.client) {
  38. window.location.href = url
  39. }
  40. }
  41. catch (error) {
  42. console.error('Failed to submit wallet recharge:', error)
  43. }
  44. }
  45. /**
  46. * 打开充值弹窗:
  47. * - 确保已经加载充值配置
  48. * - 按照 Topup 弹窗要求的结构构建档位数据
  49. */
  50. const openRecharge = async () => {
  51. await ensureConfig()
  52. const configItems = items.value
  53. if (!configItems || configItems.length === 0) {
  54. console.warn('Wallet recharge config is empty')
  55. return
  56. }
  57. const balance = wallet.value?.goldCoin ?? 0
  58. const packages = configItems.map(item => ({
  59. id: item.id,
  60. coins: item.coinRechargeAmount,
  61. priceLabel: formatNumber(item.amount),
  62. }))
  63. // 支付方式目前前端写死;如果后端后续下发支付方式,可以从接口映射
  64. const methods = [
  65. { id: 'dukpay', name: 'DukPay', icon: '/vendor/dukpay-logo.png' },
  66. ]
  67. openTopupPopup({
  68. balance,
  69. packages,
  70. methods,
  71. defaultPackageId: packages[0]?.id,
  72. defaultMethodId: methods[0]?.id,
  73. })
  74. }
  75. return {
  76. // state
  77. loading,
  78. items,
  79. hasConfig,
  80. // actions
  81. ensureConfig,
  82. openRecharge,
  83. submitRecharge,
  84. }
  85. }