feat: improve payment config drafts and certificate import
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { defineComponent, nextTick } from 'vue'
|
||||
import ElementPlus, { ElPagination } from 'element-plus'
|
||||
@@ -18,6 +19,35 @@ const options = {global:{plugins:[ElementPlus],stubs:{
|
||||
}}}
|
||||
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('stashes and restores the complete draft in page memory', async () => {
|
||||
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('draft-app')
|
||||
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('draft-secret')
|
||||
const panel = wrapper.get('[data-channel="alipay"]')
|
||||
await panel.findAll('button').find(button => button.text() === '暂存草稿')!.trigger('click')
|
||||
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('changed')
|
||||
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('changed')
|
||||
await panel.findAll('button').find(button => button.text() === '恢复草稿')!.trigger('click')
|
||||
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝应用 ID"]').element.value).toBe('draft-app')
|
||||
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('draft-secret')
|
||||
wrapper.unmount()
|
||||
})
|
||||
it('imports merchant private key locally without using merchant certificate as platform verifier', async () => {
|
||||
const zip = new JSZip()
|
||||
zip.file('apiclient_key.pem','-----BEGIN PRIVATE KEY-----\nTEST ONLY\n-----END PRIVATE KEY-----')
|
||||
zip.file('apiclient_cert.pem','-----BEGIN CERTIFICATE-----\nTEST ONLY\n-----END CERTIFICATE-----')
|
||||
const bytes = await zip.generateAsync({type:'uint8array'})
|
||||
const wrapper = mount(PaymentsPanel,options); await flushPromises()
|
||||
await wrapper.findAll('button').find(button => button.text() === '导入微信证书 ZIP')!.trigger('click')
|
||||
const input = wrapper.get('input[type="file"]')
|
||||
Object.defineProperty(input.element,'files',{value:[new File([bytes as BlobPart],'cert.zip')]})
|
||||
await input.trigger('change')
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('已导入商户 API 私钥'))
|
||||
expect(wrapper.get<HTMLInputElement>('[aria-label="微信支付商户私钥"]').element.value).toContain('TEST ONLY')
|
||||
expect(wrapper.get<HTMLInputElement>('[aria-label="微信支付平台证书 / 验签公钥(兼容)"]').element.value).toBe('')
|
||||
expect(calls.savePaymentChannel).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
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="支付宝渠道配置"]')
|
||||
@@ -103,30 +133,30 @@ describe('PaymentsPanel', () => {
|
||||
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 () => {
|
||||
it('submits replacement credentials once, clears inputs after success, 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')
|
||||
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('replacement-secret')
|
||||
expect(wrapper.text()).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 () => {
|
||||
it('shows safe save failures and retains the complete draft 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.text()).not.toContain('配置保存成功'); expect(wrapper.text()).not.toMatch(/replacement-secret|raw PEM|database-error/)
|
||||
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('replacement-secret')
|
||||
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()
|
||||
@@ -210,8 +240,8 @@ describe('PaymentsPanel', () => {
|
||||
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.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('replacement-secret')
|
||||
expect(wrapper.html()).not.toMatch(/raw-server-secret|PEM SQL token/)
|
||||
expect(wrapper.text()).not.toContain('配置保存成功')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import JSZip from 'jszip'
|
||||
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'
|
||||
@@ -99,14 +100,15 @@ async function saveChannel(form:ChannelForm) {
|
||||
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 = {}
|
||||
form.saving = true
|
||||
try {
|
||||
const response = await savePaymentChannel(form.channel,{enabled:form.enabled,fields,secrets})
|
||||
if (current !== request) return
|
||||
applyConfiguration(form,response.data.data)
|
||||
delete drafts.value[form.channel]
|
||||
form.success = '配置保存成功;配置校验不代表真实交易联调通过'
|
||||
} catch (error) {
|
||||
// Use only fixed allowlisted messages, never server messages or credential values.
|
||||
// Keep the draft, including credentials, so a failed validation can be corrected and retried.
|
||||
if (current === request) form.error = configurationError(error, '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试')
|
||||
} finally { if (current === request) form.saving = false }
|
||||
}
|
||||
@@ -138,8 +140,52 @@ async function refresh() {
|
||||
loading.value = false
|
||||
}
|
||||
function reset() { channelFilter.value = ''; statusFilter.value = ''; query.value = ''; page.value = 1 }
|
||||
type Draft = {enabled:boolean; fields:PaymentChannelMetadata; secrets:PaymentChannelSecrets}
|
||||
const drafts = ref<Partial<Record<PaymentChannel,Draft>>>({})
|
||||
function stashDraft(form:ChannelForm) {
|
||||
drafts.value[form.channel] = {enabled:form.enabled,fields:{...form.fields},secrets:{...form.secrets}}
|
||||
form.success = '草稿已暂存在当前页面内存中;可恢复,离开或刷新浏览器页面后清除'
|
||||
}
|
||||
function restoreDraft(form:ChannelForm) {
|
||||
const draft = drafts.value[form.channel]
|
||||
if (!draft) return
|
||||
form.enabled = draft.enabled; form.fields = {...draft.fields}; form.secrets = {...draft.secrets}
|
||||
form.error = ''; form.success = '已恢复暂存草稿'
|
||||
}
|
||||
const importing = ref(false)
|
||||
const importInput = ref<HTMLInputElement|null>(null)
|
||||
const importingChannel = ref<PaymentChannel|null>(null)
|
||||
function openCertificateImport(channel:PaymentChannel) { importingChannel.value = channel; importInput.value?.click() }
|
||||
async function importCertificate(event:Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]; input.value = ''
|
||||
const channel = importingChannel.value; importingChannel.value = null
|
||||
if (!file || channel !== 'wechat') return
|
||||
const form = channels.value.find(item => item.channel === channel)
|
||||
if (!form || !form.config || form.saving || loading.value || importing.value) return
|
||||
const current = request
|
||||
importing.value = true
|
||||
form.success = ''
|
||||
try {
|
||||
if (file.size > 1024 * 1024) throw new Error('证书包过大')
|
||||
const zip = await JSZip.loadAsync(file)
|
||||
const entries = Object.values(zip.files).filter(entry => !entry.dir && /\.(pem|crt|key)$/i.test(entry.name))
|
||||
if (entries.length > 10) throw new Error('证书文件过多')
|
||||
const materials = await Promise.all(entries.map(async entry => ({name:entry.name.toLowerCase(), text:await entry.async('text')})))
|
||||
const privateKey = materials.find(item => /apiclient[_-]?key|private/.test(item.name) && item.text.includes('PRIVATE KEY'))?.text
|
||||
const certificate = materials.find(item => /apiclient[_-]?cert|certificate|cert/.test(item.name) && item.text.includes('BEGIN CERTIFICATE'))?.text
|
||||
if (current !== request) return
|
||||
if (!privateKey && !certificate) throw new Error('未找到可识别的 PEM 证书材料')
|
||||
if (privateKey) form.secrets.private_key = privateKey.trim()
|
||||
form.success = privateKey
|
||||
? '已导入商户 API 私钥;请补充商户证书序列号、AppID、APIv3 密钥和其他必填字段后保存'
|
||||
: '已识别商户 API 证书,但无法从证书包安全推断配置字段;请手工填写私钥、序列号和 APIv3 密钥'
|
||||
form.error = ''
|
||||
} catch { if (current === request) form.error = '证书包导入失败:请选择不超过 1 MB 的微信支付证书 ZIP,并确认其中包含 PEM 证书或私钥' }
|
||||
finally { importing.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
onUnmounted(() => { request++; channels.value.forEach(form => { form.secrets = {} }) })
|
||||
onUnmounted(() => { request++; drafts.value = {}; channels.value.forEach(form => { form.secrets = {} }) })
|
||||
</script>
|
||||
<template>
|
||||
<section class="payment-workspace" aria-labelledby="payment-title">
|
||||
@@ -148,6 +194,7 @@ onUnmounted(() => { request++; channels.value.forEach(form => { form.secrets = {
|
||||
<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>
|
||||
<input ref="importInput" class="certificate-import-input" type="file" accept=".zip,application/zip" aria-label="导入微信支付证书 ZIP" @change="importCertificate">
|
||||
<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>
|
||||
@@ -155,7 +202,11 @@ onUnmounted(() => { request++; channels.value.forEach(form => { form.secrets = {
|
||||
</button>
|
||||
<p v-if="form.loading" role="status">正在加载渠道配置…</p>
|
||||
<div v-show="expandedChannels[form.channel]" :id="`channel-details-${form.channel}`" class="channel-details">
|
||||
<el-button v-if="form.channel === 'wechat'" type="default" :disabled="form.saving || loading || importing || !form.config || form.config.can_save === false" @click="openCertificateImport(form.channel)">导入微信证书 ZIP</el-button>
|
||||
<template v-if="form.config">
|
||||
<el-button :disabled="form.saving || importing" @click="stashDraft(form)">暂存草稿</el-button>
|
||||
<el-button :disabled="form.saving || importing || !drafts[form.channel]" @click="restoreDraft(form)">恢复草稿</el-button>
|
||||
<p class="payment-muted">草稿仅保留在当前页面内存中,离开或刷新浏览器页面后清除;保存失败时输入会保留。</p>
|
||||
<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>
|
||||
@@ -204,6 +255,6 @@ onUnmounted(() => { request++; channels.value.forEach(form => { form.secrets = {
|
||||
.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}
|
||||
.certificate-import-input{display:none}.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>
|
||||
|
||||
Reference in New Issue
Block a user