微信JSSDK对接,代下单支付
This commit is contained in:
@@ -1,9 +1,17 @@
|
||||
import type { WechatJsapiPrepayParams } from '@dukang/shared-types';
|
||||
|
||||
export type PayMethod = 'JSAPI' | 'NATIVE';
|
||||
|
||||
export type PayOrderResult =
|
||||
| { mode: 'mock'; externalNo: string }
|
||||
| { mode: 'jsapi'; prepay: WechatJsapiPrepayParams };
|
||||
| { mode: 'jsapi'; prepay: WechatJsapiPrepayParams }
|
||||
| { mode: 'native'; codeUrl: string; externalNo: string };
|
||||
|
||||
export interface IPayProvider {
|
||||
payOrder(orderId: bigint, openId?: string, platform?: 'h5' | 'mini'): Promise<PayOrderResult>;
|
||||
payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform?: 'h5' | 'mini',
|
||||
payMethod?: PayMethod,
|
||||
): Promise<PayOrderResult>;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { loadAppConfig } from '@dukang/shared-types';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PayMockProvider implements IPayProvider {
|
||||
async payOrder(_orderId: bigint, _openId?: string, _platform?: 'h5' | 'mini'): Promise<PayOrderResult> {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async payOrder(
|
||||
orderId: bigint,
|
||||
_openId?: string,
|
||||
_platform?: 'h5' | 'mini',
|
||||
payMethod: PayMethod = 'JSAPI',
|
||||
): Promise<PayOrderResult> {
|
||||
if (!loadAppConfig().mockPay) {
|
||||
throw new Error('Real WeChat pay requires PayWechatProvider');
|
||||
}
|
||||
if (payMethod === 'NATIVE') {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
const orderNo = order?.orderNo ?? orderId.toString();
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl: `mock://wechat-pay/native?orderNo=${encodeURIComponent(orderNo)}`,
|
||||
externalNo: `MOCK-NATIVE-${Date.now()}`,
|
||||
};
|
||||
}
|
||||
return { mode: 'mock', externalNo: `MOCK-${Date.now()}` };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { loadAppConfig } from '@dukang/shared-types';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
import { PayMockProvider } from './pay.mock.provider';
|
||||
import { PayWechatProvider } from './pay.wechat.provider';
|
||||
|
||||
/** 按当前 process.env 动态选择 Mock / 微信 JSAPI 支付 */
|
||||
/** 按当前 process.env 动态选择 Mock / 微信支付 */
|
||||
@Injectable()
|
||||
export class PayRouterProvider implements IPayProvider {
|
||||
constructor(
|
||||
@@ -16,7 +16,12 @@ export class PayRouterProvider implements IPayProvider {
|
||||
return loadAppConfig().mockPay ? this.mock : this.wechat;
|
||||
}
|
||||
|
||||
payOrder(orderId: bigint, openId?: string, platform?: 'h5' | 'mini'): Promise<PayOrderResult> {
|
||||
return this.resolve().payOrder(orderId, openId, platform);
|
||||
payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform?: 'h5' | 'mini',
|
||||
payMethod?: PayMethod,
|
||||
): Promise<PayOrderResult> {
|
||||
return this.resolve().payOrder(orderId, openId, platform, payMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { loadAppConfig } from '@dukang/shared-types';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { WECHAT_PROVIDER } from '../integrations.constants';
|
||||
import type { IWechatProvider } from '../wechat/wechat.interface';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PayWechatProvider implements IPayProvider {
|
||||
@@ -14,28 +14,60 @@ export class PayWechatProvider implements IPayProvider {
|
||||
@Inject(WECHAT_PROVIDER) private readonly wechat: IWechatProvider,
|
||||
) {}
|
||||
|
||||
async payOrder(orderId: bigint, openId?: string, platform: 'h5' | 'mini' = 'h5'): Promise<PayOrderResult> {
|
||||
async payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform: 'h5' | 'mini' = 'h5',
|
||||
payMethod: PayMethod = 'JSAPI',
|
||||
): Promise<PayOrderResult> {
|
||||
if (loadAppConfig().mockPay) {
|
||||
if (payMethod === 'NATIVE') {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
const orderNo = order?.orderNo ?? orderId.toString();
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl: `mock://wechat-pay/native?orderNo=${encodeURIComponent(orderNo)}`,
|
||||
externalNo: `MOCK-NATIVE-${Date.now()}`,
|
||||
};
|
||||
}
|
||||
return { mode: 'mock', externalNo: `MOCK-${Date.now()}` };
|
||||
}
|
||||
if (!this.wechat.isPayEnabled()) {
|
||||
throw new Error('微信支付未配置:请关闭 MOCK_PAY 并配置 WX_MCH_ID 等商户参数');
|
||||
}
|
||||
if (!openId) {
|
||||
throw new Error('微信支付需要用户 openId,请先完成微信授权登录');
|
||||
}
|
||||
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
if (!order) throw new Error('订单不存在');
|
||||
|
||||
const amountFen = Math.round(Number(order.payAmount) * 100);
|
||||
const notifyUrl = process.env.WX_PAY_NOTIFY_URL ?? '';
|
||||
|
||||
if (payMethod === 'NATIVE') {
|
||||
this.logger.log(`create NATIVE prepay order=${order.orderNo} mchid=${this.wechat.getMchId()}`);
|
||||
const { codeUrl } = await this.wechat.createNativePrepay({
|
||||
orderNo: order.orderNo,
|
||||
description: `杜康好客订单 ${order.orderNo}`,
|
||||
amountFen,
|
||||
notifyUrl,
|
||||
});
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl,
|
||||
externalNo: `NATIVE-${order.orderNo}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!openId) {
|
||||
throw new Error('微信支付需要用户 openId,请先完成微信授权登录');
|
||||
}
|
||||
|
||||
this.logger.log(`create JSAPI prepay order=${order.orderNo} mchid=${this.wechat.getMchId()} platform=${platform}`);
|
||||
const prepay = await this.wechat.createJsapiPrepay({
|
||||
orderNo: order.orderNo,
|
||||
description: `杜康好客订单 ${order.orderNo}`,
|
||||
amountFen,
|
||||
openId,
|
||||
notifyUrl: process.env.WX_PAY_NOTIFY_URL ?? '',
|
||||
notifyUrl,
|
||||
platform,
|
||||
});
|
||||
return { mode: 'jsapi', prepay };
|
||||
|
||||
@@ -553,6 +553,55 @@ export class WechatApiProvider implements IWechatProvider {
|
||||
};
|
||||
}
|
||||
|
||||
async createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}) {
|
||||
if (!this.isPayEnabled()) {
|
||||
throw new InternalServerErrorException(
|
||||
'微信支付未配置:请关闭 MOCK_PAY 并配置 WX_MCH_ID、WX_MCH_SERIAL_NO、WX_MCH_PRIVATE_KEY、WX_API_V3_KEY',
|
||||
);
|
||||
}
|
||||
const notifyUrl = params.notifyUrl || this.notifyUrl;
|
||||
if (!notifyUrl) {
|
||||
throw new InternalServerErrorException('请配置 WX_PAY_NOTIFY_URL');
|
||||
}
|
||||
const payAppId = this.appId || this.miniAppId;
|
||||
if (!payAppId) {
|
||||
throw new InternalServerErrorException('微信支付未配置:请设置 WX_APP_ID');
|
||||
}
|
||||
const body = {
|
||||
appid: payAppId,
|
||||
mchid: this.mchId,
|
||||
description: params.description,
|
||||
out_trade_no: params.orderNo,
|
||||
notify_url: notifyUrl,
|
||||
amount: { total: params.amountFen, currency: 'CNY' },
|
||||
};
|
||||
const path = '/v3/pay/transactions/native';
|
||||
const payload = JSON.stringify(body);
|
||||
const auth = this.signPayRequest('POST', path, payload);
|
||||
const res = await this.fetchPayJson<{ code_url?: string }>(
|
||||
`https://api.mch.weixin.qq.com${path}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: auth,
|
||||
},
|
||||
body: payload,
|
||||
},
|
||||
);
|
||||
if (!res.code_url) {
|
||||
throw new InternalServerErrorException('微信 Native 下单失败');
|
||||
}
|
||||
this.logger.log(`NATIVE prepay ok mchid=${this.mchId} orderNo=${params.orderNo}`);
|
||||
return { codeUrl: res.code_url };
|
||||
}
|
||||
|
||||
async parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
rawBody: string,
|
||||
|
||||
@@ -51,6 +51,10 @@ export class WechatDisabledProvider implements IWechatProvider {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
createNativePrepay() {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
parsePayNotification() {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
@@ -132,6 +132,14 @@ export interface IWechatProvider {
|
||||
platform?: 'h5' | 'mini';
|
||||
}): Promise<WechatJsapiPrepayParams>;
|
||||
|
||||
/** 创建 Native 扫码支付 code_url */
|
||||
createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}): Promise<{ codeUrl: string }>;
|
||||
|
||||
/** 解析并验签支付回调通知 */
|
||||
parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
|
||||
@@ -80,6 +80,10 @@ export class WechatMockProvider implements IWechatProvider {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
createNativePrepay(): never {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
parsePayNotification(): never {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
@@ -80,6 +80,15 @@ export class WechatRouterProvider implements IWechatProvider {
|
||||
return this.resolve().createJsapiPrepay(params);
|
||||
}
|
||||
|
||||
createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}) {
|
||||
return this.resolve().createNativePrepay(params);
|
||||
}
|
||||
|
||||
parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
rawBody: string,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
@@ -10,7 +10,11 @@ import type { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||
import { TradeService } from '../trade/trade.service';
|
||||
import { HqProxyOrderCreateDto, HqProxyOrderPreviewDto } from './dto/hq-proxy-order.dto';
|
||||
import {
|
||||
HqProxyOrderCreateDto,
|
||||
HqProxyOrderPayDto,
|
||||
HqProxyOrderPreviewDto,
|
||||
} from './dto/hq-proxy-order.dto';
|
||||
|
||||
@Controller('admin/proxy-orders')
|
||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||
@@ -42,4 +46,19 @@ export class AdminProxyOrdersController {
|
||||
) {
|
||||
return this.tradeService.createHqProxyOrder(user.actorId, dto, req);
|
||||
}
|
||||
|
||||
@Post(':id/pay')
|
||||
pay(@Param('id') id: string, @Body() dto: HqProxyOrderPayDto) {
|
||||
return this.tradeService.payHqProxyOrder(BigInt(id), dto.payMethod ?? 'NATIVE');
|
||||
}
|
||||
|
||||
@Post(':id/pay/mock-confirm')
|
||||
mockConfirmPay(@Param('id') id: string) {
|
||||
return this.tradeService.mockConfirmProxyPay(BigInt(id), { hq: true });
|
||||
}
|
||||
|
||||
@Get(':id/pay-status')
|
||||
payStatus(@Param('id') id: string) {
|
||||
return this.tradeService.getProxyPayStatus(BigInt(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,3 +85,9 @@ export class HqProxyOrderCreateDto {
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
}
|
||||
|
||||
export class HqProxyOrderPayDto {
|
||||
@IsOptional()
|
||||
@IsIn(['NATIVE', 'JSAPI'])
|
||||
payMethod?: 'NATIVE' | 'JSAPI';
|
||||
}
|
||||
|
||||
@@ -93,3 +93,8 @@ export class PartnerProxyOrderCreateDto {
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
}
|
||||
|
||||
export class PartnerProxyOrderPayDto {
|
||||
@IsIn(['NATIVE', 'JSAPI'])
|
||||
payMethod: 'NATIVE' | 'JSAPI';
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { PartnerPermissionGuard } from '../../common/guards/partner-permission.g
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import {
|
||||
PartnerProxyOrderCreateDto,
|
||||
PartnerProxyOrderPayDto,
|
||||
PartnerProxyOrderPreviewDto,
|
||||
} from './dto/partner-proxy-order.dto';
|
||||
import { ManualShipOrderDto } from '../ops/dto/admin-mutate.dto';
|
||||
@@ -223,11 +224,6 @@ export class PartnerProxyOrderController {
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
}
|
||||
|
||||
@Post('preview')
|
||||
preview(@CurrentUser() user: AuthUser, @Body() dto: PartnerProxyOrderPreviewDto) {
|
||||
return this.tradeService.previewPartnerProxyOrderForPartner(user.actorId, dto);
|
||||
@@ -241,4 +237,36 @@ export class PartnerProxyOrderController {
|
||||
) {
|
||||
return this.tradeService.createPartnerProxyOrder(user.actorId, dto, req);
|
||||
}
|
||||
|
||||
@Post(':id/pay')
|
||||
pay(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: PartnerProxyOrderPayDto,
|
||||
) {
|
||||
return this.tradeService.payPartnerProxyOrder(user.actorId, BigInt(id), dto.payMethod);
|
||||
}
|
||||
|
||||
@Post(':id/pay/mock-confirm')
|
||||
mockConfirmPay(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.mockConfirmProxyPay(BigInt(id), {
|
||||
partnerAccountId: user.actorId,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id/pay-status')
|
||||
async payStatus(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
await this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
return this.tradeService.getProxyPayStatus(BigInt(id));
|
||||
}
|
||||
|
||||
@Get(':id/track')
|
||||
track(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrderTrack(user.actorId, BigInt(id));
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1257,7 +1257,7 @@ export class TradeService {
|
||||
}
|
||||
|
||||
const orderNo = generateOrderNo();
|
||||
const now = new Date();
|
||||
const payExpireAt = new Date(Date.now() + 30 * 60 * 1000);
|
||||
const location = buildOrderClientLocationSnapshot(
|
||||
req,
|
||||
this.ipGeoService.resolve(extractClientIp(req)),
|
||||
@@ -1271,10 +1271,10 @@ export class TradeService {
|
||||
orderType: 'PROXY',
|
||||
userId: user.id,
|
||||
cityId: city.id,
|
||||
status: 'COMPLETED',
|
||||
payStatus: 'PAID',
|
||||
status: 'PENDING_PAY',
|
||||
payStatus: 'UNPAID',
|
||||
deliveryType: preview.deliveryType,
|
||||
channelSource: 'OFFLINE_PROXY',
|
||||
channelSource: 'PROXY_ONLINE',
|
||||
promoCodeId,
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
@@ -1299,9 +1299,7 @@ export class TradeService {
|
||||
ipProvince: location.ipProvince,
|
||||
ipCity: location.ipCity,
|
||||
ipDistrict: location.ipDistrict,
|
||||
paidAt: now,
|
||||
shippedAt: now,
|
||||
completedAt: now,
|
||||
payExpireAt,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? primary.id,
|
||||
orderCommissionRateAtPay: paySnapshot?.orderCommissionRate ?? null,
|
||||
proxyPartnerAccountId: primary.id,
|
||||
@@ -1312,23 +1310,13 @@ export class TradeService {
|
||||
include: { product: true, imageResource: true },
|
||||
});
|
||||
|
||||
await tx.orderDelivery.create({
|
||||
data: {
|
||||
orderId: created.id,
|
||||
provider: 'MANUAL',
|
||||
outWarehouseAt: now,
|
||||
shippingAt: now,
|
||||
deliveredAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: created.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus: 'COMPLETED',
|
||||
toStatus: 'PENDING_PAY',
|
||||
operator: 'PARTNER_PROXY',
|
||||
remark: `合伙人线下代下单 mode=${body.deliveryMode} customer=${normalizedPhone} partner=${primary.id}`,
|
||||
remark: `合伙人代下单待支付 mode=${body.deliveryMode} customer=${normalizedPhone} partner=${primary.id}`,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1342,8 +1330,6 @@ export class TradeService {
|
||||
return created;
|
||||
});
|
||||
|
||||
await this.benefitService.grantOnOrderPaid(order.id);
|
||||
|
||||
this.analyticsService.trackPartnerOneSafe(partnerAccountId, 'PARTNER_H5', {
|
||||
partnerAccountId: primary.id,
|
||||
eventName: 'partner_proxy_order_create',
|
||||
@@ -1359,7 +1345,17 @@ export class TradeService {
|
||||
},
|
||||
});
|
||||
|
||||
return serializeBigInt(mapOrderCompat(order));
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
benefitAmount: Number(order.benefitAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
proxyPartnerName: primary.name,
|
||||
};
|
||||
}
|
||||
|
||||
/** 合伙人代下单列表:按 proxyPartnerAccountId 归属,与管仓订单无关 */
|
||||
@@ -1547,7 +1543,7 @@ export class TradeService {
|
||||
}
|
||||
|
||||
const orderNo = generateOrderNo();
|
||||
const now = new Date();
|
||||
const payExpireAt = new Date(Date.now() + 30 * 60 * 1000);
|
||||
const location = buildOrderClientLocationSnapshot(
|
||||
req,
|
||||
this.ipGeoService.resolve(extractClientIp(req)),
|
||||
@@ -1561,10 +1557,10 @@ export class TradeService {
|
||||
orderType: 'PROXY',
|
||||
userId: user.id,
|
||||
cityId: city.id,
|
||||
status: 'COMPLETED',
|
||||
payStatus: 'PAID',
|
||||
status: 'PENDING_PAY',
|
||||
payStatus: 'UNPAID',
|
||||
deliveryType: preview.deliveryType,
|
||||
channelSource: 'OFFLINE_PROXY',
|
||||
channelSource: 'PROXY_ONLINE',
|
||||
promoCodeId,
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
@@ -1589,9 +1585,7 @@ export class TradeService {
|
||||
ipProvince: location.ipProvince,
|
||||
ipCity: location.ipCity,
|
||||
ipDistrict: location.ipDistrict,
|
||||
paidAt: now,
|
||||
shippedAt: now,
|
||||
completedAt: now,
|
||||
payExpireAt,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? null,
|
||||
orderCommissionRateAtPay: paySnapshot?.orderCommissionRate ?? null,
|
||||
proxyPartnerAccountId: null,
|
||||
@@ -1602,23 +1596,13 @@ export class TradeService {
|
||||
include: { product: true, imageResource: true },
|
||||
});
|
||||
|
||||
await tx.orderDelivery.create({
|
||||
data: {
|
||||
orderId: created.id,
|
||||
provider: 'MANUAL',
|
||||
outWarehouseAt: now,
|
||||
shippingAt: now,
|
||||
deliveredAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: created.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus: 'COMPLETED',
|
||||
toStatus: 'PENDING_PAY',
|
||||
operator: 'HQ_PROXY',
|
||||
remark: `总部线下代下单 mode=${body.deliveryMode} customer=${normalizedPhone} hq=${hq.id}`,
|
||||
remark: `总部代下单待支付 mode=${body.deliveryMode} customer=${normalizedPhone} hq=${hq.id}`,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1632,15 +1616,245 @@ export class TradeService {
|
||||
return created;
|
||||
});
|
||||
|
||||
await this.benefitService.grantOnOrderPaid(order.id);
|
||||
|
||||
return serializeBigInt({
|
||||
id: order.id,
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
benefitAmount: Number(order.benefitAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
proxyPartnerName: proxyDisplayName,
|
||||
};
|
||||
}
|
||||
|
||||
/** 合伙人代下单支付:NATIVE 商家码 / JSAPI 合伙人微信代付 */
|
||||
async payPartnerProxyOrder(
|
||||
partnerAccountId: bigint,
|
||||
orderId: bigint,
|
||||
payMethod: 'NATIVE' | 'JSAPI',
|
||||
) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.status !== 'PENDING_PAY' || order.payStatus !== 'UNPAID') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
if (order.payExpireAt && order.payExpireAt.getTime() < Date.now()) {
|
||||
throw new BadRequestException('订单已超时未支付');
|
||||
}
|
||||
|
||||
let openId: string | undefined;
|
||||
if (payMethod === 'JSAPI') {
|
||||
openId = primary.wxOpenId ?? undefined;
|
||||
const appConfig = loadAppConfig();
|
||||
if (!appConfig.mockPay && !openId) {
|
||||
throw new BadRequestException('请先在微信内登录并绑定微信后再代付');
|
||||
}
|
||||
}
|
||||
|
||||
const payResult = await this.payProvider.payOrder(orderId, openId, 'h5', payMethod);
|
||||
|
||||
if (payResult.mode === 'native') {
|
||||
return {
|
||||
mode: 'native' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
codeUrl: payResult.codeUrl,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
if (payResult.mode === 'jsapi') {
|
||||
return {
|
||||
mode: 'jsapi' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
prepay: payResult.prepay,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
await this.markProxyOrderPaid(order.id, payResult.externalNo, 'PARTNER_PROXY_MOCK_PAY');
|
||||
return {
|
||||
mode: 'mock' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 总部代下单支付:仅 Native 收款码 */
|
||||
async payHqProxyOrder(orderId: bigint, payMethod: 'NATIVE' | 'JSAPI' = 'NATIVE') {
|
||||
if (payMethod !== 'NATIVE') {
|
||||
throw new BadRequestException('总部代下单仅支持收款码支付');
|
||||
}
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, orderType: 'PROXY' },
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.status !== 'PENDING_PAY' || order.payStatus !== 'UNPAID') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
if (order.payExpireAt && order.payExpireAt.getTime() < Date.now()) {
|
||||
throw new BadRequestException('订单已超时未支付');
|
||||
}
|
||||
|
||||
const payResult = await this.payProvider.payOrder(orderId, undefined, 'h5', 'NATIVE');
|
||||
if (payResult.mode !== 'native') {
|
||||
throw new BadRequestException('无法生成收款码');
|
||||
}
|
||||
return {
|
||||
mode: 'native' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
codeUrl: payResult.codeUrl,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Mock 环境确认代下单支付 */
|
||||
async mockConfirmProxyPay(
|
||||
orderId: bigint,
|
||||
opts: { partnerAccountId?: bigint; hq?: boolean },
|
||||
) {
|
||||
const appConfig = loadAppConfig();
|
||||
if (!appConfig.mockPay) {
|
||||
throw new BadRequestException('仅 MOCK_PAY 环境可用');
|
||||
}
|
||||
|
||||
let order;
|
||||
if (opts.partnerAccountId != null) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(opts.partnerAccountId);
|
||||
order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, orderType: 'PROXY' },
|
||||
});
|
||||
}
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.payStatus === 'PAID') {
|
||||
return this.getProxyPayStatus(order.id);
|
||||
}
|
||||
if (order.status !== 'PENDING_PAY') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
|
||||
await this.markProxyOrderPaid(
|
||||
order.id,
|
||||
`MOCK-CONFIRM-${Date.now()}`,
|
||||
opts.hq ? 'HQ_PROXY_MOCK_PAY' : 'PARTNER_PROXY_MOCK_PAY',
|
||||
);
|
||||
return this.getProxyPayStatus(order.id);
|
||||
}
|
||||
|
||||
async getProxyPayStatus(orderId: bigint) {
|
||||
const order = await this.prisma.order.findUnique({
|
||||
where: { id: orderId },
|
||||
select: {
|
||||
id: true,
|
||||
orderNo: true,
|
||||
status: true,
|
||||
payStatus: true,
|
||||
payAmount: true,
|
||||
deliveryType: true,
|
||||
payExpireAt: true,
|
||||
paidAt: true,
|
||||
},
|
||||
});
|
||||
if (!order) throw new NotFoundException('订单不存在');
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
paidAt: order.paidAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async getPartnerProxyOrderTrack(partnerAccountId: bigint, orderId: bigint) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
select: { id: true, deliveryType: true },
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
return this.fulfillmentService.getOrderTrack(orderId);
|
||||
}
|
||||
|
||||
private async markProxyOrderPaid(orderId: bigint, externalNo: string, operator: string) {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
if (!order) throw new NotFoundException('订单不存在');
|
||||
if (order.payStatus === 'PAID') return;
|
||||
|
||||
const now = new Date();
|
||||
const paySnapshot = await this.partnerCityService.resolveForOrder(
|
||||
order.cityId,
|
||||
order.receiverDistrict,
|
||||
);
|
||||
const toStatus =
|
||||
order.deliveryType === 'ON_SITE_PICKUP' ? 'PENDING_RECEIVE' : 'PENDING_SHIP';
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.order.update({
|
||||
where: { id: order.id },
|
||||
data: {
|
||||
status: toStatus,
|
||||
payStatus: 'PAID',
|
||||
paidAt: now,
|
||||
payExternalNo: externalNo,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? order.partnerAccountIdAtPay,
|
||||
orderCommissionRateAtPay:
|
||||
paySnapshot?.orderCommissionRate ?? order.orderCommissionRateAtPay,
|
||||
},
|
||||
});
|
||||
await tx.logThirdParty.create({
|
||||
data: {
|
||||
provider: 'WECHAT_PAY',
|
||||
scene: 'ORDER_PAY',
|
||||
refType: 'ORDER',
|
||||
refId: order.id,
|
||||
externalNo,
|
||||
amount: order.payAmount,
|
||||
status: 'SUCCESS',
|
||||
},
|
||||
});
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: order.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus,
|
||||
operator,
|
||||
}),
|
||||
});
|
||||
const delivery = await tx.orderDelivery.findUnique({ where: { orderId: order.id } });
|
||||
if (!delivery) {
|
||||
await tx.orderDelivery.create({
|
||||
data: { orderId: order.id, provider: 'MANUAL' },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await this.afterOrderPaid(order.id);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user