feat: improve payment config drafts and certificate import
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-17 22:41:51 +08:00
parent cfcc9b386b
commit f43eaa685e
4 changed files with 194 additions and 12 deletions

View File

@@ -10,6 +10,7 @@
"dependencies": { "dependencies": {
"axios": "^1.7.9", "axios": "^1.7.9",
"element-plus": "^2.9.4", "element-plus": "^2.9.4",
"jszip": "^3.10.2",
"pinia": "^2.3.0", "pinia": "^2.3.0",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"vue": "^3.5.13", "vue": "^3.5.13",
@@ -1744,6 +1745,12 @@
"proto-list": "~1.2.1" "proto-list": "~1.2.1"
} }
}, },
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmmirror.com/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"license": "MIT"
},
"node_modules/cssstyle": { "node_modules/cssstyle": {
"version": "4.6.0", "version": "4.6.0",
"resolved": "https://registry.npmmirror.com/cssstyle/-/cssstyle-4.6.0.tgz", "resolved": "https://registry.npmmirror.com/cssstyle/-/cssstyle-4.6.0.tgz",
@@ -2393,6 +2400,18 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmmirror.com/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
"license": "MIT"
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ini": { "node_modules/ini": {
"version": "1.3.8", "version": "1.3.8",
"resolved": "https://registry.npmmirror.com/ini/-/ini-1.3.8.tgz", "resolved": "https://registry.npmmirror.com/ini/-/ini-1.3.8.tgz",
@@ -2416,6 +2435,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"license": "MIT"
},
"node_modules/js-beautify": { "node_modules/js-beautify": {
"version": "2.0.3", "version": "2.0.3",
"resolved": "https://registry.npmmirror.com/js-beautify/-/js-beautify-2.0.3.tgz", "resolved": "https://registry.npmmirror.com/js-beautify/-/js-beautify-2.0.3.tgz",
@@ -2516,6 +2541,27 @@
"node": ">= 14" "node": ">= 14"
} }
}, },
"node_modules/jszip": {
"version": "3.10.2",
"resolved": "https://registry.npmmirror.com/jszip/-/jszip-3.10.2.tgz",
"integrity": "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==",
"license": "(MIT OR GPL-3.0-or-later)",
"dependencies": {
"lie": "~3.3.0",
"pako": "~1.0.2",
"readable-stream": "~2.3.6",
"setimmediate": "^1.0.5"
}
},
"node_modules/lie": {
"version": "3.3.0",
"resolved": "https://registry.npmmirror.com/lie/-/lie-3.3.0.tgz",
"integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
"license": "MIT",
"dependencies": {
"immediate": "~3.0.5"
}
},
"node_modules/locate-path": { "node_modules/locate-path": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz",
@@ -2732,6 +2778,12 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmmirror.com/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/parse5": { "node_modules/parse5": {
"version": "7.3.0", "version": "7.3.0",
"resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz", "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz",
@@ -2896,6 +2948,12 @@
"node": "^10 || ^12 || >=14" "node": "^10 || ^12 || >=14"
} }
}, },
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"license": "MIT"
},
"node_modules/proto-list": { "node_modules/proto-list": {
"version": "1.2.4", "version": "1.2.4",
"resolved": "https://registry.npmmirror.com/proto-list/-/proto-list-1.2.4.tgz", "resolved": "https://registry.npmmirror.com/proto-list/-/proto-list-1.2.4.tgz",
@@ -2939,6 +2997,21 @@
"node": ">=10.13.0" "node": ">=10.13.0"
} }
}, },
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmmirror.com/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/require-directory": { "node_modules/require-directory": {
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz", "resolved": "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz",
@@ -3007,6 +3080,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/safer-buffer": { "node_modules/safer-buffer": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -3046,6 +3125,12 @@
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/setimmediate": {
"version": "1.0.5",
"resolved": "https://registry.npmmirror.com/setimmediate/-/setimmediate-1.0.5.tgz",
"integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
"license": "MIT"
},
"node_modules/siginfo": { "node_modules/siginfo": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz", "resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz",
@@ -3076,6 +3161,15 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string-width": { "node_modules/string-width": {
"version": "4.2.3", "version": "4.2.3",
"resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz", "resolved": "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz",
@@ -3250,6 +3344,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/vite": { "node_modules/vite": {
"version": "6.4.3", "version": "6.4.3",
"resolved": "https://registry.npmmirror.com/vite/-/vite-6.4.3.tgz", "resolved": "https://registry.npmmirror.com/vite/-/vite-6.4.3.tgz",

View File

@@ -12,6 +12,7 @@
"dependencies": { "dependencies": {
"axios": "^1.7.9", "axios": "^1.7.9",
"element-plus": "^2.9.4", "element-plus": "^2.9.4",
"jszip": "^3.10.2",
"pinia": "^2.3.0", "pinia": "^2.3.0",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"vue": "^3.5.13", "vue": "^3.5.13",

View File

@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest' import { beforeEach, describe, expect, it, vi } from 'vitest'
import JSZip from 'jszip'
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import { defineComponent, nextTick } from 'vue' import { defineComponent, nextTick } from 'vue'
import ElementPlus, { ElPagination } from 'element-plus' 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}]}}) }) 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', () => { 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 () => { it('collapses channel forms by default and expands them independently', async () => {
const wrapper = mount(PaymentsPanel,{...options,attachTo:document.body}); await flushPromises() const wrapper = mount(PaymentsPanel,{...options,attachTo:document.body}); await flushPromises()
const alipayToggle = wrapper.get('[aria-label="支付宝渠道配置"]') const alipayToggle = wrapper.get('[aria-label="支付宝渠道配置"]')
@@ -103,30 +133,30 @@ describe('PaymentsPanel', () => {
expect(wrapper.text()).toContain('配置保存成功'); expect(wrapper.text()).toContain('不代表真实交易联调通过') expect(wrapper.text()).toContain('配置保存成功'); expect(wrapper.text()).toContain('不代表真实交易联调通过')
wrapper.unmount() 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 let resolve!: (value:unknown) => void
calls.savePaymentChannel.mockReturnValueOnce(new Promise(r => {resolve=r})) calls.savePaymentChannel.mockReturnValueOnce(new Promise(r => {resolve=r}))
const wrapper = mount(PaymentsPanel,options); await flushPromises() const wrapper = mount(PaymentsPanel,options); await flushPromises()
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret') await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit') await wrapper.get('[data-channel="alipay"] form').trigger('submit')
expect(calls.savePaymentChannel.mock.calls[0]![1].secrets).toEqual({private_key:'replacement-secret'}) expect(calls.savePaymentChannel.mock.calls[0]![1].secrets).toEqual({private_key:'replacement-secret'})
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('') expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('replacement-secret')
expect(wrapper.html()).not.toContain('replacement-secret') expect(wrapper.text()).not.toContain('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit') await wrapper.get('[data-channel="alipay"] form').trigger('submit')
expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1) expect(calls.savePaymentChannel).toHaveBeenCalledTimes(1)
expect(wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.attributes('disabled')).toBeDefined() expect(wrapper.findAll('button').find(button => button.text().includes('刷新支付数据'))!.attributes('disabled')).toBeDefined()
resolve({data:{data:configuration('alipay')}}); await flushPromises() resolve({data:{data:configuration('alipay')}}); await flushPromises()
expect(wrapper.text()).toContain('配置保存成功'); wrapper.unmount() 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')) calls.savePaymentChannel.mockRejectedValueOnce(new Error('replacement-secret raw PEM database-error'))
const wrapper = mount(PaymentsPanel,options); await flushPromises() const wrapper = mount(PaymentsPanel,options); await flushPromises()
await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('draft-app') await wrapper.get('[aria-label="支付宝应用 ID"]').setValue('draft-app')
await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret') await wrapper.get('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises() await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises()
expect(wrapper.get('[role="alert"]').text()).toContain('服务端校验未通过') 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.text()).not.toContain('配置保存成功'); expect(wrapper.text()).not.toMatch(/replacement-secret|raw PEM|database-error/)
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('') expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('replacement-secret')
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝应用 ID"]').element.value).toBe('draft-app') expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝应用 ID"]').element.value).toBe('draft-app')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises() 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() 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('[aria-label="支付宝商户私钥"]').setValue('replacement-secret')
await wrapper.get('[data-channel="alipay"] form').trigger('submit'); await flushPromises() 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('[data-channel="alipay"] [role="alert"]').text()).toBe(message || '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试')
expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('') expect(wrapper.get<HTMLInputElement>('[aria-label="支付宝商户私钥"]').element.value).toBe('replacement-secret')
expect(wrapper.html()).not.toMatch(/raw-server-secret|replacement-secret|PEM SQL token/) expect(wrapper.html()).not.toMatch(/raw-server-secret|PEM SQL token/)
expect(wrapper.text()).not.toContain('配置保存成功') expect(wrapper.text()).not.toContain('配置保存成功')
wrapper.unmount() wrapper.unmount()
}) })

View File

@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue' import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import JSZip from 'jszip'
import { formatDateTime } from '../date-format' import { formatDateTime } from '../date-format'
import { getPaymentChannel, savePaymentChannel, listPaymentOrders, type PaymentChannelConfiguration, type PaymentChannelMetadata, type PaymentChannelSecrets, type PaymentOrder } from '../payments-api' import { getPaymentChannel, savePaymentChannel, listPaymentOrders, type PaymentChannelConfiguration, type PaymentChannelMetadata, type PaymentChannelSecrets, type PaymentOrder } from '../payments-api'
import type { PaymentChannel } from '../orders-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] 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:''} const fields:PaymentChannelMetadata = {app_id:'',notify_url:''}
for (const field of ordinaryFields[form.channel]) fields[field.key] = form.fields[field.key]?.trim() || '' for (const field of ordinaryFields[form.channel]) fields[field.key] = form.fields[field.key]?.trim() || ''
form.saving = true; form.secrets = {} form.saving = true
try { try {
const response = await savePaymentChannel(form.channel,{enabled:form.enabled,fields,secrets}) const response = await savePaymentChannel(form.channel,{enabled:form.enabled,fields,secrets})
if (current !== request) return if (current !== request) return
applyConfiguration(form,response.data.data) applyConfiguration(form,response.data.data)
delete drafts.value[form.channel]
form.success = '配置保存成功;配置校验不代表真实交易联调通过' form.success = '配置保存成功;配置校验不代表真实交易联调通过'
} catch (error) { } 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, '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试') if (current === request) form.error = configurationError(error, '保存失败:服务端校验未通过或暂不可用,请核对配置与密钥格式后重试')
} finally { if (current === request) form.saving = false } } finally { if (current === request) form.saving = false }
} }
@@ -138,8 +140,52 @@ async function refresh() {
loading.value = false loading.value = false
} }
function reset() { channelFilter.value = ''; statusFilter.value = ''; query.value = ''; page.value = 1 } 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) onMounted(refresh)
onUnmounted(() => { request++; channels.value.forEach(form => { form.secrets = {} }) }) onUnmounted(() => { request++; drafts.value = {}; channels.value.forEach(form => { form.secrets = {} }) })
</script> </script>
<template> <template>
<section class="payment-workspace" aria-labelledby="payment-title"> <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> <div class="payment-subheading"><h3 id="channel-title">渠道配置</h3><span class="payment-muted">管理员配置 · 密钥不回显</span></div>
<p class="payment-description">普通字段可编辑;密钥留空保留现值,填写新值表示替换。配置校验不代表真实交易联调通过。</p> <p class="payment-description">普通字段可编辑;密钥留空保留现值,填写新值表示替换。配置校验不代表真实交易联调通过。</p>
<p v-if="loading" role="status">正在加载支付数据…</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"> <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]"> <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-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> </button>
<p v-if="form.loading" role="status">正在加载渠道配置…</p> <p v-if="form.loading" role="status">正在加载渠道配置…</p>
<div v-show="expandedChannels[form.channel]" :id="`channel-details-${form.channel}`" class="channel-details"> <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"> <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>配置来源:{{ sourceName(form.config.configuration_source || '') }}</p>
<p v-if="form.config.version != null">配置版本:{{ form.config.version }}</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.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-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-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-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}} @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> </style>