更新了购买套餐里的充值和立即支付的传参,增加我的账单模块待支付链接跳转和弹窗
This commit is contained in:
@@ -55,7 +55,6 @@ export async function createResource(props: {
|
||||
}
|
||||
|
||||
export async function prepareResource(props: {
|
||||
method: number
|
||||
type: number
|
||||
short?: {
|
||||
live: number
|
||||
@@ -71,6 +70,8 @@ export async function prepareResource(props: {
|
||||
expire: number
|
||||
daily_limit: number
|
||||
}
|
||||
payment_method: number
|
||||
payment_platform: number
|
||||
}) {
|
||||
return await callByUser<{
|
||||
trade_no: string
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
'use server'
|
||||
import {callByUser, callPublic} from '@/actions/base'
|
||||
|
||||
export async function RechargeByAlipay(props: {
|
||||
export async function RechargeByPay(props: {
|
||||
amount: string
|
||||
platform: number
|
||||
method: number
|
||||
}) {
|
||||
return callByUser<{
|
||||
trade_no: string
|
||||
pay_url: string
|
||||
}>('/api/user/recharge/prepare/alipay', props)
|
||||
}>('/api/user/recharge/prepare', props)
|
||||
}
|
||||
|
||||
export async function RechargeByAlipayConfirm(props: {
|
||||
|
||||
@@ -4,7 +4,7 @@ import {PageRecord} from '@/lib/api'
|
||||
import {Bill} from '@/lib/models'
|
||||
import {useStatus} from '@/lib/states'
|
||||
import {listBills} from '@/actions/bill'
|
||||
import {Search, Eraser, CreditCard, AlertCircle, CheckCircle, Clock, ClockIcon} from 'lucide-react'
|
||||
import {Search, Eraser, CreditCard} from 'lucide-react'
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from '@/components/ui/select'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import DataTable from '@/components/data-table'
|
||||
@@ -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 Link from 'next/link'
|
||||
import {PaymentStatusCell} from '@/components/composites/payment'
|
||||
|
||||
const filterSchema = zod.object({
|
||||
type: zod.enum(['all', '3', '1', '2']).default('all'),
|
||||
@@ -29,10 +29,6 @@ type FilterSchema = zod.infer<typeof filterSchema>
|
||||
export type BillsPageProps = {}
|
||||
|
||||
export default function BillsPage(props: BillsPageProps) {
|
||||
// ======================
|
||||
// 查询
|
||||
// ======================
|
||||
|
||||
const [status, setStatus] = useStatus()
|
||||
const [data, setData] = useState<PageRecord<Bill>>({
|
||||
page: 1,
|
||||
@@ -70,10 +66,6 @@ export default function BillsPage(props: BillsPageProps) {
|
||||
refresh(1, 10).then()
|
||||
}, [])
|
||||
|
||||
// ======================
|
||||
// 筛选
|
||||
// ======================
|
||||
|
||||
const form = useForm<FilterSchema>({
|
||||
resolver: zodResolver(filterSchema),
|
||||
defaultValues: {
|
||||
@@ -86,14 +78,8 @@ export default function BillsPage(props: BillsPageProps) {
|
||||
await refresh(1, data.size)
|
||||
}
|
||||
|
||||
// ======================
|
||||
// render
|
||||
// ======================
|
||||
|
||||
return (
|
||||
<Page>
|
||||
|
||||
{/* 操作区 */}
|
||||
<section className="flex justify-between flex-wrap">
|
||||
<div>
|
||||
</div>
|
||||
@@ -151,7 +137,6 @@ export default function BillsPage(props: BillsPageProps) {
|
||||
</Form>
|
||||
</section>
|
||||
|
||||
{/* 数据表 */}
|
||||
<DataTable
|
||||
data={data.list}
|
||||
status={status}
|
||||
@@ -197,58 +182,36 @@ export default function BillsPage(props: BillsPageProps) {
|
||||
accessorKey: 'info', header: `账单详情`,
|
||||
},
|
||||
{
|
||||
accessorKey: 'status', header: `状态`, cell: ({row}) => (
|
||||
<>
|
||||
{row.original.trade && (
|
||||
row.original.trade.status === 0 ? (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex gap-1 items-center text-warn">
|
||||
<ClockIcon size={16}/>
|
||||
<span>订单待支付</span>
|
||||
<Link href="/admin/bills" className="text-sm underline text-blue-500">
|
||||
{row.original.trade.inner_no}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
) : row.original.trade.status === 1 ? (
|
||||
<div className="flex gap-1 items-center text-done">
|
||||
<CheckCircle size={16}/>
|
||||
<span>已完成</span>
|
||||
</div>
|
||||
) : row.original.trade.status === 2 ? (
|
||||
<div className="flex gap-1 items-center text-weak">
|
||||
<AlertCircle size={16}/>
|
||||
<span>已取消</span>
|
||||
</div>
|
||||
) : row.original.trade.status === 3 ? (
|
||||
<div className="flex gap-1 items-center text-fail">
|
||||
<AlertCircle size={16}/>
|
||||
<span>已退款</span>
|
||||
</div>
|
||||
) : (
|
||||
<span>-</span>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
accessorKey: 'status',
|
||||
header: `状态`,
|
||||
cell: ({row}) => (
|
||||
<PaymentStatusCell trade={{
|
||||
...row.original.trade,
|
||||
amount: row.original.amount,
|
||||
}}/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'amount', header: `支付信息`, cell: ({row}) => (
|
||||
<div className="flex gap-1">
|
||||
<span className="text-sm">
|
||||
{!row.original.trade && '余额'}
|
||||
{row.original.trade && row.original.trade.method === 1 && '支付宝'}
|
||||
{row.original.trade && row.original.trade.method === 2 && '微信'}
|
||||
</span>
|
||||
<span className={
|
||||
row.original.amount > 0 ? `text-green-400` : `text-orange-400`
|
||||
}>
|
||||
¥
|
||||
{row.original.amount}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
accessorKey: 'amount',
|
||||
header: '支付信息',
|
||||
cell: ({row}) => {
|
||||
const amount = typeof row.original.amount === 'string'
|
||||
? parseFloat(row.original.amount)
|
||||
: row.original.amount || 0
|
||||
return (
|
||||
<div className="flex gap-1">
|
||||
<span className="text-sm">
|
||||
{!row.original.trade && '余额'}
|
||||
{row.original.trade && row.original.trade.method === 1 && '支付宝'}
|
||||
{row.original.trade && row.original.trade.method === 2 && '微信'}
|
||||
</span>
|
||||
<span className={amount > 0 ? 'text-green-400' : 'text-orange-400'}>
|
||||
¥
|
||||
{amount.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at', header: '创建时间', cell: ({row}) => (
|
||||
|
||||
8
src/components/composites/payment/index.ts
Normal file
8
src/components/composites/payment/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// BillsPage负责数据获取和列表展示
|
||||
|
||||
// PaymentStatusCell负责支付状态显示和交互
|
||||
|
||||
// PaymentDialog负责支付过程处理
|
||||
// 导出支付相关组件
|
||||
export * from './payment-dialog'
|
||||
export * from './payment'
|
||||
157
src/components/composites/payment/payment-dialog.tsx
Normal file
157
src/components/composites/payment/payment-dialog.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
'use client'
|
||||
import {useEffect, useRef, useState, useMemo} from 'react'
|
||||
import * as qrcode from 'qrcode'
|
||||
import {Dialog, DialogContent, DialogHeader, DialogTitle} from '@/components/ui/dialog'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {Loader, CheckCircle} from 'lucide-react'
|
||||
import {toast} from 'sonner'
|
||||
import wechat from '@/components/composites/purchase/_assets/wechat.svg'
|
||||
import alipay from '@/components/composites/purchase/_assets/alipay.svg'
|
||||
import Image from 'next/image'
|
||||
import {completeResource} from '@/actions/resource'
|
||||
|
||||
export function PaymentDialog({trade, open, onOpenChange}: {
|
||||
trade: {
|
||||
inner_no: string
|
||||
method: number
|
||||
pay_url: string
|
||||
amount?: number
|
||||
}
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [paymentVerified, setPaymentVerified] = useState(false)
|
||||
|
||||
const paymentInfo = useMemo(() => {
|
||||
return trade.method === 1 ? {
|
||||
icon: alipay,
|
||||
name: '支付宝',
|
||||
} : {
|
||||
icon: wechat,
|
||||
name: '微信支付',
|
||||
}
|
||||
}, [trade.method])
|
||||
|
||||
const canvas = useRef<HTMLCanvasElement>(null)
|
||||
// 生成微信二维码
|
||||
useEffect(() => {
|
||||
if (!open || !canvas.current || trade.method === 1) return
|
||||
qrcode.toCanvas(canvas.current, trade.pay_url, {
|
||||
width: 200,
|
||||
margin: 0,
|
||||
}).catch((err) => {
|
||||
console.error('生成二维码失败:', err)
|
||||
toast.error('生成支付二维码失败')
|
||||
})
|
||||
}, [open, trade.method, trade.pay_url])
|
||||
|
||||
// 支付成功后自动关闭
|
||||
useEffect(() => {
|
||||
if (paymentVerified) {
|
||||
const timer = setTimeout(() => {
|
||||
onOpenChange(false)
|
||||
setPaymentVerified(false)
|
||||
}, 2000)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [paymentVerified, onOpenChange])
|
||||
|
||||
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)
|
||||
}
|
||||
catch (e) {
|
||||
toast.error('支付验证失败', {
|
||||
description: (e as Error).message,
|
||||
})
|
||||
}
|
||||
finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent onOpenAutoFocus={() => {
|
||||
if (canvas.current && trade.pay_url) {
|
||||
qrcode.toCanvas(canvas.current, trade.pay_url, {width: 200})
|
||||
}
|
||||
}}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex gap-2 items-center">
|
||||
{paymentInfo.icon && (
|
||||
<Image
|
||||
src={paymentInfo.icon}
|
||||
alt={`${paymentInfo.name} logo`}
|
||||
width={24}
|
||||
height={24}
|
||||
className="rounded-md"
|
||||
/>
|
||||
)}
|
||||
<span>{paymentInfo.name}</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
{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-3">
|
||||
<div className="bg-gray-100 size-50 flex items-center justify-center">
|
||||
{trade.method === 1 ? (
|
||||
<iframe src={trade.pay_url} className="w-full h-full"/>
|
||||
) : (
|
||||
<canvas ref={canvas} className="w-full h-full"/>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 text-center">
|
||||
请使用
|
||||
{trade.method === 1 ? '支付宝' : '微信'}
|
||||
扫码支付
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-center space-y-2 w-full">
|
||||
<p className="text-sm font-medium">
|
||||
支付金额:
|
||||
<span className="text-accent">
|
||||
{typeof trade.amount === 'number'
|
||||
? trade.amount.toFixed(2)
|
||||
: '0.00'}
|
||||
元
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
订单号:
|
||||
{trade.inner_no}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!paymentVerified && (
|
||||
<div className="flex justify-center gap-4">
|
||||
<Button onClick={handleComplete} disabled={loading}>
|
||||
{loading && <Loader className="animate-spin mr-2"/>}
|
||||
已完成支付
|
||||
</Button>
|
||||
<Button theme="outline" onClick={() => onOpenChange(false)}>关闭</Button>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
228
src/components/composites/payment/payment.tsx
Normal file
228
src/components/composites/payment/payment.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
'use client'
|
||||
import {useState} from 'react'
|
||||
import {Dialog, DialogContent} from '@/components/ui/dialog'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {CheckCircle, AlertCircle, ClockIcon} from 'lucide-react'
|
||||
import {format} from 'date-fns'
|
||||
import Link from 'next/link'
|
||||
import Image from 'next/image'
|
||||
import wechat from '@/components/composites/purchase/_assets/wechat.svg'
|
||||
import alipay from '@/components/composites/purchase/_assets/alipay.svg'
|
||||
import {usePlatformType, Platform} from '@/lib/models/trade'
|
||||
import {PaymentDialog} from './payment-dialog'
|
||||
|
||||
export function PaymentStatusCell({trade}: {
|
||||
trade?: {
|
||||
inner_no: string
|
||||
method: number
|
||||
pay_url?: string
|
||||
status?: number
|
||||
amount?: number | string
|
||||
}
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [paymentFailed, setPaymentFailed] = useState(false)
|
||||
const platform = usePlatformType()
|
||||
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
if (!trade?.pay_url) return
|
||||
|
||||
if (platform === Platform.Desktop) {
|
||||
setOpen(true)
|
||||
}
|
||||
else {
|
||||
setConfirmOpen(true)
|
||||
}
|
||||
}
|
||||
|
||||
const handleConfirmPayment = () => {
|
||||
setConfirmOpen(false)
|
||||
if (!trade?.pay_url) return
|
||||
const redirectTime = Date.now()
|
||||
window.location.href = trade.pay_url
|
||||
const checkPaymentStatus = () => {
|
||||
if (Date.now() - redirectTime > 3000) {
|
||||
setPaymentFailed(true)
|
||||
}
|
||||
}
|
||||
setTimeout(checkPaymentStatus, 3000)
|
||||
}
|
||||
|
||||
if (!trade || trade.status !== 0) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
{trade?.status === 1 ? (
|
||||
<CheckCircle size={16} className="text-done"/>
|
||||
) : trade?.status === 2 ? (
|
||||
<AlertCircle size={16} className="text-weak"/>
|
||||
) : trade?.status === 3 ? (
|
||||
<AlertCircle size={16} className="text-fail"/>
|
||||
) : null}
|
||||
<span>
|
||||
{trade?.status === 1 ? '已完成'
|
||||
: trade?.status === 2 ? '已取消'
|
||||
: trade?.status === 3 ? '已退款' : '-'}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (paymentFailed) {
|
||||
return (
|
||||
<Dialog open={paymentFailed} onOpenChange={setPaymentFailed}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<div className="text-center mb-6">
|
||||
<div className="inline-flex items-center justify-center h-16 w-16 rounded-full bg-primary/10 text-primary mb-4">
|
||||
<i className="fa fa-credit-card text-2xl"></i>
|
||||
</div>
|
||||
<h3 className="text-xl font-bold text-neutral-700 mb-2">支付失败</h3>
|
||||
<p className="text-neutral-500">未能成功唤起支付App,请检查是否已安装相关应用或选择其他支付方式。</p>
|
||||
</div>
|
||||
<div className="space-y-3 py-4 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">订单号</span>
|
||||
<span>{trade.inner_no}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">支付方式</span>
|
||||
<span>
|
||||
{trade.method === 1 ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Image
|
||||
src={alipay}
|
||||
alt="支付宝logo"
|
||||
width={16}
|
||||
height={16}
|
||||
className="rounded-md"
|
||||
/>
|
||||
<span>支付宝</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Image
|
||||
src={wechat}
|
||||
alt="微信支付logo"
|
||||
width={16}
|
||||
height={16}
|
||||
className="rounded-md"
|
||||
/>
|
||||
<span>微信支付</span>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">支付金额</span>
|
||||
<span className="font-medium text-red-500">
|
||||
¥
|
||||
{typeof trade.amount === 'string'
|
||||
? parseFloat(trade.amount).toFixed(2)
|
||||
: (trade.amount || 0).toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">支付时间</span>
|
||||
<span>{format(new Date(), 'yyyy-MM-dd HH:mm:ss')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center mt-4">
|
||||
<Button className="w-full max-w-[200px]" onClick={() => setPaymentFailed(false)} >完成</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
if (!trade.inner_no || !trade.method || !trade.pay_url) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClockIcon size={16} className="text-warn"/>
|
||||
<span>订单异常</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClockIcon size={16} className="text-warn"/>
|
||||
<span>订单待支付</span>
|
||||
<Link
|
||||
href="#"
|
||||
onClick={handleClick}
|
||||
className="text-sm underline text-blue-500"
|
||||
passHref
|
||||
>
|
||||
{trade.inner_no}
|
||||
</Link>
|
||||
<PaymentDialog
|
||||
trade={{
|
||||
inner_no: trade.inner_no,
|
||||
method: trade.method,
|
||||
pay_url: trade.pay_url,
|
||||
amount: typeof trade.amount === 'string'
|
||||
? parseFloat(trade.amount)
|
||||
: trade.amount || 0,
|
||||
}}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
/>
|
||||
|
||||
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
|
||||
<DialogContent>
|
||||
<div className="text-center mb-6">
|
||||
<div className="inline-flex items-center justify-center h-16 w-16 rounded-full bg-primary/10 text-primary mb-4">
|
||||
<i className="fa fa-credit-card text-2xl"></i>
|
||||
</div>
|
||||
<h3 className="text-xl font-bold text-neutral-700 mb-2">确认支付</h3>
|
||||
<p className="text-neutral-500">请确认以下支付信息</p>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">订单号</span>
|
||||
<span>{trade.inner_no}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">支付方式</span>
|
||||
<span className="flex items-center gap-1">
|
||||
{trade.method === 1 ? (
|
||||
<Image
|
||||
src={alipay}
|
||||
alt="支付宝"
|
||||
width={16}
|
||||
height={16}
|
||||
className="rounded-md"
|
||||
/>
|
||||
) : (
|
||||
<Image
|
||||
src={wechat}
|
||||
alt="微信支付"
|
||||
width={16}
|
||||
height={16}
|
||||
className="rounded-md"
|
||||
/>
|
||||
)}
|
||||
{trade.method === 1 ? '支付宝' : '微信支付'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">支付金额</span>
|
||||
<span className="font-medium">
|
||||
¥
|
||||
{typeof trade.amount === 'string'
|
||||
? parseFloat(trade.amount).toFixed(2)
|
||||
: (trade.amount || 0).toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between gap-4">
|
||||
<Button theme="outline" className="flex-1" onClick={() => setConfirmOpen(false)}> 取消 </Button>
|
||||
<Button className="flex-1" onClick={handleConfirmPayment}> 确认并支付 </Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ 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'
|
||||
|
||||
export type PayProps = {
|
||||
method: 'alipay' | 'wechat' | 'balance'
|
||||
@@ -24,7 +25,7 @@ export type PayProps = {
|
||||
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)
|
||||
@@ -44,15 +45,32 @@ export default function Pay(props: PayProps) {
|
||||
return
|
||||
}
|
||||
|
||||
// 根据平台类型设置支付方法
|
||||
let paymentMethod: PaymentMethod
|
||||
if (platform === Platform.Desktop) {
|
||||
paymentMethod = PaymentMethod.Sft
|
||||
}
|
||||
else {
|
||||
// 移动端根据选择的支付方式设置
|
||||
paymentMethod = props.method === 'alipay'
|
||||
? PaymentMethod.SftAlipay
|
||||
: PaymentMethod.SftWeChat
|
||||
}
|
||||
|
||||
const method = {
|
||||
alipay: 1,
|
||||
wechat: 2,
|
||||
alipay: PaymentMethod.Alipay,
|
||||
wechat: PaymentMethod.WeChat,
|
||||
}[props.method]
|
||||
|
||||
const resp = await prepareResource({
|
||||
const res = {
|
||||
...props.resource,
|
||||
method,
|
||||
})
|
||||
payment_method: paymentMethod,
|
||||
payment_platform: platform, // 使用检测到的平台类型
|
||||
}
|
||||
console.log(res, 'reresp')
|
||||
const resp = await prepareResource(res)
|
||||
console.log(resp, 'resp')
|
||||
|
||||
if (!resp.success) {
|
||||
toast.error(`创建订单失败: ${resp.message}`)
|
||||
setOpen(false)
|
||||
|
||||
@@ -17,15 +17,20 @@ import {zodResolver} from '@hookform/resolvers/zod'
|
||||
import {toast} from 'sonner'
|
||||
import wechat from '@/components/composites/purchase/_assets/wechat.svg'
|
||||
import alipay from '@/components/composites/purchase/_assets/alipay.svg'
|
||||
import {useEffect, useRef, useState} from 'react'
|
||||
import {useEffect, useMemo, useRef, useState} from 'react'
|
||||
import {Loader} from 'lucide-react'
|
||||
import {RechargeByAlipay, RechargeByAlipayConfirm, RechargeByWechat, RechargeByWechatConfirm} from '@/actions/user'
|
||||
import {RechargeByPay, RechargeByAlipayConfirm, RechargeByWechat, RechargeByWechatConfirm} from '@/actions/user'
|
||||
import * as qrcode from 'qrcode'
|
||||
import {useProfileStore} from '@/components/providers/StoreProvider'
|
||||
import {merge} from '@/lib/utils'
|
||||
import {
|
||||
Platform,
|
||||
PAYMENT_METHODS,
|
||||
usePlatformType,
|
||||
} from '@/lib/models/trade'
|
||||
|
||||
const schema = zod.object({
|
||||
method: zod.enum(['alipay', 'wechat']),
|
||||
method: zod.enum(['alipay', 'wechat', 'sft', 'sftAlipay', 'sftWeChat']),
|
||||
amount: zod.number().min(1, '充值金额必须大于 0'),
|
||||
})
|
||||
|
||||
@@ -39,7 +44,7 @@ export type RechargeModelProps = {
|
||||
|
||||
export default function RechargeModal(props: RechargeModelProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const platform = usePlatformType()
|
||||
const form = useForm<Schema>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
@@ -57,55 +62,66 @@ export default function RechargeModal(props: RechargeModelProps) {
|
||||
pay_url: string
|
||||
}>()
|
||||
|
||||
// 获取当前平台可用的支付方法
|
||||
const availableMethods = useMemo(() => {
|
||||
console.log(PAYMENT_METHODS, 'PAYMENT_METHODS')
|
||||
|
||||
return Object.values(PAYMENT_METHODS)
|
||||
.filter(method => method.availablePlatforms.includes(platform))
|
||||
.map(method => ({
|
||||
value: method.formValue,
|
||||
name: method.name,
|
||||
icon: method.icon,
|
||||
}))
|
||||
}, [platform])
|
||||
const canvas = useRef<HTMLCanvasElement>(null)
|
||||
useEffect(() => {
|
||||
if (canvas.current && payInfo) {
|
||||
qrcode.toCanvas(canvas.current, payInfo.pay_url, {
|
||||
width: 200,
|
||||
margin: 0,
|
||||
})
|
||||
}
|
||||
}, [payInfo])
|
||||
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 {
|
||||
switch (data.method) {
|
||||
case 'alipay':
|
||||
const aliRes = await RechargeByAlipay({
|
||||
amount: data.amount.toString(),
|
||||
})
|
||||
if (aliRes.success) {
|
||||
setStep(1)
|
||||
setPayInfo(aliRes.data)
|
||||
}
|
||||
else {
|
||||
toast.error(`创建订单失败`, {
|
||||
description: aliRes.message,
|
||||
})
|
||||
}
|
||||
break
|
||||
case 'wechat':
|
||||
const weRes = await RechargeByWechat({
|
||||
amount: data.amount.toString(),
|
||||
})
|
||||
if (weRes.success) {
|
||||
setStep(1)
|
||||
setPayInfo(weRes.data)
|
||||
}
|
||||
else {
|
||||
toast.error(`创建订单失败`, {
|
||||
description: weRes.message,
|
||||
})
|
||||
}
|
||||
break
|
||||
const paymentMethod = Object.entries(PAYMENT_METHODS).find(
|
||||
([_, config]) => config.formValue === data.method,
|
||||
)
|
||||
console.log(paymentMethod, 'paymentMethod')
|
||||
|
||||
if (!paymentMethod) {
|
||||
throw new Error('无效的支付方式')
|
||||
}
|
||||
const resp = {
|
||||
amount: data.amount.toString(),
|
||||
platform: platform,
|
||||
method: paymentMethod[1].actualMethod,
|
||||
}
|
||||
console.log(resp, 'resp')
|
||||
|
||||
// const result = await RechargeByPay({
|
||||
// amount: data.amount.toString(),
|
||||
// platform: platform,
|
||||
// method: parseInt(paymentMethod[0]) as PaymentMethod,
|
||||
// })
|
||||
const result = await RechargeByPay(resp)
|
||||
console.log(result, 'result')
|
||||
|
||||
if (result.success) {
|
||||
setStep(1)
|
||||
setPayInfo(result.data)
|
||||
}
|
||||
else {
|
||||
throw new Error(result.message)
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e)
|
||||
toast.error(`创建订单失败`, {
|
||||
description: (e as Error).message,
|
||||
catch (error) {
|
||||
toast.error('创建订单失败', {
|
||||
description: error instanceof Error ? error.message : '未知错误',
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -151,6 +167,7 @@ export default function RechargeModal(props: RechargeModelProps) {
|
||||
setOpen(false)
|
||||
setPayInfo(undefined)
|
||||
setStep(0)
|
||||
form.reset()
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -159,7 +176,7 @@ export default function RechargeModal(props: RechargeModelProps) {
|
||||
<Button theme="accent" type="button" className={merge(`px-4 h-8`, props.classNames?.trigger)}>去充值</Button>
|
||||
</DialogTrigger>
|
||||
|
||||
<DialogContent>
|
||||
<DialogContent className={platform === Platform.Mobile ? 'max-w-[95vw]' : 'max-w-md'}>
|
||||
<DialogTitle className="flex flex-col gap-2">
|
||||
充值中心
|
||||
</DialogTitle>
|
||||
@@ -235,22 +252,18 @@ export default function RechargeModal(props: RechargeModelProps) {
|
||||
defaultValue={field.value}
|
||||
onValueChange={field.onChange}
|
||||
className="flex gap-2">
|
||||
<FormOption
|
||||
id={`${id}-alipay`}
|
||||
value="alipay"
|
||||
compare={field.value}
|
||||
className="flex-1 flex-row justify-center items-center">
|
||||
<Image src={alipay} alt="支付宝 logo" className="w-6 h-6"/>
|
||||
<span>支付宝</span>
|
||||
</FormOption>
|
||||
<FormOption
|
||||
id={`${id}-wechat`}
|
||||
value="wechat"
|
||||
compare={field.value}
|
||||
className="flex-1 flex-row justify-center items-center">
|
||||
<Image src={wechat} alt="微信 logo" className="w-6 h-6"/>
|
||||
<span>微信</span>
|
||||
</FormOption>
|
||||
{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>
|
||||
|
||||
136
src/lib/models/trade.ts
Normal file
136
src/lib/models/trade.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import {StaticImageData} from 'next/image'
|
||||
import {useEffect, useState} from 'react'
|
||||
import zod from 'zod'
|
||||
import wechat from '@/components/composites/purchase/_assets/wechat.svg'
|
||||
import alipay from '@/components/composites/purchase/_assets/alipay.svg'
|
||||
|
||||
// 支付方法枚举
|
||||
export const PaymentMethod = {
|
||||
Alipay: 1,
|
||||
WeChat: 2,
|
||||
Sft: 3,
|
||||
SftAlipay: 4,
|
||||
SftWeChat: 5,
|
||||
} as const
|
||||
|
||||
// 平台枚举
|
||||
export const Platform = {
|
||||
Desktop: 1,
|
||||
Mobile: 2,
|
||||
} as const
|
||||
|
||||
// 定义类型
|
||||
export type PaymentMethod = typeof PaymentMethod[keyof typeof PaymentMethod]
|
||||
export type Platform = typeof Platform[keyof typeof Platform]
|
||||
|
||||
// 支付方法配置类型
|
||||
export type PaymentMethodConfig = {
|
||||
name: string
|
||||
icon: StaticImageData | null
|
||||
formValue: string
|
||||
availablePlatforms: Platform[]
|
||||
actualMethod: PaymentMethod
|
||||
}
|
||||
|
||||
// 支付方法配置
|
||||
export const PAYMENT_METHODS: Record<PaymentMethod, PaymentMethodConfig> = {
|
||||
[PaymentMethod.Alipay]: {
|
||||
name: '支付宝',
|
||||
icon: alipay,
|
||||
formValue: 'alipay',
|
||||
availablePlatforms: [Platform.Desktop],
|
||||
actualMethod: PaymentMethod.Sft,
|
||||
},
|
||||
[PaymentMethod.WeChat]: {
|
||||
name: '微信支付',
|
||||
icon: wechat,
|
||||
formValue: 'wechat',
|
||||
availablePlatforms: [Platform.Desktop],
|
||||
actualMethod: PaymentMethod.Sft,
|
||||
},
|
||||
[PaymentMethod.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,
|
||||
},
|
||||
} as const
|
||||
|
||||
// 设备检测Hook
|
||||
export const usePlatformType = (): Platform => {
|
||||
const [platform, setPlatform] = useState<Platform>(Platform.Desktop)
|
||||
|
||||
useEffect(() => {
|
||||
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
|
||||
}
|
||||
// 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({
|
||||
method: zod.enum(['alipay', 'wechat', 'sft', 'sftAlipay', 'sftWeChat']),
|
||||
amount: zod.number().min(1, '充值金额必须大于 0'),
|
||||
})
|
||||
|
||||
export type PaymentSchema = zod.infer<typeof paymentSchema>
|
||||
|
||||
// 支付请求参数类型
|
||||
export type PaymentRequest = {
|
||||
amount: string
|
||||
platform: Platform
|
||||
method: PaymentMethod
|
||||
}
|
||||
|
||||
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