购买套餐里去充值桌面端和移动端支付流程封装
This commit is contained in:
@@ -16,7 +16,7 @@ import zod from 'zod'
|
||||
import {zodResolver} from '@hookform/resolvers/zod'
|
||||
import {Label} from '@/components/ui/label'
|
||||
import Page from '@/components/page'
|
||||
import {PaymentStatusCell} from '@/components/composites/payment'
|
||||
import {PaymentStatusCell} from './payment'
|
||||
|
||||
const filterSchema = zod.object({
|
||||
type: zod.enum(['all', '3', '1', '2']).default('all'),
|
||||
|
||||
114
src/components/composites/payment/desktop-payment.tsx
Normal file
114
src/components/composites/payment/desktop-payment.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
'use client'
|
||||
import {DialogContent, DialogHeader, DialogTitle} from '@/components/ui/dialog'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {completeResource} from '@/actions/resource'
|
||||
import {toast} from 'sonner'
|
||||
import {CheckCircle, Loader} from 'lucide-react'
|
||||
import {useState, useEffect, useRef} from 'react'
|
||||
import * as qrcode from 'qrcode'
|
||||
import Image from 'next/image'
|
||||
import wechat from '@/components/composites/purchase/_assets/wechat.svg'
|
||||
import alipay from '@/components/composites/purchase/_assets/alipay.svg'
|
||||
import {PaymentMethod} from './types'
|
||||
|
||||
interface Trade {
|
||||
inner_no: string
|
||||
method: number
|
||||
pay_url: string
|
||||
amount?: number
|
||||
status?: number
|
||||
}
|
||||
export function DesktopPayment({trade, onClose}: {trade: Trade, onClose: () => void}) {
|
||||
const [paymentVerified, setPaymentVerified] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
|
||||
const paymentInfo = {
|
||||
icon: trade.method === PaymentMethod.Alipay ? alipay : wechat,
|
||||
name: trade.method === PaymentMethod.Alipay ? '支付宝' : '微信支付',
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!canvasRef.current || trade.method === 1) return
|
||||
qrcode.toCanvas(canvasRef.current, trade.pay_url, {width: 200})
|
||||
.catch((err) => {
|
||||
console.error('生成二维码失败:', err)
|
||||
toast.error('生成支付二维码失败')
|
||||
})
|
||||
}, [trade.method, trade.pay_url])
|
||||
|
||||
const handleComplete = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const resp = await completeResource({trade_no: trade.inner_no})
|
||||
if (!resp.success) throw new Error(resp.message)
|
||||
toast.success('支付成功')
|
||||
setPaymentVerified(true)
|
||||
setTimeout(onClose, 2000)
|
||||
}
|
||||
catch (e) {
|
||||
toast.error('支付验证失败', {description: (e as Error).message})
|
||||
}
|
||||
finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex gap-2 items-center">
|
||||
<Image src={paymentInfo.icon} alt={paymentInfo.name} width={24} height={24}/>
|
||||
<span>{paymentInfo.name}</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{paymentVerified ? (
|
||||
<div className="text-center py-8">
|
||||
<CheckCircle className="mx-auto text-green-500 w-12 h-12"/>
|
||||
<p className="mt-4 text-lg font-medium">支付验证成功</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="bg-gray-100 w-52 h-52 flex items-center justify-center">
|
||||
{trade.method === 1 ? (
|
||||
<iframe src={trade.pay_url} className="w-full h-full"/>
|
||||
) : (
|
||||
<canvas ref={canvasRef} className="w-full h-full"/>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-600">
|
||||
请使用
|
||||
{paymentInfo.name}
|
||||
扫码支付
|
||||
</p>
|
||||
|
||||
<div className="w-full text-center space-y-2">
|
||||
<p className="text-sm font-medium">
|
||||
支付金额:
|
||||
{' '}
|
||||
<span className="text-accent">
|
||||
¥
|
||||
{trade.amount?.toFixed(2) || '0.00'}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
订单号:
|
||||
{trade.inner_no}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 w-full justify-center">
|
||||
<Button onClick={handleComplete} >
|
||||
{loading && <Loader className="animate-spin mr-2"/>}
|
||||
已完成支付
|
||||
</Button>
|
||||
<Button theme="outline" onClick={onClose}>
|
||||
关闭
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,24 @@
|
||||
// BillsPage负责数据获取和列表展示
|
||||
|
||||
// PaymentStatusCell负责支付状态显示和交互
|
||||
|
||||
// PaymentDialog负责支付过程处理
|
||||
// 导出支付相关组件
|
||||
export * from './payment-dialog'
|
||||
export * from './payment'
|
||||
export * from './payment-button'
|
||||
export * from './payment-modal'
|
||||
export * from './mobile-payment'
|
||||
export * from './desktop-payment'
|
||||
export type {Trade, PaymentResponse, PaymentMethod} from './types'
|
||||
|
||||
// components/
|
||||
// composites/
|
||||
// payment/
|
||||
// index.ts # 统一导出
|
||||
// payment-button.tsx # 支付按钮组件
|
||||
// payment-modal.tsx # 支付弹窗容器
|
||||
// mobile-payment.tsx # 移动端支付确认
|
||||
// desktop-payment.tsx # 桌面端支付确认
|
||||
// payment-status.tsx # 支付状态显示
|
||||
|
||||
// PaymentButton (点击)
|
||||
// ├─ 触发 onClick 创建订单
|
||||
// ├─ 成功后打开 PaymentModal
|
||||
// │ ├─ MobilePayment (移动端)
|
||||
// │ └─ DesktopPayment (桌面端)
|
||||
// └─ 支付成功 → onSuccess 回调
|
||||
// └─ 父组件执行后续逻辑
|
||||
|
||||
117
src/components/composites/payment/mobile-payment.tsx
Normal file
117
src/components/composites/payment/mobile-payment.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
'use client'
|
||||
import {DialogContent, DialogHeader, DialogTitle} from '@/components/ui/dialog'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {completeResource} from '@/actions/resource'
|
||||
import {toast} from 'sonner'
|
||||
import {CheckCircle, CreditCard} from 'lucide-react'
|
||||
import {useState} from 'react'
|
||||
import Image from 'next/image'
|
||||
import wechat from '@/components/composites/purchase/_assets/wechat.svg'
|
||||
import alipay from '@/components/composites/purchase/_assets/alipay.svg'
|
||||
import {Trade, PaymentMethod} from './types'
|
||||
|
||||
export function MobilePayment({
|
||||
trade,
|
||||
onClose,
|
||||
}: {
|
||||
trade: Trade
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [paymentVerified, setPaymentVerified] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const paymentInfo = (() => {
|
||||
switch (trade.method) {
|
||||
case PaymentMethod.Alipay:
|
||||
case PaymentMethod.SftAlipay:
|
||||
return {icon: alipay, name: '支付宝'}
|
||||
case PaymentMethod.WeChat:
|
||||
case PaymentMethod.SftWeChat:
|
||||
return {icon: wechat, name: '微信支付'}
|
||||
default:
|
||||
console.warn('Unknown payment method:', trade.method)
|
||||
return {icon: wechat, name: '微信支付'} // 默认返回微信支付
|
||||
}
|
||||
})()
|
||||
|
||||
const handleComplete = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const resp = await completeResource({trade_no: trade.inner_no})
|
||||
if (!resp.success) throw new Error(resp.message)
|
||||
toast.success('支付成功')
|
||||
setPaymentVerified(true)
|
||||
setTimeout(onClose, 2000)
|
||||
}
|
||||
catch (e) {
|
||||
toast.error('支付验证失败', {description: (e as Error).message})
|
||||
}
|
||||
finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogContent className="max-w-[95vw] rounded-lg">
|
||||
{paymentVerified ? (
|
||||
<div className="py-6 text-center">
|
||||
<CheckCircle className="mx-auto h-14 w-14 text-green-500"/>
|
||||
<p className="mt-4 text-lg font-medium">支付验证成功</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* 支付确认信息 */}
|
||||
<div className="text-center">
|
||||
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-blue-50 text-blue-500">
|
||||
<CreditCard className="h-8 w-8"/>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-gray-800">确认支付</h3>
|
||||
<p className="text-gray-500">请确认以下支付信息</p>
|
||||
</div>
|
||||
|
||||
{/* 支付详情 */}
|
||||
<div className="space-y-4 rounded-lg bg-gray-50 p-4">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">订单号</span>
|
||||
<span className="font-medium">{trade.inner_no}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">支付方式</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Image
|
||||
src={paymentInfo.icon}
|
||||
alt={paymentInfo.name}
|
||||
width={28}
|
||||
height={28}
|
||||
className="rounded-md"
|
||||
/>
|
||||
<span>{paymentInfo.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">支付金额</span>
|
||||
<span className="text-lg font-bold text-blue-600">
|
||||
¥
|
||||
{typeof trade.amount === 'number'
|
||||
? trade.amount.toFixed(2)
|
||||
: '0.00'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
theme="outline"
|
||||
className="flex-1 py-3 text-base"
|
||||
onClick={onClose} >
|
||||
取消
|
||||
</Button>
|
||||
<Button className="flex-1 py-3 text-base" onClick={() => window.location.href = trade.pay_url} >
|
||||
确认支付
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
56
src/components/composites/payment/payment-button.tsx
Normal file
56
src/components/composites/payment/payment-button.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
'use client'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {useState} from 'react'
|
||||
import {PaymentModal} from './payment-modal'
|
||||
import type {Trade, PaymentResponse} from './types'
|
||||
import {usePlatformType, Platform} from '@/lib/models/trade'
|
||||
|
||||
export function PaymentButton({
|
||||
onClick,
|
||||
trade,
|
||||
disabled,
|
||||
onSuccess,
|
||||
}: {
|
||||
onClick: () => Promise<PaymentResponse>
|
||||
trade?: Trade
|
||||
disabled?: boolean
|
||||
onSuccess?: () => void
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const platform = usePlatformType() // 获取平台信息
|
||||
|
||||
const handleClick = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await onClick()
|
||||
if (result?.success && result.data) {
|
||||
setOpen(true)
|
||||
}
|
||||
}
|
||||
finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={handleClick}
|
||||
disabled={disabled || loading}
|
||||
>
|
||||
{loading ? '处理中...' : '立即支付'}
|
||||
</Button>
|
||||
|
||||
{trade && (
|
||||
<PaymentModal
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
trade={trade}
|
||||
platform={platform} // 传递平台信息
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
43
src/components/composites/payment/payment-modal.tsx
Normal file
43
src/components/composites/payment/payment-modal.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
import {Dialog} from '@/components/ui/dialog'
|
||||
import {MobilePayment} from './mobile-payment'
|
||||
import {DesktopPayment} from './desktop-payment'
|
||||
import {Platform} from '@/lib/models/trade'
|
||||
import {Trade} from './types'
|
||||
|
||||
export function PaymentModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
trade,
|
||||
platform,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
trade: Trade
|
||||
platform: Platform
|
||||
onSuccess?: () => void
|
||||
}) {
|
||||
const handleClose = (success: boolean) => {
|
||||
onOpenChange(false)
|
||||
if (success && onSuccess) {
|
||||
onSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{platform === Platform.Mobile ? (
|
||||
<MobilePayment
|
||||
trade={trade}
|
||||
onClose={() => handleClose(true)}
|
||||
/>
|
||||
) : (
|
||||
<DesktopPayment
|
||||
trade={trade}
|
||||
onClose={() => handleClose(true)}
|
||||
/>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
26
src/components/composites/payment/payment-status.tsx
Normal file
26
src/components/composites/payment/payment-status.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client'
|
||||
import {CheckCircle, AlertCircle, ClockIcon} from 'lucide-react'
|
||||
import {Trade, PaymentStatus} from './types'
|
||||
|
||||
export function PaymentStatus({trade}: {trade?: Trade}) {
|
||||
if (!trade) return null
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
{trade.status === PaymentStatus.Completed ? (
|
||||
<CheckCircle size={16} className="text-done"/>
|
||||
) : trade.status === PaymentStatus.Cancelled ? (
|
||||
<AlertCircle size={16} className="text-weak"/>
|
||||
) : trade.status === PaymentStatus.Refunded ? (
|
||||
<AlertCircle size={16} className="text-fail"/>
|
||||
) : (
|
||||
<ClockIcon size={16} className="text-warn"/>
|
||||
)}
|
||||
<span>
|
||||
{trade.status === PaymentStatus.Completed ? '已完成'
|
||||
: trade.status === PaymentStatus.Cancelled ? '已取消'
|
||||
: trade.status === PaymentStatus.Refunded ? '已退款' : '待支付'}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
31
src/components/composites/payment/types.tsx
Normal file
31
src/components/composites/payment/types.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
export enum PaymentMethod {
|
||||
Alipay = 1,
|
||||
WeChat = 2,
|
||||
Sft = 3,
|
||||
SftAlipay = 4,
|
||||
SftWeChat = 5,
|
||||
}
|
||||
|
||||
export interface Trade {
|
||||
inner_no: string
|
||||
method: PaymentMethod
|
||||
pay_url: string
|
||||
amount?: number
|
||||
status?: PaymentStatus
|
||||
}
|
||||
|
||||
export interface PaymentResponse {
|
||||
success: boolean
|
||||
data?: {
|
||||
trade_no: string
|
||||
pay_url: string
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
export enum PaymentStatus {
|
||||
Pending = 0,
|
||||
Completed = 1,
|
||||
Cancelled = 2,
|
||||
Refunded = 3,
|
||||
}
|
||||
export type PaymentPlatform = 'mobile' | 'desktop'
|
||||
@@ -1,117 +1,87 @@
|
||||
'use client'
|
||||
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger} from '@/components/ui/dialog'
|
||||
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from '@/components/ui/dialog'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import alipay from './_assets/alipay.svg'
|
||||
import wechat from './_assets/wechat.svg'
|
||||
import balance from './_assets/balance.svg'
|
||||
import Image from 'next/image'
|
||||
import {useEffect, useRef, useState} from 'react'
|
||||
import {useState} from 'react'
|
||||
import {useProfileStore} from '@/components/stores-provider'
|
||||
import {Alert, AlertTitle} from '@/components/ui/alert'
|
||||
import {ApiResponse, ExtraResp, ExtraReq} from '@/lib/api'
|
||||
import {toast} from 'sonner'
|
||||
import {Loader} from 'lucide-react'
|
||||
import {useRouter} from 'next/navigation'
|
||||
import * as qrcode from 'qrcode'
|
||||
import {completeResource, createResource, prepareResource} from '@/actions/resource'
|
||||
import {PaymentMethod, Platform, usePlatformType} from '@/lib/models/trade'
|
||||
import {PaymentModal} from '@/components/composites/payment/payment-modal'
|
||||
import type {Trade} from '@/components/composites/payment/types'
|
||||
|
||||
export type PayProps = {
|
||||
method: 'alipay' | 'wechat' | 'balance'
|
||||
amount: string
|
||||
resource: ExtraReq<typeof createResource>
|
||||
resource: Parameters<typeof createResource>[0]
|
||||
}
|
||||
|
||||
export default function Pay(props: PayProps) {
|
||||
const profile = useProfileStore(store => store.profile)
|
||||
const refreshProfile = useProfileStore(store => store.refreshProfile)
|
||||
const platform = usePlatformType() // 获取当前平台类型
|
||||
const [open, setOpen] = useState(false)
|
||||
const [payInfo, setPayInfo] = useState<ExtraResp<typeof prepareResource> | undefined>()
|
||||
const canvas = useRef<HTMLCanvasElement>(null)
|
||||
useEffect(() => {
|
||||
if (canvas.current && payInfo) {
|
||||
qrcode.toCanvas(canvas.current, payInfo.pay_url, {
|
||||
width: 200,
|
||||
margin: 0,
|
||||
}).then()
|
||||
}
|
||||
}, [payInfo])
|
||||
const [trade, setTrade] = useState<Trade | null>(null)
|
||||
const router = useRouter()
|
||||
const platform = usePlatformType()
|
||||
|
||||
const onOpen = async () => {
|
||||
setOpen(true)
|
||||
|
||||
if (props.method === 'balance') {
|
||||
return
|
||||
}
|
||||
if (props.method === 'balance') return
|
||||
|
||||
// 根据平台类型设置支付方法
|
||||
let paymentMethod: PaymentMethod
|
||||
if (platform === Platform.Desktop) {
|
||||
paymentMethod = PaymentMethod.Sft
|
||||
}
|
||||
else {
|
||||
// 移动端根据选择的支付方式设置
|
||||
paymentMethod = props.method === 'alipay'
|
||||
? PaymentMethod.SftAlipay
|
||||
: PaymentMethod.SftWeChat
|
||||
}
|
||||
|
||||
const method = {
|
||||
alipay: PaymentMethod.Alipay,
|
||||
wechat: PaymentMethod.WeChat,
|
||||
}[props.method]
|
||||
// 准备支付信息
|
||||
const paymentMethod = props.method === 'alipay'
|
||||
? platform === Platform.Mobile
|
||||
? PaymentMethod.SftAlipay // 4
|
||||
: PaymentMethod.Alipay // 1
|
||||
: platform === Platform.Mobile
|
||||
? PaymentMethod.SftWeChat // 5
|
||||
: PaymentMethod.WeChat // 2
|
||||
|
||||
const res = {
|
||||
...props.resource,
|
||||
payment_method: paymentMethod,
|
||||
payment_platform: platform, // 使用检测到的平台类型
|
||||
payment_platform: platform,
|
||||
}
|
||||
console.log(res, 'reresp')
|
||||
const resp = await prepareResource(res)
|
||||
console.log(resp, 'resp')
|
||||
console.log(res, '请求参数')
|
||||
|
||||
const resp = await prepareResource(res)
|
||||
if (!resp.success) {
|
||||
toast.error(`创建订单失败: ${resp.message}`)
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
|
||||
setPayInfo(resp.data)
|
||||
setTrade({
|
||||
inner_no: resp.data.trade_no,
|
||||
method: props.method === 'alipay' ? PaymentMethod.Alipay : PaymentMethod.WeChat,
|
||||
pay_url: resp.data.pay_url,
|
||||
amount: Number(props.amount),
|
||||
})
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
const onSubmit = async () => {
|
||||
let resp: ApiResponse
|
||||
try {
|
||||
switch (props.method) {
|
||||
case 'alipay':
|
||||
case 'wechat':
|
||||
if (!payInfo) {
|
||||
toast.error('无法读取支付信息', {
|
||||
description: `请联系客服确认支付状态`,
|
||||
})
|
||||
return
|
||||
}
|
||||
resp = await completeResource({
|
||||
trade_no: payInfo.trade_no,
|
||||
})
|
||||
break
|
||||
let resp: Awaited<ReturnType<typeof completeResource>> | Awaited<ReturnType<typeof createResource>>
|
||||
|
||||
case 'balance':
|
||||
if (props.method === 'balance') {
|
||||
resp = await createResource(props.resource)
|
||||
break
|
||||
}
|
||||
else if (trade) {
|
||||
resp = await completeResource({trade_no: trade.inner_no})
|
||||
}
|
||||
else {
|
||||
throw new Error('支付信息不存在')
|
||||
}
|
||||
|
||||
if (!resp.success) {
|
||||
throw new Error(resp.message)
|
||||
}
|
||||
if (!resp.success) throw new Error(resp.message)
|
||||
|
||||
toast.success('购买成功', {
|
||||
duration: 10 * 1000,
|
||||
closeButton: true,
|
||||
action: {
|
||||
label: `去提取`,
|
||||
label: '去提取',
|
||||
onClick: () => router.push('/admin/extract'),
|
||||
},
|
||||
})
|
||||
@@ -120,7 +90,6 @@ export default function Pay(props: PayProps) {
|
||||
await refreshProfile()
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e)
|
||||
toast.error('购买失败', {
|
||||
description: (e as Error).message,
|
||||
})
|
||||
@@ -130,131 +99,92 @@ export default function Pay(props: PayProps) {
|
||||
const balanceEnough = profile && profile.balance >= Number(props.amount)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="mt-4 h-12" onClick={onOpen}>
|
||||
立即支付
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex gap-2 items-center">
|
||||
{props.method === 'alipay' && (
|
||||
<>
|
||||
<Image src={alipay} alt="支付宝" width={20} height={20}/>
|
||||
<span>支付宝</span>
|
||||
</>
|
||||
)}
|
||||
{props.method === 'wechat' && (
|
||||
<>
|
||||
<Image src={wechat} alt="微信" width={20} height={20}/>
|
||||
<span>微信</span>
|
||||
</>
|
||||
)}
|
||||
{props.method === 'balance' && (
|
||||
<>
|
||||
<>
|
||||
<Button className="mt-4 h-12" onClick={onOpen}>
|
||||
立即支付
|
||||
</Button>
|
||||
|
||||
{/* 余额支付对话框 */}
|
||||
{/* 余额支付对话框 */}
|
||||
{props.method === 'balance' && (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex gap-2 items-center">
|
||||
<Image src={balance} alt="余额" width={20} height={20}/>
|
||||
<span>余额支付</span>
|
||||
</>
|
||||
)}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{props.method === 'balance' ? (
|
||||
profile && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-weak text-sm">账户余额</span>
|
||||
<span className="text-lg">
|
||||
{profile.balance}
|
||||
元
|
||||
</span>
|
||||
{profile && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-weak text-sm">账户余额</span>
|
||||
<span className="text-lg">
|
||||
{profile.balance}
|
||||
元
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-weak text-sm">支付金额</span>
|
||||
<span className="text-lg text-accent">
|
||||
-
|
||||
{props.amount}
|
||||
元
|
||||
</span>
|
||||
</div>
|
||||
<hr className="my-2"/>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-weak text-sm">支付后余额</span>
|
||||
<span className={`text-lg ${balanceEnough ? 'text-done' : 'text-fail'}`}>
|
||||
{(profile.balance - Number(props.amount)).toFixed(2)}
|
||||
元
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-weak text-sm">支付金额</span>
|
||||
<span className="text-lg text-accent">
|
||||
-
|
||||
{props.amount}
|
||||
元
|
||||
</span>
|
||||
</div>
|
||||
<hr className="my-2"/>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-weak text-sm">支付后余额</span>
|
||||
<span className={`text-lg ${balanceEnough ? 'text-done' : `text-fail`}`}>
|
||||
{(profile.balance - Number(props.amount)).toFixed(2)}
|
||||
元
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{balanceEnough ? (
|
||||
<Alert variant="done">
|
||||
<AlertTitle>
|
||||
检查无误后,点击确认支付按钮完成支付
|
||||
</AlertTitle>
|
||||
</Alert>
|
||||
) : (
|
||||
<Alert variant="fail">
|
||||
<AlertTitle>
|
||||
余额不足,请先充值或选择其他支付方式
|
||||
</AlertTitle>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="bg-gray-100 size-50 flex items-center justify-center">
|
||||
{payInfo ? (
|
||||
props.method === 'alipay'
|
||||
? <iframe src={payInfo.pay_url} className="w-full h-full"/>
|
||||
: <canvas ref={canvas} className="w-full h-full"/>
|
||||
{balanceEnough ? (
|
||||
<Alert variant="done">
|
||||
<AlertTitle>
|
||||
检查无误后,点击确认支付按钮完成支付
|
||||
</AlertTitle>
|
||||
</Alert>
|
||||
) : (
|
||||
<Loader size={40} className="animate-spin text-weak"/>
|
||||
<Alert variant="fail">
|
||||
<AlertTitle>
|
||||
余额不足,请先充值或选择其他支付方式
|
||||
</AlertTitle>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 text-center">
|
||||
请使用
|
||||
{props.method === 'alipay' ? '支付宝' : '微信'}
|
||||
扫码支付
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center space-y-1">
|
||||
<p className="font-medium">
|
||||
支付金额:
|
||||
<span className="text-accent">
|
||||
{props.amount}
|
||||
元
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
订单号:
|
||||
{payInfo?.trade_no || '创建订单中...'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={props.method === 'balance' && !!profile && !balanceEnough}
|
||||
onClick={onSubmit}
|
||||
>
|
||||
{props.method === 'balance' ? '确认支付' : '已完成支付'}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
theme="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
disabled={!balanceEnough}
|
||||
onClick={onSubmit}
|
||||
>
|
||||
确认支付
|
||||
</Button>
|
||||
<Button theme="outline" onClick={() => setOpen(false)}>
|
||||
取消
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
|
||||
{/* 支付宝/微信支付使用公共组件 */}
|
||||
{props.method !== 'balance' && trade && (
|
||||
<PaymentModal
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
trade={trade}
|
||||
platform={platform}
|
||||
onSuccess={onSubmit}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,20 +12,20 @@ import {useForm} from 'react-hook-form'
|
||||
import zod from 'zod'
|
||||
import FormOption from '@/components/composites/purchase/option'
|
||||
import {RadioGroup} from '@/components/ui/radio-group'
|
||||
import Image from 'next/image'
|
||||
import {zodResolver} from '@hookform/resolvers/zod'
|
||||
import {toast} from 'sonner'
|
||||
import {useEffect, useMemo, useRef, useState} from 'react'
|
||||
import {Loader} from 'lucide-react'
|
||||
import {RechargeComplete, RechargePrepare} from '@/actions/user'
|
||||
import * as qrcode from 'qrcode'
|
||||
import {useMemo, useState} from 'react'
|
||||
import {RechargePrepare} from '@/actions/user'
|
||||
import {useProfileStore} from '@/components/stores-provider'
|
||||
import {merge} from '@/lib/utils'
|
||||
import {
|
||||
Platform,
|
||||
PAYMENT_METHODS,
|
||||
usePlatformType,
|
||||
PaymentMethod,
|
||||
} from '@/lib/models/trade'
|
||||
import {PaymentModal} from '@/components/composites/payment/payment-modal'
|
||||
import type {Trade} from '@/components/composites/payment/types'
|
||||
|
||||
const schema = zod.object({
|
||||
method: zod.enum(['alipay', 'wechat', 'sft', 'sftAlipay', 'sftWeChat']),
|
||||
@@ -53,17 +53,11 @@ export default function RechargeModal(props: RechargeModelProps) {
|
||||
|
||||
const method = form.watch('method')
|
||||
const amount = form.watch('amount')
|
||||
|
||||
const [step, setStep] = useState(0)
|
||||
const [payInfo, setPayInfo] = useState<{
|
||||
trade_no: string
|
||||
pay_url: string
|
||||
}>()
|
||||
const [trade, setTrade] = useState<Trade | null>(null)
|
||||
const refreshProfile = useProfileStore(store => store.refreshProfile)
|
||||
|
||||
// 获取当前平台可用的支付方法
|
||||
const availableMethods = useMemo(() => {
|
||||
console.log(PAYMENT_METHODS, 'PAYMENT_METHODS')
|
||||
|
||||
return Object.values(PAYMENT_METHODS)
|
||||
.filter(method => method.availablePlatforms.includes(platform))
|
||||
.map(method => ({
|
||||
@@ -72,41 +66,40 @@ export default function RechargeModal(props: RechargeModelProps) {
|
||||
icon: method.icon,
|
||||
}))
|
||||
}, [platform])
|
||||
const canvas = useRef<HTMLCanvasElement>(null)
|
||||
useEffect(() => {
|
||||
console.log('Canvas ref:', canvas.current)
|
||||
if (!payInfo || !canvas.current || method.includes('alipay')) return
|
||||
qrcode.toCanvas(canvas.current, payInfo.pay_url, {
|
||||
width: 200,
|
||||
margin: 0,
|
||||
})
|
||||
}, [payInfo, method])
|
||||
|
||||
const refreshProfile = useProfileStore(store => store.refreshProfile)
|
||||
|
||||
const createRecharge = async (data: Schema) => {
|
||||
try {
|
||||
const paymentMethod = Object.entries(PAYMENT_METHODS).find(
|
||||
([_, config]) => config.formValue === data.method,
|
||||
)
|
||||
console.log(paymentMethod, 'paymentMethod')
|
||||
|
||||
if (!paymentMethod) {
|
||||
throw new Error('无效的支付方式')
|
||||
}
|
||||
const actualMethod = paymentMethod[1].getActualMethod(platform)
|
||||
console.log('转换后的支付方式:', {
|
||||
formValue: data.method,
|
||||
platform: platform === Platform.Mobile ? 'Mobile' : 'Desktop',
|
||||
actualMethod,
|
||||
methodName: actualMethod === PaymentMethod.Alipay ? 'Alipay'
|
||||
: actualMethod === PaymentMethod.SftAlipay ? 'SftAlipay'
|
||||
: actualMethod === PaymentMethod.WeChat ? 'WeChat'
|
||||
: actualMethod === PaymentMethod.SftWeChat ? 'SftWeChat' : 'Unknown',
|
||||
})
|
||||
const resp = {
|
||||
amount: data.amount.toString(),
|
||||
platform: platform,
|
||||
method: paymentMethod[1].actualMethod,
|
||||
method: actualMethod,
|
||||
}
|
||||
console.log(resp, 'resp')
|
||||
|
||||
const result = await RechargePrepare(resp)
|
||||
console.log(result, 'result')
|
||||
|
||||
if (result.success) {
|
||||
setStep(1)
|
||||
setPayInfo(result.data)
|
||||
setTrade({
|
||||
inner_no: result.data.trade_no,
|
||||
method: actualMethod,
|
||||
pay_url: result.data.pay_url,
|
||||
amount: data.amount,
|
||||
})
|
||||
}
|
||||
else {
|
||||
throw new Error(result.message)
|
||||
@@ -119,203 +112,117 @@ export default function RechargeModal(props: RechargeModelProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const confirmRecharge = async () => {
|
||||
if (!payInfo) {
|
||||
toast.error(`充值失败`, {
|
||||
description: `订单信息不存在`,
|
||||
})
|
||||
return
|
||||
}
|
||||
const handlePaymentSuccess = async () => {
|
||||
try {
|
||||
switch (method) {
|
||||
case 'alipay':
|
||||
const aliRes = await RechargeComplete({
|
||||
trade_no: payInfo.trade_no,
|
||||
})
|
||||
if (!aliRes.success) {
|
||||
throw new Error(aliRes.message)
|
||||
}
|
||||
break
|
||||
case 'wechat':
|
||||
const weRes = await RechargeComplete({
|
||||
trade_no: payInfo.trade_no,
|
||||
})
|
||||
if (!weRes.success) {
|
||||
throw new Error(weRes.message)
|
||||
}
|
||||
break
|
||||
}
|
||||
toast.success(`充值成功`)
|
||||
closeDialog()
|
||||
await refreshProfile()
|
||||
toast.success('充值成功')
|
||||
setOpen(false)
|
||||
form.reset()
|
||||
}
|
||||
catch (e) {
|
||||
toast.error(`充值失败`, {
|
||||
toast.error('刷新账户信息失败', {
|
||||
description: (e as Error).message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const closeDialog = () => {
|
||||
setOpen(false)
|
||||
setPayInfo(undefined)
|
||||
setStep(0)
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button theme="accent" type="button" className={merge(`px-4 h-8`, props.classNames?.trigger)}>去充值</Button>
|
||||
<Button
|
||||
theme="accent"
|
||||
type="button"
|
||||
className={merge(`px-4 h-8`, props.classNames?.trigger)}
|
||||
>
|
||||
去充值
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
|
||||
<DialogContent className={platform === Platform.Mobile ? 'max-w-[95vw]' : 'max-w-md'}>
|
||||
<DialogTitle className="flex flex-col gap-2">
|
||||
充值中心
|
||||
</DialogTitle>
|
||||
|
||||
{step === 0 && (
|
||||
<Form form={form} onSubmit={createRecharge} className="flex flex-col gap-8">
|
||||
|
||||
{/* 充值额度 */}
|
||||
<FormField<Schema> name="amount" label="充值额度" className="flex flex-col gap-4">
|
||||
{({id, field}) => (
|
||||
<RadioGroup
|
||||
id={id}
|
||||
defaultValue={String(field.value)}
|
||||
onValueChange={v => field.onChange(Number(v))}
|
||||
className="flex flex-col gap-2">
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<FormOption
|
||||
id={`${id}-20`}
|
||||
value="20"
|
||||
label="20元"
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
<FormOption
|
||||
id={`${id}-50`}
|
||||
value="50"
|
||||
label="50元"
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
<FormOption
|
||||
id={`${id}-100`}
|
||||
value="100"
|
||||
label="100元"
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<FormOption
|
||||
id={`${id}-200`}
|
||||
value="200"
|
||||
label="200元"
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
<FormOption
|
||||
id={`${id}-500`}
|
||||
value="500"
|
||||
label="500元"
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
<FormOption
|
||||
id={`${id}-1000`}
|
||||
value="1000"
|
||||
label="1000元"
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
)}
|
||||
</FormField>
|
||||
|
||||
{/* 支付方式 */}
|
||||
<FormField name="method" label="支付方式" className="flex flex-col gap-4">
|
||||
{({id, field}) => (
|
||||
<RadioGroup
|
||||
id={id}
|
||||
defaultValue={field.value}
|
||||
onValueChange={field.onChange}
|
||||
className="flex gap-2">
|
||||
{availableMethods.map(({value, name, icon}) => (
|
||||
<FormOption
|
||||
key={value}
|
||||
id={`${id}-${value}`}
|
||||
value={value}
|
||||
compare={field.value}
|
||||
className="flex-1 flex-row justify-center items-center"
|
||||
>
|
||||
{icon && <Image src={icon} alt={`${name} logo`} className="w-6 h-6"/>}
|
||||
<span>{name}</span>
|
||||
</FormOption>
|
||||
))}
|
||||
</RadioGroup>
|
||||
)}
|
||||
</FormField>
|
||||
|
||||
<DialogFooter className="!flex !flex-row !justify-center">
|
||||
<Button className="px-8 h-12 text-lg">立即支付</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
)}
|
||||
{step == 1 && (
|
||||
{!trade ? (
|
||||
<>
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="bg-gray-100 size-50 flex items-center justify-center">
|
||||
{payInfo
|
||||
? method === 'alipay'
|
||||
? <iframe src={payInfo.pay_url} className="w-full h-full"/>
|
||||
: <canvas ref={canvas} className="w-full h-full"/>
|
||||
: (
|
||||
<Loader size={40} className="animate-spin text-weak"/>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 text-center">
|
||||
请使用
|
||||
{method === 'alipay' ? '支付宝' : '微信'}
|
||||
扫码支付
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center space-y-1">
|
||||
<p className="font-medium">
|
||||
支付金额:
|
||||
<span className="text-accent">
|
||||
{amount}
|
||||
元
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
订单号:
|
||||
{payInfo?.trade_no || '创建订单中...'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogTitle className="flex flex-col gap-2">充值中心</DialogTitle>
|
||||
<Form form={form} onSubmit={createRecharge} className="flex flex-col gap-8">
|
||||
{/* 充值额度 */}
|
||||
<FormField<Schema> name="amount" label="充值额度" className="flex flex-col gap-4">
|
||||
{({id, field}) => (
|
||||
<RadioGroup
|
||||
id={id}
|
||||
defaultValue={String(field.value)}
|
||||
onValueChange={v => field.onChange(Number(v))}
|
||||
className="flex flex-col gap-2"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{[20, 50, 100].map(value => (
|
||||
<FormOption
|
||||
key={value}
|
||||
id={`${id}-${value}`}
|
||||
value={String(value)}
|
||||
label={`${value}元`}
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{[200, 500, 1000].map(value => (
|
||||
<FormOption
|
||||
key={value}
|
||||
id={`${id}-${value}`}
|
||||
value={String(value)}
|
||||
label={`${value}元`}
|
||||
compare={String(field.value)}
|
||||
className="flex-1 max-sm:text-sm max-sm:px-0"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</RadioGroup>
|
||||
)}
|
||||
</FormField>
|
||||
|
||||
<DialogFooter className="!flex !flex-row !justify-center">
|
||||
<Button
|
||||
className="px-8 text-lg"
|
||||
onClick={confirmRecharge}
|
||||
>
|
||||
已完成支付
|
||||
</Button>
|
||||
<Button
|
||||
theme="outline"
|
||||
className="px-8 text-lg"
|
||||
onClick={closeDialog}
|
||||
>
|
||||
关闭
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
{/* 支付方式 */}
|
||||
<FormField name="method" label="支付方式" className="flex flex-col gap-4">
|
||||
{({id, field}) => (
|
||||
<RadioGroup
|
||||
id={id}
|
||||
defaultValue={field.value}
|
||||
onValueChange={field.onChange}
|
||||
className="flex gap-2"
|
||||
>
|
||||
{availableMethods.map(({value, name, icon}) => (
|
||||
<FormOption
|
||||
key={value}
|
||||
id={`${id}-${value}`}
|
||||
value={value}
|
||||
compare={field.value}
|
||||
className="flex-1 flex-row justify-center items-center"
|
||||
>
|
||||
{icon && <img src={icon.src} alt={`${name} logo`} className="w-6 h-6 mr-2"/>}
|
||||
<span>{name}</span>
|
||||
</FormOption>
|
||||
))}
|
||||
</RadioGroup>
|
||||
)}
|
||||
</FormField>
|
||||
|
||||
<DialogFooter className="!flex !flex-row !justify-center">
|
||||
<Button className="px-8 h-12 text-lg">立即支付</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
</>
|
||||
) : (
|
||||
<PaymentModal
|
||||
open={open}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setTrade(null)
|
||||
setOpen(false)
|
||||
}
|
||||
}}
|
||||
trade={trade}
|
||||
platform={platform}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -19,9 +19,18 @@ export const Platform = {
|
||||
Mobile: 2,
|
||||
} as const
|
||||
|
||||
// 支付状态枚举
|
||||
export const PaymentStatus = {
|
||||
Pending: 0,
|
||||
Completed: 1,
|
||||
Cancelled: 2, // 同步修改
|
||||
Refunded: 3,
|
||||
} as const
|
||||
|
||||
// 定义类型
|
||||
export type PaymentMethod = typeof PaymentMethod[keyof typeof PaymentMethod]
|
||||
export type Platform = typeof Platform[keyof typeof Platform]
|
||||
export type PaymentStatus = typeof PaymentStatus[keyof typeof PaymentStatus]
|
||||
|
||||
// 支付方法配置类型
|
||||
export type PaymentMethodConfig = {
|
||||
@@ -29,86 +38,93 @@ export type PaymentMethodConfig = {
|
||||
icon: StaticImageData | null
|
||||
formValue: string
|
||||
availablePlatforms: Platform[]
|
||||
actualMethod: PaymentMethod
|
||||
getActualMethod: (platform: Platform) => PaymentMethod
|
||||
}
|
||||
|
||||
// 支付方法配置
|
||||
export const PAYMENT_METHODS: Record<PaymentMethod, PaymentMethodConfig> = {
|
||||
[PaymentMethod.Alipay]: {
|
||||
export const PAYMENT_METHODS: Record<string, PaymentMethodConfig> = {
|
||||
alipay: {
|
||||
name: '支付宝',
|
||||
icon: alipay,
|
||||
formValue: 'alipay',
|
||||
availablePlatforms: [Platform.Desktop],
|
||||
actualMethod: PaymentMethod.Sft,
|
||||
availablePlatforms: [Platform.Desktop, Platform.Mobile],
|
||||
getActualMethod: platform =>
|
||||
platform === Platform.Desktop ? PaymentMethod.Sft : PaymentMethod.SftAlipay,
|
||||
},
|
||||
[PaymentMethod.WeChat]: {
|
||||
wechat: {
|
||||
name: '微信支付',
|
||||
icon: wechat,
|
||||
formValue: 'wechat',
|
||||
availablePlatforms: [Platform.Desktop],
|
||||
actualMethod: PaymentMethod.Sft,
|
||||
availablePlatforms: [Platform.Desktop, Platform.Mobile],
|
||||
getActualMethod: platform =>
|
||||
platform === Platform.Desktop ? PaymentMethod.Sft : PaymentMethod.SftWeChat,
|
||||
},
|
||||
[PaymentMethod.Sft]: {
|
||||
sft: {
|
||||
name: '商福通',
|
||||
icon: null,
|
||||
formValue: 'sft',
|
||||
availablePlatforms: [],
|
||||
actualMethod: PaymentMethod.Sft,
|
||||
},
|
||||
[PaymentMethod.SftAlipay]: {
|
||||
name: '支付宝',
|
||||
icon: alipay,
|
||||
formValue: 'sftAlipay',
|
||||
availablePlatforms: [Platform.Mobile],
|
||||
actualMethod: PaymentMethod.SftAlipay,
|
||||
},
|
||||
[PaymentMethod.SftWeChat]: {
|
||||
name: '微信',
|
||||
icon: wechat,
|
||||
formValue: 'sftWeChat',
|
||||
availablePlatforms: [Platform.Mobile],
|
||||
actualMethod: PaymentMethod.SftWeChat,
|
||||
getActualMethod: () => PaymentMethod.Sft,
|
||||
},
|
||||
} as const
|
||||
|
||||
// 交易信息类型
|
||||
export interface Trade {
|
||||
inner_no: string
|
||||
method: PaymentMethod
|
||||
pay_url: string
|
||||
status?: PaymentStatus
|
||||
amount?: number
|
||||
created_at?: string
|
||||
expired_at?: string
|
||||
}
|
||||
|
||||
// 支付请求参数类型
|
||||
export type PaymentRequest = {
|
||||
amount: string
|
||||
platform: Platform
|
||||
method: PaymentMethod
|
||||
product_id?: string
|
||||
product_name?: string
|
||||
}
|
||||
|
||||
// 支付结果类型
|
||||
export type PaymentResult = {
|
||||
success: boolean
|
||||
trade_no: string
|
||||
message?: string
|
||||
payment_time?: string
|
||||
}
|
||||
|
||||
// 设备检测Hook
|
||||
export const usePlatformType = (): Platform => {
|
||||
const [platform, setPlatform] = useState<Platform>(Platform.Desktop)
|
||||
// 在SSR环境下返回默认值
|
||||
const [platform, setPlatform] = useState<Platform>(() => {
|
||||
if (typeof window === 'undefined') return Platform.Desktop
|
||||
return window.matchMedia('(max-width: 768px)').matches
|
||||
? Platform.Mobile
|
||||
: Platform.Desktop
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
// 确保在客户端执行
|
||||
if (typeof window === 'undefined') return
|
||||
|
||||
const checkPlatform = () => {
|
||||
const isMobile = window.matchMedia('(max-width: 768px)').matches
|
||||
setPlatform(isMobile ? Platform.Mobile : Platform.Desktop)
|
||||
}
|
||||
|
||||
checkPlatform()
|
||||
const mediaQuery = window.matchMedia('(max-width: 768px)')
|
||||
mediaQuery.addEventListener('change', checkPlatform)
|
||||
return () => mediaQuery.removeEventListener('change', checkPlatform)
|
||||
|
||||
return () => {
|
||||
mediaQuery.removeEventListener('change', checkPlatform)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return platform
|
||||
}
|
||||
// export const usePlatformType = (): Platform => {
|
||||
// const [platform, setPlatform] = useState<Platform>(Platform.Desktop)
|
||||
|
||||
// useEffect(() => {
|
||||
// // 确保在客户端执行
|
||||
// if (typeof window === 'undefined') return
|
||||
|
||||
// const checkPlatform = () => {
|
||||
// const isMobile = window.matchMedia('(max-width: 768px)').matches
|
||||
// setPlatform(isMobile ? Platform.Mobile : Platform.Desktop)
|
||||
// }
|
||||
|
||||
// checkPlatform()
|
||||
// const mediaQuery = window.matchMedia('(max-width: 768px)')
|
||||
// mediaQuery.addEventListener('change', checkPlatform)
|
||||
// return () => mediaQuery.removeEventListener('change', checkPlatform)
|
||||
// }, [])
|
||||
|
||||
// return platform
|
||||
// }
|
||||
|
||||
// 支付表单验证schema
|
||||
export const paymentSchema = zod.object({
|
||||
@@ -117,20 +133,13 @@ export const paymentSchema = zod.object({
|
||||
})
|
||||
|
||||
export type PaymentSchema = zod.infer<typeof paymentSchema>
|
||||
// 新增函数:根据PaymentMethod获取展示信息
|
||||
export const getPaymentMethodInfo = (method: PaymentMethod) => {
|
||||
const found = Object.values(PAYMENT_METHODS).find(
|
||||
config => config.getActualMethod(Platform.Mobile) === method,
|
||||
)
|
||||
|
||||
// 支付请求参数类型
|
||||
export type PaymentRequest = {
|
||||
amount: string
|
||||
platform: Platform
|
||||
method: PaymentMethod
|
||||
return found
|
||||
? {icon: found.icon, name: found.name}
|
||||
: {icon: null, name: '未知支付方式'}
|
||||
}
|
||||
|
||||
export interface Trade {
|
||||
inner_no: string
|
||||
method: number
|
||||
pay_url: string
|
||||
status?: number
|
||||
amount?: number
|
||||
}
|
||||
|
||||
export interface OptionalTrade extends Partial<Trade> {}
|
||||
|
||||
Reference in New Issue
Block a user