fix:支付宝小程序登录以及支付宝支付

This commit is contained in:
2026-06-16 16:55:49 +08:00
parent 815b0e3731
commit 0ac3bece42
80 changed files with 5841 additions and 30 deletions
@@ -0,0 +1,299 @@
import React from 'react';
import {
ModalForm,
ProForm,
ProFormDependency,
ProFormSelect,
ProFormSwitch,
ProFormText,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Alert, Divider } from 'antd';
import { AlipayConfigItem } from '@/services/alipayConfig';
export interface AlipayAppFormProps {
open: boolean;
title: string;
initialValues?: Partial<AlipayConfigItem>;
onOpenChange: (v: boolean) => void;
onFinish: (values: AlipayConfigItem) => Promise<boolean>;
}
const SectionTitle: React.FC<{ children: React.ReactNode; tip?: string }> = ({
children,
tip,
}) => (
<div style={{ margin: '4px 0 12px' }}>
<Divider orientation="left" style={{ margin: '8px 0' }}>
<span style={{ fontWeight: 600 }}>{children}</span>
</Divider>
{tip ? (
<div style={{ fontSize: 12, color: '#8c8c8c', marginBottom: 8 }}>
{tip}
</div>
) : null}
</div>
);
const AlipayAppForm: React.FC<AlipayAppFormProps> = ({
open,
title,
initialValues,
onOpenChange,
onFinish,
}) => {
return (
<ModalForm<AlipayConfigItem>
title={title}
visible={open}
onVisibleChange={onOpenChange}
onFinish={onFinish}
initialValues={{
signType: 'RSA2',
charset: 'UTF-8',
format: 'json',
gatewayUrl: 'https://openapi.alipay.com/gateway.do',
status: 1,
type: 'MINI',
...initialValues,
}}
modalProps={{ destroyOnClose: true, width: 760 }}
layout="horizontal"
labelCol={{ flex: '110px' }}
wrapperCol={{ flex: 1 }}
labelAlign="right"
>
{/* ========= 基础信息 ========= */}
<SectionTitle>基础信息</SectionTitle>
<ProForm.Group>
<ProFormSelect
name="type"
label="配置类型"
width="sm"
tooltip="MINI=小程序登录,仅做 OAuth 登录与手机号解密;PAY=交易支付,用于服务商/直连下单与回调"
options={[
{ label: '小程序登录 (MINI)', value: 'MINI' },
{ label: '交易支付 (PAY)', value: 'PAY' },
]}
rules={[{ required: true, message: '请选择配置类型' }]}
/>
<ProFormText
name="tenantId"
label="租户ID"
width="sm"
placeholder="留空使用默认租户"
/>
<ProFormText
name="appId"
label="AppID"
width="md"
rules={[{ required: true, message: '请输入支付宝 AppID' }]}
placeholder="支付宝开放平台分配的应用 AppID"
/>
<ProFormSelect
name="status"
label="状态"
width="xs"
options={[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]}
rules={[{ required: true }]}
/>
</ProForm.Group>
{/* ========= 类型差异提示 ========= */}
<ProFormDependency name={['type']}>
{({ type }) =>
type === 'PAY' ? (
<Alert
showIcon
type="info"
style={{ marginBottom: 16 }}
message="交易支付配置"
description="用于支付宝下单 / 退款 / 异步通知,需配置网关、支付回调地址;服务商模式还需 PID 与子商户号。"
/>
) : (
<Alert
showIcon
type="success"
style={{ marginBottom: 16 }}
message="小程序登录配置"
description="用于 my.getAuthCode 换 userId、my.getPhoneNumber 本地 AES 解密。AES Key 必填,否则无法解密手机号。"
/>
)
}
</ProFormDependency>
{/* ========= 密钥与签名(公共) ========= */}
<SectionTitle tip="appPrivateKey 用于商家请求签名;alipayPublicKey 用于验证支付宝返回。两把 RSA Key 缺失会导致登录/支付全部失败。">
密钥与签名
</SectionTitle>
<ProForm.Group>
<ProFormSelect
name="signType"
label="签名算法"
width="sm"
tooltip="SDK 请求签名 / 回调验签算法,开放平台默认 RSA2"
options={[
{ label: 'RSA2(推荐)', value: 'RSA2' },
{ label: 'RSA', value: 'RSA' },
]}
/>
<ProFormText name="charset" label="字符集" width="sm" />
<ProFormText name="format" label="数据格式" width="sm" />
</ProForm.Group>
<ProFormTextArea
name="appPrivateKey"
label="应用私钥"
tooltip="商家本地生成的 RSA 私钥(PKCS8),用于签名所有 OpenAPI 请求"
placeholder={`-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----`}
fieldProps={{ rows: 4, autoComplete: 'off' }}
rules={[{ required: true, message: '请输入应用私钥' }]}
/>
<ProFormTextArea
name="alipayPublicKey"
label="支付宝公钥"
tooltip="开放平台下发的支付宝公钥,用于验证响应/回调签名"
placeholder={`-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----`}
fieldProps={{ rows: 4, autoComplete: 'off' }}
rules={[{ required: true, message: '请输入支付宝公钥' }]}
/>
{/* ========= 证书模式 ========= */}
<ProFormSwitch
name="certMode"
label="证书模式"
tooltip="开启后改用支付宝公钥证书验签(需上传三份证书路径),关闭则使用普通公钥模式"
/>
<ProFormDependency name={['certMode']}>
{({ certMode }) =>
certMode ? (
<>
<ProFormText
name="appCertPath"
label="应用公钥证书路径"
placeholder="/path/to/appCertPublicKey.crt"
rules={[{ required: true, message: '证书模式下必填' }]}
/>
<ProFormText
name="alipayCertPath"
label="支付宝公钥证书路径"
placeholder="/path/to/alipayCertPublicKey_RSA2.crt"
rules={[{ required: true, message: '证书模式下必填' }]}
/>
<ProFormText
name="alipayRootCertPath"
label="支付宝根证书路径"
placeholder="/path/to/alipayRootCert.crt"
rules={[{ required: true, message: '证书模式下必填' }]}
/>
</>
) : null
}
</ProFormDependency>
{/* ========= MINI 专属:AES 加解密 Key ========= */}
<ProFormDependency name={['type']}>
{({ type }) =>
type === 'MINI' ? (
<>
<SectionTitle tip="支付宝小程序 my.getPhoneNumber 返回的密文,由商家本地 AES 解密。开放平台「开发设置 → 接口加密方式」生成。">
小程序加解密
</SectionTitle>
<ProFormText
name="encryptKey"
label="AES 加解密 Key"
tooltip="24 位 Base64 字符串。缺失只影响手机号解密,不阻断登录主链路"
placeholder="例如 pmwS5xxxxxxxxxxxxxxxxx=="
/>
</>
) : null
}
</ProFormDependency>
{/* ========= PAY 专属:网关 / 回调 / 服务商 ========= */}
<ProFormDependency name={['type']}>
{({ type }) =>
type === 'PAY' ? (
<>
<SectionTitle tip="网关地址通常无需修改;回调地址必须是公网可访问的 HTTPS 地址。">
支付参数
</SectionTitle>
<ProFormText
name="gatewayUrl"
label="网关地址"
tooltip="正式环境固定为 openapi.alipay.com;沙箱使用 openapi-sandbox.dl.alipaydev.com"
rules={[{ required: true, message: '请输入网关地址' }]}
/>
<ProFormText
name="notifyUrl"
label="支付回调地址"
placeholder="https://your-domain.com/api-order/alipay/pay/notify"
rules={[
{ required: true, message: '请输入支付回调地址' },
{ type: 'url', message: '需为合法 URL' },
]}
/>
<ProFormText
name="refundNotifyUrl"
label="退款回调地址"
placeholder="https://your-domain.com/api-order/alipay/refund/notify"
rules={[{ type: 'url', message: '需为合法 URL' }]}
/>
<SectionTitle tip="服务商模式(ISV)需配置 PID 与子商户信息;直连商户保持关闭即可。">
商户模式
</SectionTitle>
<ProFormSwitch name="isServiceMode" label="服务商模式" />
<ProFormDependency name={['isServiceMode']}>
{({ isServiceMode }) =>
isServiceMode ? (
<>
<ProFormText
name="pid"
label="合作伙伴 PID"
tooltip="服务商在支付宝开放平台的 PID"
rules={[
{ required: true, message: '服务商模式下必填' },
]}
/>
<ProFormText
name="authToken"
label="app_auth_token"
tooltip="商家授权服务商代调用 API 的 token"
/>
<ProFormText
name="subAppId"
label="商家应用 AppId"
tooltip="子商家在支付宝开放平台的小程序 AppId"
/>
<ProFormText
name="subMerchantId"
label="间连商户号 (smid)"
rules={[
{ required: true, message: '服务商模式下必填' },
]}
/>
</>
) : null
}
</ProFormDependency>
</>
) : null
}
</ProFormDependency>
{/* ========= 备注 ========= */}
<SectionTitle>其它</SectionTitle>
<ProFormText name="remark" label="备注" placeholder="可选,便于内部识别" />
</ModalForm>
);
};
export default AlipayAppForm;
@@ -0,0 +1,355 @@
import React, { useRef, useState } from 'react';
import {
PageContainer,
ProFormSelect,
ProFormText,
ProTable,
type ActionType,
} from '@ant-design/pro-components';
import { Popconfirm, Space, Tag, Tooltip, Typography, message } from 'antd';
import {
ApiOutlined,
CheckCircleFilled,
CloseCircleFilled,
DeleteOutlined,
EditOutlined,
KeyOutlined,
PlusOutlined,
PoweroffOutlined,
SafetyCertificateOutlined,
ShopOutlined,
} from '@ant-design/icons';
import {
ActionBar,
GlassCard,
GradientButton,
SearchBarPlus,
} from '@/components/ui';
import { alipayConfigApi, AlipayConfigItem } from '@/services/alipayConfig';
import AlipayAppForm from './components/AlipayAppForm';
const { Text } = Typography;
const TYPE_META: Record<
string,
{ label: string; color: string; icon: React.ReactNode }
> = {
MINI: { label: '小程序登录', color: 'green', icon: <ApiOutlined /> },
PAY: { label: '交易支付', color: 'blue', icon: <ShopOutlined /> },
};
const AlipayAppPage: React.FC = () => {
const [searchParams, setSearchParams] = useState<Record<string, any>>({});
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<AlipayConfigItem | undefined>(undefined);
const actionRef = useRef<ActionType>();
const reload = () => actionRef.current?.reload();
const columns: any[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
width: 56,
align: 'center',
},
{
title: '配置类型',
dataIndex: 'type',
width: 130,
render: (_: any, record: AlipayConfigItem) => {
const meta = TYPE_META[record.type] ?? TYPE_META.MINI;
return (
<Tag
color={meta.color}
icon={meta.icon}
style={{ padding: '2px 10px', borderRadius: 12 }}
>
{meta.label}
</Tag>
);
},
},
{
title: '租户',
dataIndex: 'tenantId',
width: 110,
copyable: true,
ellipsis: true,
render: (text: any) =>
text ? (
<Text copyable={{ tooltips: ['复制', '已复制'] }}>{text}</Text>
) : (
<Text type="secondary">默认</Text>
),
},
{
title: 'AppID',
dataIndex: 'appId',
width: 220,
ellipsis: true,
render: (_: any, record: AlipayConfigItem) => (
<Space size={6}>
<KeyOutlined style={{ color: '#8c8c8c' }} />
<Text copyable={{ text: record.appId }} style={{ marginBottom: 0 }}>
{record.appId}
</Text>
</Space>
),
},
{
title: '签名',
dataIndex: 'signType',
width: 90,
align: 'center',
render: (_: any, record: AlipayConfigItem) => (
<Tag color="purple" style={{ marginRight: 0 }}>
{record.signType || 'RSA2'}
</Tag>
),
},
{
title: '验签方式',
dataIndex: 'certMode',
width: 110,
align: 'center',
render: (_: any, record: AlipayConfigItem) => (
<Tag
icon={<SafetyCertificateOutlined />}
color={record.certMode ? 'orange' : 'default'}
>
{record.certMode ? '证书模式' : '公钥模式'}
</Tag>
),
},
{
title: '商户模式',
dataIndex: 'isServiceMode',
width: 110,
align: 'center',
render: (_: any, record: AlipayConfigItem) =>
record.type === 'PAY' ? (
<Tag color={record.isServiceMode ? 'geekblue' : 'default'}>
{record.isServiceMode ? '服务商 ISV' : '直连商户'}
</Tag>
) : (
<Text type="secondary">—</Text>
),
},
{
title: '支付回调',
dataIndex: 'notifyUrl',
ellipsis: true,
render: (_: any, record: AlipayConfigItem) =>
record.type === 'PAY' && record.notifyUrl ? (
<Tooltip title={record.notifyUrl}>
<span
style={{
display: 'inline-block',
maxWidth: 220,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
verticalAlign: 'bottom',
}}
>
{record.notifyUrl}
</span>
</Tooltip>
) : (
<Text type="secondary">—</Text>
),
},
{
title: '状态',
dataIndex: 'status',
width: 100,
align: 'center',
render: (_: any, record: AlipayConfigItem) =>
record.status === 1 ? (
<Tag icon={<CheckCircleFilled />} color="success">
启用
</Tag>
) : (
<Tag icon={<CloseCircleFilled />} color="error">
禁用
</Tag>
),
},
{
title: '操作',
key: 'action',
width: 220,
fixed: 'right',
render: (_: any, entity: AlipayConfigItem) => (
<Space size={4}>
<a
onClick={() => {
setCurrent(entity);
setEditOpen(true);
}}
>
<EditOutlined /> 编辑
</a>
<Popconfirm
title={
entity.status === 1
? '确认禁用?禁用后该应用不可用于登录或支付'
: '确认启用?启用后该应用立即可用'
}
okText="确定"
cancelText="取消"
onConfirm={async () => {
const newStatus = entity.status === 1 ? 0 : 1;
try {
await alipayConfigApi.toggleStatus(
entity.id!,
newStatus as 0 | 1,
);
message.success('切换成功');
reload();
} catch (e) {
message.error('切换失败');
}
}}
>
<a style={{ color: entity.status === 1 ? '#fa8c16' : '#52c41a' }}>
<PoweroffOutlined /> {entity.status === 1 ? '禁用' : '启用'}
</a>
</Popconfirm>
<Popconfirm
title="确认删除?删除后不可恢复,请谨慎操作"
okText="确定"
okButtonProps={{ danger: true }}
cancelText="取消"
onConfirm={async () => {
try {
await alipayConfigApi.remove(entity.id!);
message.success('删除成功');
reload();
} catch (e) {
message.error('删除失败');
}
}}
>
<a style={{ color: '#ff4d4f' }}>
<DeleteOutlined /> 删除
</a>
</Popconfirm>
</Space>
),
},
];
return (
<PageContainer
header={{
title: '支付宝应用管理',
subTitle: '统一维护小程序登录与交易支付的支付宝开放平台配置',
}}
>
<SearchBarPlus
defaultCollapsed
split
onTenantChanged={() => {}}
onFinish={async (values) => setSearchParams(values)}
>
<ProFormSelect
name="searchKey"
label="检索"
valueEnum={{ type: '类型', appId: 'AppID', tenantId: '租户' }}
/>
<ProFormText name="searchValue" placeholder="请输入关键字" />
</SearchBarPlus>
<ActionBar
left={
<GradientButton
size="middle"
key="add"
type="primary"
onClick={() => setCreateOpen(true)}
>
<PlusOutlined /> 新增配置
</GradientButton>
}
/>
<GlassCard bodyStyle={{ padding: 0 }}>
<ProTable<AlipayConfigItem>
rowKey="id"
actionRef={actionRef}
headerTitle={
<Space>
<span style={{ fontWeight: 600 }}>支付宝应用列表</span>
<Text type="secondary" style={{ fontSize: 12 }}>
同一租户可同时配置多个 AppID
</Text>
</Space>
}
request={async (params) => {
const res = await alipayConfigApi.list({
page: (params as any).current || 1,
limit: (params as any).pageSize || 10,
searchKey: searchParams.searchKey,
searchValue: searchParams.searchValue,
});
return {
data: (res as any).data,
success: (res as any).resp_code === 0,
total: (res as any).total,
} as any;
}}
columns={columns}
search={false}
params={searchParams}
scroll={{ x: 1280 }}
pagination={{
showSizeChanger: true,
showQuickJumper: true,
showTotal: (t) => `共 ${t} 条`,
}}
toolBarRender={false}
/>
</GlassCard>
<AlipayAppForm
title="新增支付宝应用"
open={createOpen}
onOpenChange={setCreateOpen}
onFinish={async (values) => {
try {
await alipayConfigApi.create(values);
message.success('新增成功');
reload();
return true;
} catch (e) {
message.error('保存失败');
return false;
}
}}
/>
<AlipayAppForm
title="编辑支付宝应用"
open={editOpen}
initialValues={current}
onOpenChange={setEditOpen}
onFinish={async (values) => {
try {
await alipayConfigApi.update({ ...(current as any), ...values });
message.success('修改成功');
reload();
return true;
} catch (e) {
message.error('修改失败');
return false;
}
}}
/>
</PageContainer>
);
};
export default AlipayAppPage;
@@ -0,0 +1,59 @@
import { request } from 'umi';
export interface AlipayConfigItem {
id?: number;
tenantId?: string;
type: 'MINI' | 'PAY';
appId: string;
appPrivateKey?: string;
alipayPublicKey?: string;
signType?: 'RSA2' | 'RSA';
charset?: string;
format?: string;
encryptKey?: string;
gatewayUrl?: string;
notifyUrl?: string;
refundNotifyUrl?: string;
isServiceMode?: boolean;
pid?: string;
authToken?: string;
subAppId?: string;
subMerchantId?: string;
certMode?: boolean;
appCertPath?: string;
alipayCertPath?: string;
alipayRootCertPath?: string;
status?: 0 | 1;
remark?: string;
}
export const alipayConfigApi = {
list: async (params: { page?: number; limit?: number; searchKey?: string; searchValue?: string }) => {
const res = await request('/api-order/alipay/config/list', { method: 'GET', params });
return {
data: (res as any).data?.data || [],
total: (res as any).data?.count || 0,
resp_code: (res as any).resp_code,
resp_msg: (res as any).resp_msg,
};
},
create: async (data: AlipayConfigItem) => {
const res = await request('/api-order/alipay/config', { method: 'POST', data });
return (res as any).data || res;
},
update: async (data: AlipayConfigItem) => {
const res = await request('/api-order/alipay/config', { method: 'PUT', data });
return (res as any).data || res;
},
remove: async (id: number) => {
const res = await request(`/api-order/alipay/config/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
toggleStatus: async (id: number, status: 0 | 1) => {
const res = await request(`/api-order/alipay/config/${id}/status`, {
method: 'PATCH',
data: { status },
});
return (res as any).data || res;
},
};