feat(M05-A): 建立统一支付领域与幂等回调

This commit is contained in:
Codex
2026-06-20 14:30:35 +08:00
parent f9ec0af2ee
commit 6c506ff862
19 changed files with 905 additions and 14 deletions
+117
View File
@@ -0,0 +1,117 @@
import type { FastifyInstance, FastifyReply } from 'fastify';
import { z } from 'zod';
import type { AuthRepository } from '../auth/auth-repository.js';
import { authenticateAccessToken } from '../auth/authenticate.js';
import {
PaymentError, type PaymentRepository
} from '../payments/payment-repository.js';
const createSchema = z.object({
orderId: z.string().regex(/^[1-9]\d{0,19}$/),
provider: z.enum(['WECHAT', 'BALANCE', 'PACKAGE', 'GROUP_BUY', 'TEST']),
clientRequestId: z.string().min(8).max(128)
}).strict();
const paymentParams = z.object({ paymentId: z.string().regex(/^[1-9]\d{0,19}$/) });
const callbackSchema = z.object({
callbackId: z.string().min(8).max(128),
amountCents: z.number().int().positive()
}).strict();
export interface PaymentRouteOptions {
repository: Pick<PaymentRepository, 'createPayment' | 'processTestCallback'>;
authRepository: Pick<AuthRepository, 'validateSession'>;
jwtSecret: string;
testAdapterEnabled: boolean;
}
export async function registerPaymentRoutes(
app: FastifyInstance, options: PaymentRouteOptions
) {
app.post('/app-api/payments', async (request, reply) => {
const auth = await authenticate(request.headers.authorization, options);
const body = createSchema.safeParse(request.body);
if (!auth) return unauthorized(reply, request.traceId);
if (!body.success) return invalid(reply, request.traceId);
return handle(reply, request.traceId, async () => reply.status(201).send({
code: 0,
data: await options.repository.createPayment({
tenantId: auth.tenantId,
platformAppId: auth.platformAppId,
userId: auth.userId,
orderId: body.data.orderId,
provider: body.data.provider,
clientRequestId: body.data.clientRequestId,
testAdapterEnabled: options.testAdapterEnabled
}),
traceId: request.traceId
}));
});
app.post('/app-api/payments/:paymentId/test-complete', async (request, reply) => {
const auth = await authenticate(request.headers.authorization, options);
const params = paymentParams.safeParse(request.params);
const body = callbackSchema.safeParse(request.body);
if (!auth) return unauthorized(reply, request.traceId);
if (!params.success || !body.success) return invalid(reply, request.traceId);
return handle(reply, request.traceId, async () => {
const data = await options.repository.processTestCallback({
tenantId: auth.tenantId,
userId: auth.userId,
paymentId: params.data.paymentId,
callbackId: body.data.callbackId,
amountCents: body.data.amountCents,
testAdapterEnabled: options.testAdapterEnabled,
traceId: request.traceId
});
if ('code' in data && data.code === 'PAYMENT_AMOUNT_MISMATCH') {
return reply.status(400).send({
code: data.code,
message: 'The callback amount does not match the payment.',
data,
traceId: request.traceId
});
}
return { code: 0, data, traceId: request.traceId };
});
});
}
async function authenticate(
authorization: string | undefined, options: PaymentRouteOptions
) {
const result = await authenticateAccessToken(
authorization, options.authRepository, options.jwtSecret
);
if (!result) return null;
return {
tenantId: result.session.tenantId,
platformAppId: result.session.platformAppId,
userId: result.session.user.id
};
}
async function handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
try {
return await work();
} catch (error) {
if (!(error instanceof PaymentError)) throw error;
const status = error.code === 'ORDER_NOT_FOUND' || error.code === 'PAYMENT_NOT_FOUND'
? 404 : error.code === 'PAYMENT_IDEMPOTENCY_CONFLICT' ? 409
: error.code.includes('FORBIDDEN') ? 403 : 400;
return reply.status(status).send({
code: error.code, message: 'The payment request is not available.', traceId
});
}
}
function unauthorized(reply: FastifyReply, traceId: string) {
return reply.status(401).send({
code: 'AUTH_SESSION_INVALID', message: 'Authentication required.', traceId
});
}
function invalid(reply: FastifyReply, traceId: string) {
return reply.status(400).send({
code: 'INVALID_PAYMENT_REQUEST', message: 'The payment request is invalid.', traceId
});
}