feat: add online payment management and checkout
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-15 09:26:40 +08:00
parent 5353a4a128
commit dc2efcde08
41 changed files with 4855 additions and 21 deletions

46
frontend/src/api.test.ts Normal file
View File

@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { api, ApiError } from './api'
async function rejectedResponse(status?:unknown, detail?:unknown) {
return api.get('/payment-channels/alipay', {
adapter:async () => { throw {response:{status,data:{error:detail}},config:{secret:'request-secret'},request:{secret:'request-secret'}} },
}).catch((error:unknown) => error)
}
describe('API error interceptor', () => {
it('preserves Error.message compatibility and validated code/status without retaining raw request data', async () => {
const error = await rejectedResponse(503,{code:'payment_schema_unavailable',message:'Existing page message',secret:'raw-secret'})
expect(error).toBeInstanceOf(Error)
expect(error).toBeInstanceOf(ApiError)
expect(error).toMatchObject({message:'Existing page message',code:'payment_schema_unavailable',status:503})
expect(error).not.toHaveProperty('response')
expect(error).not.toHaveProperty('config')
expect(error).not.toHaveProperty('request')
expect(JSON.stringify(error)).not.toMatch(/raw-secret|request-secret/)
})
it.each([
['<script>secret</script>', '503'],
['a'.repeat(65), 600],
[{secret:'raw-secret'}, 401.5],
['SECRET PRIVATE KEY', null],
])('drops malformed metadata %j / %j', async (code,status) => {
const error = await rejectedResponse(status,{code,message:{secret:'raw-secret'}})
expect(error).toBeInstanceOf(ApiError)
expect(error).toMatchObject({message:'请求失败,请稍后重试'})
expect((error as ApiError).code).toBeUndefined()
expect((error as ApiError).status).toBeUndefined()
})
it('falls back safely when there is no response', async () => {
const error = await api.get('/payment-channels/wechat',{adapter:async () => { throw new Error('network internal detail') }}).catch((error:unknown) => error)
expect(error).toBeInstanceOf(ApiError)
expect(error).toMatchObject({message:'请求失败,请稍后重试'})
expect((error as ApiError).status).toBeUndefined()
})
it('leaves successful responses unchanged', async () => {
const response = await api.get('/me',{adapter:async config => ({data:{data:{username:'admin'}},status:200,statusText:'OK',headers:{},config})})
expect(response.data).toEqual({data:{username:'admin'}})
})
})

View File

@@ -0,0 +1,11 @@
import { beforeEach, expect, it, vi } from 'vitest'
const api = vi.hoisted(() => ({get:vi.fn(),put:vi.fn()}))
vi.mock('./api', () => ({api}))
import { getPaymentChannel, listPaymentOrders, savePaymentChannel } from './payments-api'
beforeEach(() => vi.resetAllMocks())
it('uses the authenticated admin client for payment order and channel configuration requests', async () => {
await listPaymentOrders(); expect(api.get).toHaveBeenCalledWith('/payment-orders')
await getPaymentChannel('alipay'); expect(api.get).toHaveBeenCalledWith('/payment-channels/alipay')
const value = {enabled:true,fields:{app_id:'app',seller_id:'seller',notify_url:'https://merchant.example/notify'},secrets:{private_key:'replacement'}}
await savePaymentChannel('alipay',value); expect(api.put).toHaveBeenCalledWith('/payment-channels/alipay',value)
})

View File

@@ -0,0 +1,42 @@
import axios from 'axios'
import type { PaymentChannel } from './orders-api'
import { api } from './api'
export type PaymentOrder = {
id:number; order_id:number; merchant_order_no:string; channel:PaymentChannel; channel_trade_no:string|null;
amount_cents:number; currency:string; status:string; order_status:string; license_id:number|null;
last_error:string|null; paid_at:string|null; created_at:string; expires_at:string;
}
export const listPaymentOrders = () => api.get<{data:PaymentOrder[]}>('/payment-orders')
// GET/PUT never return credential material; fields contains ordinary metadata only.
export type PaymentChannelMetadata = {
app_id:string; notify_url:string; seller_id?:string; mch_id?:string;
serial_no?:string; public_key_id?:string; platform_serial?:string;
}
export type PaymentChannelSecrets = {
private_key?:string; public_key?:string; platform_public_key?:string; api_v3_key?:string;
}
export type PaymentChannelConfiguration = {
channel:PaymentChannel; enabled?:boolean; configuration_source?:'environment'|'database'|'none';
version?:number|null; effective?:boolean; can_save?:boolean; required_settings?:string[];
fields:PaymentChannelMetadata;
secret_fields:{name:keyof PaymentChannelSecrets; configured:boolean}[];
}
export type PaymentChannelUpdate = {
enabled:boolean; fields:PaymentChannelMetadata; secrets:PaymentChannelSecrets;
}
export const getPaymentChannel = (channel:PaymentChannel) => api.get<{data:PaymentChannelConfiguration}>(`/payment-channels/${channel}`)
export const savePaymentChannel = (channel:PaymentChannel, value:PaymentChannelUpdate) => api.put<{data:PaymentChannelConfiguration}>(`/payment-channels/${channel}`, value)
const checkoutClient = axios.create({ baseURL: '/api/v1', timeout: 8000, withCredentials: false })
export type CheckoutPayment = { code_url:string; status:string; order_status:string; license_id:number|null; license_key:string; amount_cents:number; currency:string; channel:PaymentChannel }
export const getCheckoutPayment = (token:string) => checkoutClient.post<{data:CheckoutPayment}>('/payments/checkout', {token})
export function checkoutLink(value:string) {
const url = new URL(value, window.location.origin)
if (url.origin !== window.location.origin || url.pathname !== '/checkout' || url.search || !new URLSearchParams(url.hash.slice(1)).get('token')) {
throw new Error('付款链接无效')
}
return url.href
}

View File

@@ -0,0 +1,77 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import QRCode from 'qrcode'
const calls = vi.hoisted(() => ({ getCheckoutPayment:vi.fn() }))
vi.mock('../payments-api', () => calls)
import Checkout from './Checkout.vue'
import type { CheckoutPayment } from '../payments-api'
const pending:CheckoutPayment = {code_url:'alipays://platformapi/startapp?test=payment',status:'pending',order_status:'pending_payment',license_id:null,license_key:'',amount_cents:1234,currency:'CNY',channel:'alipay'}
const response = (value = pending) => ({data:{data:value}})
let qrImage = ''
let wrapper:ReturnType<typeof mount>|undefined
beforeEach(async () => { qrImage = await QRCode.toDataURL(pending.code_url, {width:280,margin:2,errorCorrectionLevel:'M'}); vi.useFakeTimers(); vi.resetAllMocks(); vi.spyOn(QRCode, 'toDataURL').mockImplementation((() => Promise.resolve(qrImage)) as typeof QRCode.toDataURL); window.history.replaceState({}, '', '/checkout#token=secret-checkout'); calls.getCheckoutPayment.mockResolvedValue(response()) })
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.useRealTimers(); vi.restoreAllMocks() })
describe('Checkout', () => {
it('uses the hash token, generates a real QR image, polls every 3 seconds and stops after issuance', async () => {
const storage = vi.spyOn(Storage.prototype, 'setItem')
wrapper = mount(Checkout); await flushPromises()
expect(calls.getCheckoutPayment).toHaveBeenCalledWith('secret-checkout')
expect(wrapper.get('img').attributes('src')).toBe(qrImage)
expect(QRCode.toDataURL).toHaveBeenCalledWith(pending.code_url, {width:280,margin:2,errorCorrectionLevel:'M'})
expect(wrapper.text()).toContain('12.34 CNY')
expect(storage).not.toHaveBeenCalled()
calls.getCheckoutPayment.mockResolvedValue(response({...pending,status:'paid',order_status:'issued',license_id:71,license_key:'issued-key'}))
await vi.advanceTimersByTimeAsync(2999); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1); await flushPromises()
expect(wrapper.get('input').element.value).toBe('issued-key'); expect(wrapper.text()).toContain('现有客户端');
const copy = vi.fn().mockResolvedValue(undefined); vi.stubGlobal('navigator', {...navigator, clipboard:{writeText:copy}})
await wrapper.get('button').trigger('click'); await flushPromises(); expect(copy).toHaveBeenCalledWith('issued-key'); vi.unstubAllGlobals()
expect(wrapper.text()).toContain('开通成功'); expect(wrapper.text()).toContain('71'); expect(wrapper.find('img').exists()).toBe(false)
await vi.advanceTimersByTimeAsync(9000); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(2)
})
it('does not submit a missing token or use query-string credentials', async () => {
window.history.replaceState({}, '', '/checkout?token=wrong')
wrapper = mount(Checkout); await flushPromises()
expect(wrapper.get('[role="alert"]').text()).toContain('缺少 token'); expect(calls.getCheckoutPayment).not.toHaveBeenCalled()
})
it('hides stale QR codes on query failure and retries without exposing API error content', async () => {
wrapper = mount(Checkout); await flushPromises()
calls.getCheckoutPayment.mockRejectedValueOnce(new Error('secret-checkout'))
await vi.advanceTimersByTimeAsync(3000); await flushPromises()
expect(wrapper.find('img').exists()).toBe(false); expect(wrapper.text()).not.toContain('secret-checkout')
await wrapper.get('button').trigger('click'); await flushPromises()
expect(wrapper.find('img').exists()).toBe(true)
wrapper.unmount(); wrapper = undefined
await vi.advanceTimersByTimeAsync(6000); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(3)
})
it('shows failed payments and permits a manual retry', async () => {
calls.getCheckoutPayment.mockResolvedValueOnce(response({...pending,status:'failed'}))
wrapper = mount(Checkout); await flushPromises()
expect(wrapper.text()).toContain('支付未完成'); expect(wrapper.find('img').exists()).toBe(false)
await vi.advanceTimersByTimeAsync(6000); expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(1)
await wrapper.get('button').trigger('click'); await flushPromises(); expect(wrapper.find('img').exists()).toBe(true)
})
it('asks administrators to inspect expired orders instead of promising a rebuild action', async () => {
calls.getCheckoutPayment.mockResolvedValueOnce(response({...pending,status:'expired'}))
wrapper = mount(Checkout); await flushPromises()
expect(wrapper.text()).toContain('联系管理员核查订单')
expect(wrapper.text()).not.toContain('重新创建付款链接')
})
it('stops polling when the administrator removed the authorization', async () => {
calls.getCheckoutPayment.mockResolvedValueOnce(response({...pending,status:'paid',order_status:'authorization_removed'}))
wrapper = mount(Checkout); await flushPromises()
expect(wrapper.text()).toContain('授权已被管理员移除,请联系管理员核查')
expect(wrapper.text()).not.toContain('开通成功')
expect(wrapper.find('img').exists()).toBe(false)
await vi.advanceTimersByTimeAsync(9000)
expect(calls.getCheckoutPayment).toHaveBeenCalledTimes(1)
})
it('ignores old in-flight responses when the hash token changes', async () => {
let resolve!:(value:ReturnType<typeof response>)=>void
calls.getCheckoutPayment.mockReturnValueOnce(new Promise(done => { resolve = done }))
wrapper = mount(Checkout); await flushPromises()
window.history.replaceState({}, '', '/checkout#token=new-token'); window.dispatchEvent(new Event('hashchange')); await flushPromises()
resolve(response({...pending,status:'paid',order_status:'issued'})); await flushPromises()
expect(wrapper.text()).not.toContain('开通成功'); expect(calls.getCheckoutPayment).toHaveBeenLastCalledWith('new-token')
})
})

View File

@@ -0,0 +1,71 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import QRCode from 'qrcode'
import { getCheckoutPayment, type CheckoutPayment } from '../payments-api'
const payment = ref<CheckoutPayment|null>(null), qr = ref(''), busy = ref(false), error = ref('')
const copyNotice = ref('')
async function copyLicenseKey() {
if (!payment.value?.license_key) return
try { await navigator.clipboard.writeText(payment.value.license_key); copyNotice.value = '授权密钥已复制' }
catch { copyNotice.value = '复制失败,请手动复制授权密钥' }
}
const issued = computed(() => payment.value?.order_status === 'issued')
const removed = computed(() => payment.value?.order_status === 'authorization_removed')
const failed = computed(() => ['failed', 'expired', 'cancelled', 'closed'].includes(payment.value?.status || ''))
let token = '', timer:ReturnType<typeof setTimeout>|undefined, generation = 0, disposed = false
function stopPolling() { clearTimeout(timer); timer = undefined }
async function load() {
if (!token || busy.value || disposed) return
stopPolling()
const current = generation
busy.value = true; error.value = ''
try {
const result = (await getCheckoutPayment(token)).data.data
if (disposed || current !== generation) return
payment.value = result
qr.value = ''
if (!issued.value && !removed.value && !failed.value && result.status !== 'paid' && result.code_url) {
const image = await QRCode.toDataURL(result.code_url, {width:280, margin:2, errorCorrectionLevel:'M'})
if (disposed || current !== generation) return
qr.value = image
}
if (!issued.value && !removed.value && !failed.value) timer = setTimeout(load, 3000)
} catch {
if (!disposed && current === generation) { qr.value = ''; error.value = '支付查询失败,请重试' }
} finally {
if (current === generation) busy.value = false
}
}
function readToken() {
generation++; stopPolling(); busy.value = false; payment.value = null; qr.value = ''; error.value = ''; copyNotice.value = ''
token = new URLSearchParams(window.location.hash.slice(1)).get('token') || ''
if (!token) { error.value = '付款链接无效,缺少 token'; return }
void load()
}
onMounted(() => { readToken(); window.addEventListener('hashchange', readToken) })
onUnmounted(() => { disposed = true; generation++; token = ''; stopPolling(); window.removeEventListener('hashchange', readToken) })
</script>
<template>
<main class="checkout">
<h1>订单付款</h1>
<p v-if="error" role="alert">{{ error }}</p>
<template v-if="payment">
<p class="amount">{{ (payment.amount_cents / 100).toFixed(2) }} {{ payment.currency }}</p>
<p>{{ payment.channel === 'alipay' ? '支付宝' : '微信支付' }}</p>
<template v-if="issued"><h2 role="status">开通成功</h2><p v-if="payment.license_id">授权 ID:{{ payment.license_id }}</p><template v-if="payment.license_key"><label>授权密钥<input :value="payment.license_key" readonly aria-label="授权密钥"></label><p><button @click="copyLicenseKey">复制授权密钥</button></p><p v-if="copyNotice" role="status">{{ copyNotice }}</p></template><p>授权已开通,请在现有客户端输入授权密钥完成激活。</p></template>
<p v-else-if="removed" role="status">授权已被管理员移除,请联系管理员核查</p>
<p v-else-if="failed" role="status">支付未完成或已失效,请重试查询;如仍无法付款,请联系管理员核查订单。</p>
<template v-else>
<p role="status">{{ payment.status === 'paid' || payment.order_status === 'paid' ? '已收款,正在开通授权' : '请使用对应支付应用扫码付款' }}</p>
<img v-if="qr" :src="qr" alt="付款二维码" width="280" height="280">
<p v-if="!qr && !busy && !error && payment.status !== 'paid'">暂未获取到付款二维码,正在查询</p>
</template>
</template>
<p v-if="busy" role="status">正在查询支付状态…</p>
<button v-if="token && (error || failed)" :disabled="busy" @click="load">重试查询</button>
</main>
</template>
<style scoped>
.checkout{max-width:520px;margin:40px auto;padding:28px;text-align:center;background:#fff;border-radius:12px;color:#202124}h1{font-size:24px}.amount{font-size:28px;font-weight:600}img{max-width:100%;height:auto}input{display:block;width:100%;box-sizing:border-box;padding:10px;margin-top:8px}button{padding:10px 20px;cursor:pointer}p[role=alert]{color:#a4262c}
</style>

View File

@@ -0,0 +1,219 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { defineComponent, nextTick } from 'vue'
import ElementPlus, { ElPagination } from 'element-plus'
import { formatDateTime } from '../date-format'
import { ApiError } from '../api'
const calls = vi.hoisted(() => ({getPaymentChannel:vi.fn(),savePaymentChannel:vi.fn(),listPaymentOrders:vi.fn()}))
vi.mock('../payments-api', () => calls)
import PaymentsPanel from './PaymentsPanel.vue'
const row = {id:1,order_id:7,merchant_order_no:'merchant-7',channel:'alipay',channel_trade_no:null,amount_cents:12345,currency:'CNY',status:'paid',order_status:'issued',license_id:8,last_error:'secret-token-and-license-key',paid_at:'2026-10-14T04:00:00Z',created_at:'2026-10-14T03:00:00Z',expires_at:'2026-10-14T05:00:00Z',token:'hidden-token',license_key:'hidden-license'}
const configuration = (channel:string) => ({channel,enabled:channel === 'alipay',configuration_source:'database',fields:channel === 'alipay' ? {app_id:'app-1',seller_id:'seller-1',notify_url:'https://merchant.example/notify'} : {app_id:'wx-1',mch_id:'mch-1',serial_no:'serial-1',platform_serial:'platform-1',notify_url:'https://merchant.example/wechat'},secret_fields:(channel === 'alipay' ? ['private_key','public_key'] : ['private_key','platform_public_key','api_v3_key']).map(name => ({name,configured:true}))})
const options = {global:{plugins:[ElementPlus],stubs:{
'el-button':defineComponent({props:['disabled'],emits:['click'],template:'<button :disabled="disabled" @click="$emit(\'click\',$event)"><slot/></button>'}),
'router-link':defineComponent({props:['to'],template:'<a :href="to"><slot/></a>'}),
'el-input':defineComponent({inheritAttrs:false,props:['modelValue'],emits:['update:modelValue'],template:'<input v-bind="$attrs" :value="modelValue" @input="$emit(\'update:modelValue\',$event.target.value)">' }),
'el-select':defineComponent({inheritAttrs:false,props:['modelValue'],emits:['update:modelValue'],template:'<select v-bind="$attrs" :value="modelValue" @change="$emit(\'update:modelValue\',$event.target.value)"><slot/></select>'}),
'el-option':defineComponent({props:['value','label'],template:'<option :value="value">{{ label }}</option>'}),
}}}
beforeEach(() => { vi.resetAllMocks(); calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:configuration(channel)}})); calls.savePaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:configuration(channel)}})); calls.listPaymentOrders.mockResolvedValue({data:{data:[row,{...row,id:2,order_id:9,merchant_order_no:'merchant-9',channel:'wechat',status:'created',order_status:'pending_payment',last_error:null}]}}) })
describe('PaymentsPanel', () => {
it('collapses channel forms by default and expands them independently', async () => {
const wrapper = mount(PaymentsPanel,{...options,attachTo:document.body}); await flushPromises()
const alipayToggle = wrapper.get('[aria-label="支付宝渠道配置"]')
const wechatToggle = wrapper.get('[aria-label="微信支付渠道配置"]')
expect(alipayToggle.attributes('aria-expanded')).toBe('false')
expect(wechatToggle.attributes('aria-expanded')).toBe('false')
await alipayToggle.trigger('click')
expect(alipayToggle.attributes('aria-expanded')).toBe('true')
expect(wrapper.get('#channel-details-alipay').isVisible()).toBe(true)
expect(wrapper.get('#channel-details-wechat').isVisible()).toBe(false)
await wechatToggle.trigger('click')
expect(wrapper.get('#channel-details-wechat').isVisible()).toBe(true)
await alipayToggle.trigger('click')
expect(wrapper.get('#channel-details-alipay').isVisible()).toBe(false)
wrapper.unmount()
})
it('shows editable channel configuration, formats records and filters the recent results', async () => {
const wrapper = mount(PaymentsPanel,options); await flushPromises()
expect(wrapper.text()).toContain('已启用'); expect(wrapper.text()).toContain('未启用')
expect(wrapper.text()).toContain('应用 ID'); expect(wrapper.text()).toContain('留空保留现值')
expect(wrapper.text()).toContain('123.45 CNY'); expect(wrapper.text()).toContain(formatDateTime(row.created_at))
expect(wrapper.text()).not.toMatch(/secret-token|hidden-token|hidden-license/)
expect(wrapper.get('a').attributes('href')).toBe('/orders')
await wrapper.get('[aria-label="支付渠道筛选"]').setValue('wechat')
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(1); expect(wrapper.text()).not.toContain('merchant-7')
expect(wrapper.get('.el-table__body tbody tr').text()).toContain('待支付')
expect(wrapper.get('.el-table__body tbody tr').text()).not.toContain('未知状态')
expect(wrapper.get('[aria-label="支付状态筛选"] option[value="created"]').text()).toBe('待支付')
await wrapper.get('[aria-label="支付状态筛选"]').setValue('paid')
expect(wrapper.text()).toContain('暂无符合条件')
await wrapper.findAll('button').find(button=>button.text()==='重置筛选')!.trigger('click')
await wrapper.get('[aria-label="搜索支付流水"]').setValue('merchant-7')
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(1)
await wrapper.findAll('button').find(button=>button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
expect(calls.listPaymentOrders).toHaveBeenCalledTimes(2); wrapper.unmount()
})
it('handles partial failure safely and allows refresh recovery', async () => {
calls.listPaymentOrders.mockRejectedValueOnce(new Error('sensitive-token'))
const wrapper = mount(PaymentsPanel,options); await flushPromises()
expect(wrapper.text()).toContain('应用 ID'); expect(wrapper.get('[role="alert"]').text()).toContain('支付流水加载失败')
expect(wrapper.text()).not.toContain('sensitive-token')
await wrapper.findAll('button').find(button=>button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
expect(wrapper.find('[role="alert"]').exists()).toBe(false); expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(2); wrapper.unmount()
})
it('shows loading then empty results', async () => {
let resolve!: (value:unknown) => void
calls.listPaymentOrders.mockReturnValueOnce(new Promise(r=>{resolve=r}))
const wrapper = mount(PaymentsPanel,options)
await nextTick()
expect(wrapper.text()).toContain('正在加载支付数据')
resolve({data:{data:[]}}); await flushPromises()
expect(wrapper.text()).toContain('暂无符合条件'); wrapper.unmount()
})
it('paginates loaded records and resets the page after filtering and refresh', async () => {
const records = Array.from({length:25}, (_,index)=>({...row,id:index+1,merchant_order_no:`merchant-${index+1}`}))
calls.listPaymentOrders.mockResolvedValue({data:{data:records}})
const wrapper = mount(PaymentsPanel,options); await flushPromises()
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(20)
expect(wrapper.text()).toContain('每页 20 条')
wrapper.findComponent(ElPagination).vm.$emit('update:current-page',2); await nextTick()
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(5)
expect(wrapper.text()).toContain('merchant-25')
await wrapper.get('[aria-label="搜索支付流水"]').setValue('merchant-1'); await nextTick()
expect(wrapper.findComponent(ElPagination).props('currentPage')).toBe(1)
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(11)
await wrapper.findAll('button').find(button=>button.text()==='重置筛选')!.trigger('click')
wrapper.findComponent(ElPagination).vm.$emit('update:current-page',2); await nextTick()
await wrapper.findAll('button').find(button=>button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
expect(wrapper.findComponent(ElPagination).props('currentPage')).toBe(1)
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(20)
wrapper.unmount()
})
it('loads ordinary fields but never echoes returned secret material, and omits blank secrets on save', async () => {
calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:{...configuration(channel),secrets:{private_key:'server-secret'},fields:{...configuration(channel).fields,private_key:'server-secret'},secret_fields:configuration(channel).secret_fields.map(flag => ({...flag,value:'server-secret'}))}}}))
const wrapper = mount(PaymentsPanel,options); await flushPromises()
expect(calls.getPaymentChannel).toHaveBeenCalledWith('alipay'); expect(calls.getPaymentChannel).toHaveBeenCalledWith('wechat')
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝应用 ID"]').element.value).toBe('app-1')
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
expect(wrapper.html()).not.toContain('server-secret')
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('app-edited')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
expect(calls.savePaymentChannel).toHaveBeenCalledWith('alipay',{enabled:true,fields:{app_id:'app-edited',seller_id:'seller-1',notify_url:'https://merchant.example/notify'},secrets:{}})
expect(wrapper.text()).toContain('配置保存成功'); expect(wrapper.text()).toContain('不代表真实交易联调通过')
wrapper.unmount()
})
it('submits replacement credentials once, clears inputs, blocks duplicate save and refresh while saving', async () => {
let resolve!: (value:unknown) => void
calls.savePaymentChannel.mockReturnValueOnce(new Promise(r => {resolve=r}))
const wrapper = mount(PaymentsPanel,options); await flushPromises()
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit')
expect(calls.savePaymentChannel.mock.calls[0]![1].secrets).toEqual({private_key:'replacement-secret'})
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
expect(wrapper.html()).not.toContain('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit')
expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1)
expect(wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.attributes('disabled')).toBeDefined()
resolve({data:{data:configuration('alipay')}}); await flushPromises()
expect(wrapper.text()).toContain('配置保存成功'); wrapper.unmount()
})
it('shows safe save failures, retains ordinary drafts and clears credentials for retry', async () => {
calls.savePaymentChannel.mockRejectedValueOnce(new Error('replacement-secret raw PEM database-error'))
const wrapper = mount(PaymentsPanel,options); await flushPromises()
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('draft-app')
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
expect(wrapper.get('[role="alert"]').text()).toContain('服务端校验未通过')
expect(wrapper.text()).not.toContain('配置保存成功'); expect(wrapper.html()).not.toMatch(/replacement-secret|raw PEM|database-error/)
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝应用 ID"]').element.value).toBe('draft-app')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
expect(wrapper.find('[role="alert"]').exists()).toBe(false); expect(wrapper.text()).toContain('配置保存成功'); wrapper.unmount()
})
it('validates required fields, HTTPS callbacks, missing secrets and APIv3 byte length before saving', async () => {
calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:{...configuration(channel),secret_fields:configuration(channel).secret_fields.map(flag => ({...flag,configured:false}))}}}))
const wrapper = mount(PaymentsPanel,options); await flushPromises()
const alipay = wrapper.get('[data-channel="alipay"] form')
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue(''); await alipay.trigger('submit')
expect(wrapper.text()).toContain('请填写应用 ID')
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('app')
await wrapper.get('[aria-label="支付宝HTTPS 通知地址"]').setValue('http://merchant.example'); await alipay.trigger('submit')
expect(wrapper.text()).toContain('通知地址必须')
await wrapper.get('[aria-label="支付宝HTTPS 通知地址"]').setValue('https://merchant.example'); await alipay.trigger('submit')
expect(wrapper.text()).toContain('请填写商户私钥')
await wrapper.get('[aria-label="微信支付启用渠道"]').setValue(true)
await wrapper.get('[aria-label="微信支付商户私钥"]').setValue('private')
await wrapper.get('[aria-label="微信支付平台证书 / 验签公钥(兼容)"]').setValue('public')
await wrapper.get('[aria-label="微信支付APIv3 密钥"]').setValue('短密钥')
await wrapper.get('[data-channel="wechat"] form').trigger('submit')
expect(wrapper.text()).toContain('APIv3 密钥必须为 32 字节'); expect(calls.savePaymentChannel).not.toHaveBeenCalled()
wrapper.unmount()
})
it('accepts platform-only settings and validates the optional public-key pair', async () => {
const wrapper = mount(PaymentsPanel,options); await flushPromises()
await wrapper.get('[aria-label="微信支付启用渠道"]').setValue(true)
const form = wrapper.get('[data-channel="wechat"] form')
await form.trigger('submit'); await flushPromises()
expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1)
await wrapper.get('[aria-label="微信支付启用渠道"]').setValue(true)
await wrapper.get('[aria-label="微信支付微信支付公钥 ID(推荐)"]').setValue('PUB_KEY_ID_test')
await form.trigger('submit')
expect(wrapper.text()).toContain('请完整填写微信支付公钥 ID 和微信支付公钥')
expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1)
await wrapper.get('[aria-label="微信支付微信支付公钥(推荐)"]').setValue('new-public')
await form.trigger('submit'); await flushPromises()
expect(calls.savePaymentChannel).toHaveBeenLastCalledWith('wechat',expect.objectContaining({fields:expect.objectContaining({public_key_id:'PUB_KEY_ID_test'}),secrets:{public_key:'new-public'}}))
wrapper.unmount()
})
it('isolates failed channel loads, refreshes them and disables saving when unavailable', async () => {
calls.getPaymentChannel.mockRejectedValueOnce(new Error('secret-load-error'))
const wrapper = mount(PaymentsPanel,options); await flushPromises()
expect(wrapper.get('[data-channel="alipay"]').text()).toContain('渠道配置加载失败')
expect(wrapper.find('[data-channel="wechat"] form').exists()).toBe(true)
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(2)
expect(wrapper.html()).not.toContain('secret-load-error')
calls.getPaymentChannel.mockImplementation((channel:string) => Promise.resolve({data:{data:{...configuration(channel),can_save:false}}}))
await wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
expect(wrapper.text()).toContain('当前不能保存配置')
await wrapper.get('[data-channel="alipay"] form').trigger('submit')
expect(calls.savePaymentChannel).not.toHaveBeenCalled(); wrapper.unmount()
})
it('allows disabling a channel without requiring replacement credentials', async () => {
const wrapper = mount(PaymentsPanel,options); await flushPromises()
await wrapper.get('[aria-label="支付宝启用渠道"]').setValue(false)
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
expect(calls.savePaymentChannel.mock.calls[0]![1]).toMatchObject({enabled:false,secrets:{}})
wrapper.unmount()
})
it.each([
['payment_schema_unavailable',503,'支付配置数据库结构未就绪,请管理员备份数据库并执行最新迁移后重启服务'],
['configuration_key_unavailable',503,'支付配置无法解密,请检查服务端支付加密主密钥'],
['payment_schema_unavailable',401,'登录已失效,请重新登录'],
['configuration_key_unavailable',403,'无权限访问支付配置,请联系管理员'],
[undefined,404,'服务版本不支持该接口,请更新并重启服务'],
['unknown_code',503,null],
[undefined,undefined,null],
])('maps load and save errors safely for %s / %s', async (code,status,message) => {
const error = new ApiError('raw-server-secret PEM SQL token',code,status)
calls.getPaymentChannel.mockRejectedValueOnce(error)
const wrapper = mount(PaymentsPanel,options); await flushPromises()
expect(wrapper.get('[data-channel="alipay"] [role="alert"]').text()).toBe(message || '渠道配置加载失败,请刷新重试')
expect(wrapper.find('[data-channel="wechat"] form').exists()).toBe(true)
expect(wrapper.findAll('.el-table__body tbody tr')).toHaveLength(2)
expect(wrapper.html()).not.toContain('raw-server-secret')
await wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.trigger('click'); await flushPromises()
expect(wrapper.find('[data-channel="alipay"] [role="alert"]').exists()).toBe(false)
calls.savePaymentChannel.mockRejectedValueOnce(error)
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
expect(wrapper.get('[data-channel="alipay"] [role="alert"]').text()).toBe(message || '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试')
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('')
expect(wrapper.html()).not.toMatch(/raw-server-secret|replacement-secret|PEM SQL token/)
expect(wrapper.text()).not.toContain('配置保存成功')
wrapper.unmount()
})
})

View File

@@ -0,0 +1,209 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { formatDateTime } from '../date-format'
import { getPaymentChannel, savePaymentChannel, listPaymentOrders, type PaymentChannelConfiguration, type PaymentChannelMetadata, type PaymentChannelSecrets, type PaymentOrder } from '../payments-api'
import type { PaymentChannel } from '../orders-api'
import { ApiError } from '../api'
function configurationError(error:unknown, fallback:string) {
if (!(error instanceof ApiError)) return fallback
if (error.status === 401) return '登录已失效,请重新登录'
if (error.status === 403) return '无权限访问支付配置,请联系管理员'
if (error.status === 404) return '服务版本不支持该接口,请更新并重启服务'
if (error.code === 'payment_schema_unavailable') return '支付配置数据库结构未就绪,请管理员备份数据库并执行最新迁移后重启服务'
if (error.code === 'configuration_key_unavailable') return '支付配置无法解密,请检查服务端支付加密主密钥'
return fallback
}
type Field = { key:keyof PaymentChannelMetadata; label:string; help:string }
type SecretField = { key:keyof PaymentChannelSecrets; label:string; help:string }
const ordinaryFields:Record<PaymentChannel, Field[]> = {
alipay:[
{key:'app_id',label:'应用 ID',help:'来源:支付宝开放平台 → 我的应用 → 应用详情。'},
{key:'seller_id',label:'卖家 ID',help:'来源:支付宝商家/开放平台账户信息中的商户 PID。'},
{key:'notify_url',label:'HTTPS 通知地址',help:'来源:本系统部署的公网 HTTPS 域名,加上 /api/v1/payments/alipay/notify 路径;反向代理有前缀时按实际地址填写。'},
],
wechat:[
{key:'app_id',label:'应用 ID',help:'来源:与微信支付商户号绑定的公众号、小程序或开放平台 AppID。'},
{key:'mch_id',label:'商户 ID',help:'来源:微信支付商户平台 → 账户中心 → 商户信息。'},
{key:'serial_no',label:'商户证书序列号',help:'来源:微信支付商户平台 → 账户中心 → API 安全 → 商户 API 证书详情。'},
{key:'public_key_id',label:'微信支付公钥 ID(推荐)',help:'来源:API 安全 → 微信支付公钥 → 申请/下载公钥后的公钥详情。通常以 PUB_KEY_ID_ 开头。'},
{key:'platform_serial',label:'平台证书序列号(兼容)',help:'来源:已通过微信支付官方工具或证书接口获取的微信支付平台证书,读取其序列号;兼容方案使用。'},
{key:'notify_url',label:'HTTPS 通知地址',help:'来源:本系统部署的公网 HTTPS 域名,加上 /api/v1/payments/wechat/notify 路径;反向代理有前缀时按实际地址填写。'},
],
}
const secretFields:Record<PaymentChannel, SecretField[]> = {
alipay:[
{key:'private_key',label:'商户私钥',help:'来源:配置应用接口加签时,由支付宝密钥工具或本地工具生成并保存的应用 RSA 私钥;与上传的应用公钥配对。'},
{key:'public_key',label:'支付宝验签公钥',help:'来源:支付宝开放平台应用 → 开发设置 → 接口加签;使用支付宝公钥。'},
],
wechat:[
{key:'private_key',label:'商户私钥',help:'来源:申请商户 API 证书时由证书工具生成并保存的 apiclient_key.pem。填写完整 PEM 私钥,与商户证书配对。'},
{key:'public_key',label:'微信支付公钥(推荐)',help:'来源:API 安全 → 微信支付公钥 → 下载的 PEM 公钥文件,必须与上方公钥 ID 配对。'},
{key:'platform_public_key',label:'平台证书 / 验签公钥(兼容)',help:'来源:从已获取的微信支付平台证书中提取的 RSA 公钥,或完整 PEM 平台证书;必须与上方平台证书序列号配对。'},
{key:'api_v3_key',label:'APIv3 密钥',help:'来源:API 安全 → APIv3 密钥;必须是当前设置的 32 字节密钥。'},
],
}
type ChannelForm = { channel:PaymentChannel; config:PaymentChannelConfiguration|null; enabled:boolean; fields:PaymentChannelMetadata; secrets:PaymentChannelSecrets; loading:boolean; saving:boolean; error:string; success:string }
const channels = ref<ChannelForm[]>(['alipay','wechat'].map(channel => ({channel:channel as PaymentChannel,config:null,enabled:false,fields:{app_id:'',notify_url:''},secrets:{},loading:true,saving:false,error:'',success:''})))
const expandedChannels = ref<Record<PaymentChannel, boolean>>({alipay:false,wechat:false})
const saving = computed(() => channels.value.some(form => form.saving))
const sourceName = (source:string) => ({environment:'服务端环境变量',database:'后台配置',none:'未配置'} as Record<string,string>)[source] || '未知来源'
// Allowlist ordinary fields and boolean flags; never assign returned secret material.
function applyConfiguration(form:ChannelForm, value:PaymentChannelConfiguration) {
form.config = {channel:form.channel,enabled:value.enabled,configuration_source:value.configuration_source,required_settings:[],version:value.version,effective:value.effective,can_save:value.can_save,fields:{app_id:'',notify_url:''},secret_fields:[]}
form.enabled = value.enabled === true; form.fields = {app_id:'',notify_url:''}; form.secrets = {}
for (const field of ordinaryFields[form.channel]) form.fields[field.key] = value.fields[field.key] || ''
for (const field of secretFields[form.channel]) form.config.secret_fields.push({name:field.key,configured:value.secret_fields.some(flag => flag.name === field.key && flag.configured === true)})
}
function configured(form:ChannelForm, key:keyof PaymentChannelSecrets) { return form.config?.secret_fields.some(field => field.name === key && field.configured) === true }
async function loadChannel(form:ChannelForm, current:number) {
form.loading = true; form.config = null; form.secrets = {}; form.error = ''; form.success = ''
try {
const response = await getPaymentChannel(form.channel)
if (current === request) applyConfiguration(form,response.data.data)
} catch (error) { if (current === request) form.error = configurationError(error, '渠道配置加载失败,请刷新重试') }
finally { if (current === request) form.loading = false }
}
function validate(form:ChannelForm) {
if (!form.enabled) return ''
for (const field of ordinaryFields[form.channel]) {
if (form.channel === 'wechat' && ['public_key_id','platform_serial'].includes(field.key)) continue
if (!form.fields[field.key]?.trim()) return `请填写${field.label}`
}
try {
const url = new URL(form.fields.notify_url)
if (url.protocol !== 'https:' || url.username || url.password) return '通知地址必须为不含账号密码的 HTTPS 地址'
} catch { return '请填写有效的 HTTPS 通知地址' }
const hasSecret = (key:keyof PaymentChannelSecrets) => !!form.secrets[key]?.trim() || configured(form,key)
for (const field of secretFields[form.channel]) {
if (form.channel === 'wechat' && ['public_key','platform_public_key'].includes(field.key)) continue
if (!hasSecret(field.key)) return `请填写${field.label}`
}
if (form.channel === 'wechat') {
const publicID = form.fields.public_key_id?.trim() || ''
const platformID = form.fields.platform_serial?.trim() || ''
if (publicID && (!/^PUB_KEY_ID_.+/.test(publicID) || !hasSecret('public_key'))) return '请完整填写微信支付公钥 ID 和微信支付公钥'
if (platformID && !hasSecret('platform_public_key')) return '请完整填写平台证书序列号和平台验签公钥'
if (hasSecret('public_key') && !publicID) return '请填写微信支付公钥 ID'
if (hasSecret('platform_public_key') && !platformID) return '请填写平台证书序列号'
if (!publicID && !platformID) return '请至少配置一组微信支付公钥或平台证书验签方案'
}
if (form.channel === 'wechat' && form.secrets.api_v3_key && new TextEncoder().encode(form.secrets.api_v3_key).length !== 32) return 'APIv3 密钥必须为 32 字节'
return ''
}
async function saveChannel(form:ChannelForm) {
if (form.saving || form.loading || loading.value || !form.config || form.config.can_save === false) return
form.success = ''; form.error = validate(form)
if (form.error) return
const current = request
const secrets:PaymentChannelSecrets = {}
for (const field of secretFields[form.channel]) if (form.secrets[field.key]?.trim()) secrets[field.key] = form.secrets[field.key]
const fields:PaymentChannelMetadata = {app_id:'',notify_url:''}
for (const field of ordinaryFields[form.channel]) fields[field.key] = form.fields[field.key]?.trim() || ''
form.saving = true; form.secrets = {}
try {
const response = await savePaymentChannel(form.channel,{enabled:form.enabled,fields,secrets})
if (current !== request) return
applyConfiguration(form,response.data.data)
form.success = '配置保存成功;配置校验不代表真实交易联调通过'
} catch (error) {
// Use only fixed allowlisted messages, never server messages or credential values.
if (current === request) form.error = configurationError(error, '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试')
} finally { if (current === request) form.saving = false }
}
const orders = ref<PaymentOrder[]>([])
const loading = ref(false), ordersError = ref('')
const channelFilter = ref(''), statusFilter = ref(''), query = ref(''), page = ref(1)
const channelName = (channel:string) => ({alipay:'支付宝',wechat:'微信支付'} as Record<string,string>)[channel] || '未知渠道'
const statusName = (status:string) => ({created:'待支付',pending:'待支付',paid:'已支付',failed:'失败',expired:'已失效',cancelled:'已取消',closed:'已关闭',pending_payment:'待支付',issued:'授权已开通',authorization_removed:'授权已移除'} as Record<string,string>)[status] || '未知状态'
const stateClass = (status:string) => ['paid','issued'].includes(status) ? 'is-success' : ['created','pending','pending_payment'].includes(status) ? 'is-pending' : 'is-inactive'
const statuses = computed(() => [...new Set(orders.value.map(row => row.status))])
const filtered = computed(() => orders.value.filter(row => (!channelFilter.value || row.channel === channelFilter.value) && (!statusFilter.value || row.status === statusFilter.value) && (!query.value.trim() || [row.order_id,row.merchant_order_no,row.channel_trade_no || ''].some(value => String(value).toLowerCase().includes(query.value.trim().toLowerCase())))))
const pagedOrders = computed(() => filtered.value.slice((page.value - 1) * 20, page.value * 20))
watch([channelFilter, statusFilter, query], () => { page.value = 1 })
const amount = (row:PaymentOrder) => `${(row.amount_cents / 100).toFixed(2)} ${row.currency}`
const dateColumns = [{key:'paid_at',label:'支付时间'},{key:'created_at',label:'创建时间'},{key:'expires_at',label:'二维码展示期限'}] as const
let request = 0
async function refresh() {
if (saving.value) return
const current = ++request
page.value = 1; loading.value = true; ordersError.value = ''; orders.value = []
const [orderResult] = await Promise.all([
Promise.allSettled([listPaymentOrders()]).then(results => results[0]!),
Promise.all(channels.value.map(form => loadChannel(form,current))),
])
if (current !== request) return
if (orderResult.status === 'fulfilled') orders.value = orderResult.value.data.data
else ordersError.value = '支付流水加载失败,请刷新重试'
loading.value = false
}
function reset() { channelFilter.value = ''; statusFilter.value = ''; query.value = ''; page.value = 1 }
onMounted(refresh)
onUnmounted(() => { request++; channels.value.forEach(form => { form.secrets = {} }) })
</script>
<template>
<section class="payment-workspace" aria-labelledby="payment-title">
<header class="payment-heading"><div><p class="payment-eyebrow">支付管理</p><h2 id="payment-title">支付渠道与流水</h2><p class="payment-description">管理员为已有客户创建订单后,在订单页面生成付款链接。</p></div><el-button :loading="loading" :disabled="loading || saving" @click="refresh"><span aria-hidden="true">↻</span> 刷新支付数据</el-button></header>
<section class="payment-config" aria-labelledby="channel-title">
<div class="payment-subheading"><h3 id="channel-title">渠道配置</h3><span class="payment-muted">管理员配置 · 密钥不回显</span></div>
<p class="payment-description">普通字段可编辑;密钥留空保留现值,填写新值表示替换。配置校验不代表真实交易联调通过。</p>
<p v-if="loading" role="status">正在加载支付数据…</p>
<div class="channel-grid"><article v-for="form in channels" :key="form.channel" class="channel-card" :data-channel="form.channel">
<button type="button" class="channel-toggle" :aria-label="`${channelName(form.channel)}渠道配置`" :aria-expanded="expandedChannels[form.channel]" :aria-controls="`channel-details-${form.channel}`" @click="expandedChannels[form.channel] = !expandedChannels[form.channel]">
<span class="channel-toggle-title">{{ channelName(form.channel) }}<span v-if="form.config?.enabled !== undefined" class="payment-state" :class="form.config?.enabled ? 'is-success' : 'is-inactive'"><i aria-hidden="true"></i>{{ form.config?.enabled ? '已启用' : '未启用' }}</span></span>
<span class="channel-toggle-action">{{ expandedChannels[form.channel] ? '收起' : '展开配置' }} <span aria-hidden="true">{{ expandedChannels[form.channel] ? '⌃' : '⌄' }}</span></span>
</button>
<p v-if="form.loading" role="status">正在加载渠道配置…</p>
<div v-show="expandedChannels[form.channel]" :id="`channel-details-${form.channel}`" class="channel-details">
<template v-if="form.config">
<p>配置来源:{{ sourceName(form.config.configuration_source || '') }}</p>
<p v-if="form.config.version != null">配置版本:{{ form.config.version }}</p>
<p v-if="form.config.effective !== undefined">{{ form.config.effective ? '已生效' : '未生效' }}</p>
<p v-if="form.config.can_save === false" class="payment-error" role="alert">当前不能保存配置,请联系管理员检查服务端支付配置加密主密钥及配置服务。</p>
<form autocomplete="off" @submit.prevent="saveChannel(form)"><fieldset :disabled="form.saving || loading || form.config.can_save === false">
<label class="channel-enabled"><input v-model="form.enabled" type="checkbox" :aria-label="`${channelName(form.channel)}启用渠道`">启用渠道</label>
<label v-for="field in ordinaryFields[form.channel]" :key="field.key" class="channel-field"><span>{{ field.label }}</span><small class="channel-help">{{ field.help }}</small><el-input v-model="form.fields[field.key]" :disabled="form.saving || loading || form.config.can_save === false" :aria-label="`${channelName(form.channel)}${field.label}`" autocomplete="off"/></label>
<label v-for="field in secretFields[form.channel]" :key="field.key" class="channel-field"><span>{{ field.label }} <small>{{ configured(form,field.key) ? '已配置' : '未配置' }}</small></span><small class="channel-help">{{ field.help }}</small><el-input v-model="form.secrets[field.key]" :disabled="form.saving || loading || form.config.can_save === false" type="password" :aria-label="`${channelName(form.channel)}${field.label}`" autocomplete="new-password" placeholder="留空保留现值;填写新值替换"/></label>
<el-button native-type="submit" type="primary" :loading="form.saving" :disabled="form.saving || loading || form.config.can_save === false">{{ form.saving ? '正在保存…' : '保存配置' }}</el-button>
</fieldset></form>
</template>
</div>
<p v-if="form.error" class="payment-error" role="alert">{{ form.error }}</p>
<p v-if="form.success" class="payment-success" role="status">{{ form.success }}</p>
</article></div>
</section>
<section class="payment-list" aria-label="支付流水列表">
<div class="payment-list-toolbar"><div class="payment-list-title"><h3>支付流水</h3><span class="payment-count">{{ filtered.length }} / {{ orders.length }} 条</span></div><router-link class="payment-order-link" to="/orders">去订单创建付款链接 →</router-link></div>
<p class="payment-description">最近 100 条支付流水,筛选与分页仅作用于本次加载的数据,数量不代表服务端全部记录。日期为本地时间。</p>
<div class="payment-filters"><el-input v-model="query" clearable aria-label="搜索支付流水" placeholder="订单 ID / 商户单号 / 渠道单号"/><label class="payment-filter"><span>渠道</span><el-select v-model="channelFilter" aria-label="支付渠道筛选"><el-option value="" label="全部渠道"/><el-option value="alipay" label="支付宝"/><el-option value="wechat" label="微信支付"/></el-select></label><label class="payment-filter"><span>状态</span><el-select v-model="statusFilter" aria-label="支付状态筛选"><el-option value="" label="全部状态"/><el-option v-for="status in statuses" :key="status" :value="status" :label="statusName(status)"/></el-select></label><el-button @click="reset">重置筛选</el-button></div>
<p v-if="ordersError" class="payment-error" role="alert">{{ ordersError }}</p>
<div class="payment-table-wrap"><el-table :data="pagedOrders" row-key="id" v-loading="loading" :empty-text="loading ? '正在加载支付数据…' : ordersError ? '支付流水加载失败,请刷新重试' : '暂无符合条件的支付流水'">
<el-table-column prop="id" label="支付 ID" width="90"/><el-table-column prop="order_id" label="订单 ID" width="90"/>
<el-table-column label="商户单号" min-width="200"><template #default="{ row }"><code class="payment-trade" :title="row.merchant_order_no">{{ row.merchant_order_no }}</code></template></el-table-column>
<el-table-column label="渠道" width="100"><template #default="{ row }">{{ channelName(row.channel) }}</template></el-table-column>
<el-table-column label="渠道交易号" min-width="200"><template #default="{ row }"><code class="payment-trade" :title="row.channel_trade_no || ''">{{ row.channel_trade_no || '—' }}</code></template></el-table-column>
<el-table-column label="金额" width="140"><template #default="{ row }">{{ amount(row) }}</template></el-table-column>
<el-table-column label="支付状态" width="130"><template #default="{ row }"><span class="payment-state" :class="stateClass(row.status)"><i aria-hidden="true"></i>{{ statusName(row.status) }}</span></template></el-table-column>
<el-table-column label="订单状态" width="150"><template #default="{ row }"><span class="payment-state" :class="stateClass(row.order_status)"><i aria-hidden="true"></i>{{ statusName(row.order_status) }}</span></template></el-table-column>
<el-table-column label="授权 ID" width="90"><template #default="{ row }">{{ row.license_id ?? '—' }}</template></el-table-column>
<el-table-column v-for="column in dateColumns" :key="column.key" :label="column.label" width="190"><template #default="{ row }">{{ formatDateTime(row[column.key]) }}</template></el-table-column>
<el-table-column label="异常" min-width="260"><template #default="{ row }">{{ row.last_error ? '存在支付异常,请核查服务端记录' : '—' }}</template></el-table-column>
</el-table></div>
<div class="payment-pagination"><span>本次加载 {{ orders.length }} 条 · 筛选后 {{ filtered.length }} 条 · 每页 20 条</span><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="20" layout="prev, pager, next"/></div>
</section>
</section>
</template>
<style scoped>
.payment-workspace{--payment-line:#e5eaf0;--payment-muted:#687586;color:#17202b}
.payment-heading{display:flex;justify-content:space-between;align-items:center;gap:18px;padding-bottom:21px;border-bottom:1px solid var(--payment-line)}.payment-heading h2{margin:0;font-size:20px;line-height:1.35}.payment-eyebrow{margin:0 0 5px;color:#1769e0;font-size:11px;font-weight:700}
.payment-description{margin:5px 0 0;color:var(--payment-muted);font-size:13px;line-height:1.6}.payment-config{margin-top:20px;padding:18px 20px;background:#f7f9fc;border:1px solid var(--payment-line);border-radius:7px}
.payment-subheading,.payment-list-toolbar,.payment-list-title,.payment-pagination{display:flex;align-items:center;gap:12px}.payment-subheading,.payment-list-toolbar,.payment-pagination{justify-content:space-between}.payment-subheading h3,.payment-subheading h4,.payment-list-title h3{margin:0;font-size:14px;font-weight:650}.payment-muted,.payment-count{color:var(--payment-muted);font-size:12px}
.channel-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;margin-top:17px}.channel-card{border:1px solid var(--payment-line);border-radius:6px;padding:16px;background:#fff;min-width:0;overflow-wrap:anywhere}.channel-card p,.channel-card li{color:#526173;font-size:12px}.channel-card ul{margin:8px 0 0;padding-left:18px}.channel-card li{margin:6px 0}
.channel-toggle{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;padding:0;border:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}.channel-toggle-title{display:flex;align-items:center;gap:12px;font-size:14px;font-weight:650}.channel-toggle-action{flex-shrink:0;color:#1769e0;font-size:12px}.channel-toggle:focus-visible{outline:2px solid #1769e0;outline-offset:5px;border-radius:3px}.channel-details{margin-top:14px;padding-top:2px;border-top:1px solid var(--payment-line)}
.channel-card fieldset{border:0;padding:0;margin:14px 0 0;min-width:0}.channel-enabled{display:flex;align-items:center;gap:8px;font-size:13px}.channel-field{display:flex;flex-direction:column;gap:6px;margin:13px 0;color:#526173;font-size:12px}.channel-field>span small{margin-left:8px;color:var(--payment-muted)}.channel-help{display:block;margin:0;color:#7a8797;font-size:11px;line-height:1.5}.payment-success{color:#16845b;font-size:13px;line-height:1.6}
.payment-list{margin-top:24px}.payment-list-toolbar{min-height:36px;margin-bottom:12px}.payment-count{padding:3px 7px;border-radius:4px;background:#f0f3f7}.payment-order-link{color:#1769e0;font-size:12px;text-decoration:none}.payment-filters{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:16px 0 12px}.payment-filters>.el-input{flex:1;min-width:230px}.payment-filter{display:flex;align-items:center;gap:9px;color:#526173;font-size:12px}.payment-filter :deep(.el-select){width:150px}
.payment-table-wrap{width:100%;overflow-x:auto;border:1px solid var(--payment-line);border-radius:6px}.payment-table-wrap :deep(.el-table){min-width:850px}.payment-table-wrap :deep(.el-table th.el-table__cell){height:42px;background:#f7f9fc;color:#657387;font-size:12px;font-weight:600}.payment-table-wrap :deep(.el-table td.el-table__cell){height:57px;color:#354255;font-size:13px}
.payment-trade,.channel-card code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12px}.payment-trade{display:block;overflow:hidden;color:#526173;text-overflow:ellipsis;white-space:nowrap}.payment-state{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:600;white-space:nowrap}.payment-state i{width:7px;height:7px;border-radius:50%;background:#98a3b2}.payment-state.is-success{color:#16845b}.payment-state.is-success i{background:#20a36a}.payment-state.is-pending{color:#8b640e}.payment-state.is-pending i{background:#d69a28}.payment-state.is-inactive{color:#687586}
.payment-error{margin:12px 0;color:#b44830;font-size:13px}.payment-pagination{margin-top:12px;color:var(--payment-muted);font-size:12px}.payment-pagination :deep(.el-pagination){margin-top:0}
@media(max-width:900px){.payment-filters>.el-input{flex-basis:100%}}@media(max-width:620px){.payment-heading{align-items:flex-start;flex-wrap:wrap}.payment-config{padding:15px}.payment-subheading{align-items:flex-start;flex-wrap:wrap}.channel-grid{grid-template-columns:minmax(0,1fr)}.payment-list-toolbar,.payment-pagination{align-items:flex-start;flex-direction:column}.payment-filter{justify-content:space-between;width:100%}.payment-filter :deep(.el-select){width:min(72%,280px)}.payment-pagination :deep(.el-pagination){padding-left:0}}
</style>