feat(payment): implement Zibal IPG payment gateway integration, admin merchant configuration and verification page
Deploy Canina / deploy (push) Successful in 3m28s
Deploy Canina / deploy (push) Successful in 3m28s
This commit is contained in:
1 parent
03900e726a
commit
8992060cb7
94 files changed
+53456
-29275
No files matched your search
@@ -27,6 +27,7 @@ import { TestimonialsModule } from './testimonials/testimonials.module';
|
||||
import { IngredientsModule } from './ingredients/ingredients.module';
|
||||
import { PrescriptionsModule } from './prescriptions/prescriptions.module';
|
||||
import { B2BModule } from './b2b/b2b.module';
|
||||
import { PaymentModule } from './payment/payment.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -40,6 +41,7 @@ import { B2BModule } from './b2b/b2b.module';
|
||||
PetsModule,
|
||||
OrdersModule,
|
||||
SettingsModule,
|
||||
PaymentModule,
|
||||
ThrottlerModule.forRoot([
|
||||
{
|
||||
ttl: 60000,
|
||||
|
||||
@@ -227,6 +227,8 @@ export class OrdersService {
|
||||
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
|
||||
trackingNumber,
|
||||
status: 'processing',
|
||||
paymentMethod: 'wallet',
|
||||
shippingAddress: createOrderDto.shippingAddress,
|
||||
orderItems: {
|
||||
create: orderItemsData,
|
||||
},
|
||||
@@ -240,6 +242,9 @@ export class OrdersService {
|
||||
});
|
||||
}
|
||||
|
||||
const isOnline = createOrderDto.paymentMethod === 'online';
|
||||
const initialStatus = isOnline ? 'pending_payment' : 'processing';
|
||||
|
||||
const createdOrder = await this.prisma.order.create({
|
||||
data: {
|
||||
userId,
|
||||
@@ -249,7 +254,9 @@ export class OrdersService {
|
||||
isRefill: Boolean(createOrderDto.isRefill),
|
||||
refillIntervalDays: createOrderDto.refillIntervalDays || 60,
|
||||
trackingNumber,
|
||||
status: 'processing',
|
||||
status: initialStatus,
|
||||
paymentMethod: createOrderDto.paymentMethod || 'card',
|
||||
shippingAddress: createOrderDto.shippingAddress,
|
||||
orderItems: {
|
||||
create: orderItemsData,
|
||||
},
|
||||
@@ -261,8 +268,8 @@ export class OrdersService {
|
||||
},
|
||||
});
|
||||
|
||||
// Send Order Confirmation SMS
|
||||
if (userId) {
|
||||
// Send Order Confirmation SMS (for card-to-card or non-online orders, online orders get SMS on verify)
|
||||
if (userId && !isOnline) {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class InitiatePaymentDto {
|
||||
@ApiProperty({ description: 'شناسه سفارش در دیتابیس' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
orderId: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس بازگشت اختیاری جهت سفارشیسازی' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
customCallbackUrl?: string;
|
||||
}
|
||||
|
||||
export class InitiateWalletTopupDto {
|
||||
@ApiProperty({ description: 'مبلغ افزایش اعتبار (به تومان)' })
|
||||
@IsNotEmpty()
|
||||
amount: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس بازگشت اختیاری' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
customCallbackUrl?: string;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class ZibalCallbackQueryDto {
|
||||
@ApiPropertyOptional({ description: 'وضعیت موفقیت اولیه زیبال (1 یا 0)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
success?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه پیگیری تراکنش زیبال' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
trackId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه سفارش ارسال شده در زمان ایجاد' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
orderId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'کد وضعیت پرداخت زیبال' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شماره کارت ماسک شده (در متد لِیزی)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cardNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شماره کارت هش شده (در متد لِیزی)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
hashedCardNumber?: string;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Query,
|
||||
Param,
|
||||
UseGuards,
|
||||
Req,
|
||||
Res,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import {
|
||||
InitiatePaymentDto,
|
||||
InitiateWalletTopupDto,
|
||||
} from './dto/initiate-payment.dto';
|
||||
import { ZibalCallbackQueryDto } from './dto/verify-payment.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiBearerAuth,
|
||||
ApiResponse,
|
||||
ApiOkResponse,
|
||||
ApiBadRequestResponse,
|
||||
} from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Payment - درگاه پرداخت اینترنتی زیبال (Zibal IPG)')
|
||||
@Controller('payment')
|
||||
export class PaymentController {
|
||||
constructor(
|
||||
private readonly paymentService: PaymentService,
|
||||
private readonly zibalService: ZibalService,
|
||||
) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('zibal/initiate')
|
||||
@ApiOperation({ summary: 'شروع فرایند پرداخت آنلاین سفارش با درگاه زیبال' })
|
||||
@ApiOkResponse({
|
||||
description: 'لینک هدایت به درگاه پرداخت زیبال با موفقیت تولید شد',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
trackId: '15966442233311',
|
||||
paymentUrl: 'https://gateway.zibal.ir/start/15966442233311',
|
||||
orderId: 'e1d2c3b4-1234-5678-abcd-ef1234567890',
|
||||
amount: 350000,
|
||||
},
|
||||
},
|
||||
})
|
||||
@ApiBadRequestResponse({ description: 'خطا در ایجاد تراکنش یا نامعتبر بودن سفارش' })
|
||||
async initiateOrderPayment(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Body() body: InitiatePaymentDto,
|
||||
) {
|
||||
return this.paymentService.initiateOrderPayment(
|
||||
req.user.id,
|
||||
body.orderId,
|
||||
body.customCallbackUrl,
|
||||
);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('zibal/wallet/initiate')
|
||||
@ApiOperation({ summary: 'شارژ آنلاین کیف پول از طریق درگاه زیبال' })
|
||||
@ApiOkResponse({
|
||||
description: 'لینک هدایت به درگاه پرداخت برای شارژ کیف پول',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
trackId: '15966442233311',
|
||||
paymentUrl: 'https://gateway.zibal.ir/start/15966442233311',
|
||||
amount: 500000,
|
||||
},
|
||||
},
|
||||
})
|
||||
async initiateWalletTopup(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Body() body: InitiateWalletTopupDto,
|
||||
) {
|
||||
return this.paymentService.initiateWalletTopup(
|
||||
req.user.id,
|
||||
Number(body.amount),
|
||||
body.customCallbackUrl,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('zibal/callback')
|
||||
@ApiOperation({ summary: 'دریافت کالبک بازگشت از درگاه زیبال و تایید تراکنش' })
|
||||
async handleZibalCallback(
|
||||
@Query() query: ZibalCallbackQueryDto,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const trackId = query.trackId || '';
|
||||
const success = query.success;
|
||||
const status = query.status;
|
||||
const orderId = query.orderId;
|
||||
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
|
||||
if (!trackId) {
|
||||
return res.redirect(
|
||||
`${frontendUrl}/payment/verify?success=0&message=${encodeURIComponent('شناسه پیگیری نامعتبر است')}`,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.paymentService.verifyAndProcess(
|
||||
trackId,
|
||||
success,
|
||||
status,
|
||||
orderId,
|
||||
);
|
||||
|
||||
const params = new URLSearchParams({
|
||||
trackId: String(result.trackId || trackId),
|
||||
success: result.success ? '1' : '0',
|
||||
status: result.status || '',
|
||||
orderId: result.orderId || orderId || '',
|
||||
refNumber: result.refNumber || '',
|
||||
cardNumber: result.cardNumber || '',
|
||||
message: result.message || '',
|
||||
amount: String(result.amount || ''),
|
||||
type: result.type || '',
|
||||
});
|
||||
|
||||
return res.redirect(`${frontendUrl}/payment/verify?${params.toString()}`);
|
||||
} catch (err: any) {
|
||||
return res.redirect(
|
||||
`${frontendUrl}/payment/verify?success=0&trackId=${trackId}&message=${encodeURIComponent(err.message || 'خطا در پردازش پرداخت')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('zibal/callback')
|
||||
@ApiOperation({ summary: 'دریافت وبهوک / کالبک لِیزی زیبال' })
|
||||
async handleZibalLazyCallback(
|
||||
@Body() body: ZibalCallbackQueryDto,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const trackId = body.trackId || '';
|
||||
const success = body.success;
|
||||
const status = body.status;
|
||||
const orderId = body.orderId;
|
||||
|
||||
if (!trackId) {
|
||||
return res.status(HttpStatus.BAD_REQUEST).json({ success: false, message: 'trackId is required' });
|
||||
}
|
||||
|
||||
const result = await this.paymentService.verifyAndProcess(
|
||||
trackId,
|
||||
success,
|
||||
status,
|
||||
orderId,
|
||||
);
|
||||
|
||||
return res.status(HttpStatus.OK).json(result);
|
||||
}
|
||||
|
||||
@Get('verify-status/:trackId')
|
||||
@ApiOperation({ summary: 'استعلام و دریافت وضعیت تراکنش پرداخت با TrackID' })
|
||||
async getTransactionStatus(@Param('trackId') trackId: string) {
|
||||
return this.paymentService.getTransaction(trackId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PaymentController } from './payment.controller';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { SmsModule } from '../common/sms.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, SmsModule],
|
||||
controllers: [PaymentController],
|
||||
providers: [PaymentService, ZibalService],
|
||||
exports: [PaymentService, ZibalService],
|
||||
})
|
||||
export class PaymentModule {}
|
||||
@@ -0,0 +1,441 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PaymentService {
|
||||
private readonly logger = new Logger(PaymentService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly zibalService: ZibalService,
|
||||
private readonly smsService: SmsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 1. Initiate Online Payment for an Order via Zibal
|
||||
*/
|
||||
async initiateOrderPayment(
|
||||
userId: string,
|
||||
orderId: string,
|
||||
customCallbackUrl?: string,
|
||||
) {
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, userId },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!order) {
|
||||
throw new NotFoundException('سفارش مورد نظر یافت نشد');
|
||||
}
|
||||
|
||||
if (order.status !== 'processing' && order.status !== 'pending_payment') {
|
||||
if (['shipped', 'delivered'].includes(order.status)) {
|
||||
throw new BadRequestException('این سفارش قبلاً تکمیل و ارسال شده است');
|
||||
}
|
||||
}
|
||||
|
||||
const amountTomans = Number(order.totalAmount);
|
||||
const amountRials = Math.round(amountTomans * 10);
|
||||
|
||||
if (amountRials < 1000) {
|
||||
throw new BadRequestException('مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است');
|
||||
}
|
||||
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
// Default callback points to frontend verify page (or backend proxy)
|
||||
const callbackUrl =
|
||||
customCallbackUrl || `${frontendUrl}/payment/verify?orderId=${order.id}`;
|
||||
|
||||
// Create a pending PaymentTransaction in database
|
||||
const transaction = await this.prisma.paymentTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
orderId: order.id,
|
||||
amount: new Prisma.Decimal(amountTomans),
|
||||
amountRials: BigInt(amountRials),
|
||||
gateway: 'zibal',
|
||||
status: 'PENDING',
|
||||
type: 'ORDER',
|
||||
description: `پرداخت آنلاین سفارش ${order.trackingNumber || order.id}`,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const zibalRes = await this.zibalService.requestPayment({
|
||||
amountRials,
|
||||
callbackUrl,
|
||||
orderId: order.id,
|
||||
mobile: order.user?.mobile || undefined,
|
||||
description: `پرداخت سفارش ${order.trackingNumber || ''} - پتشاپ کانینا`,
|
||||
});
|
||||
|
||||
if (zibalRes.result !== 100) {
|
||||
const errorMsg = this.zibalService.getResultMessage(zibalRes.result);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: zibalRes.result,
|
||||
message: errorMsg,
|
||||
},
|
||||
});
|
||||
throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`);
|
||||
}
|
||||
|
||||
const trackId = String(zibalRes.trackId);
|
||||
|
||||
// Update transaction with trackId
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
trackId,
|
||||
resultCode: zibalRes.result,
|
||||
message: zibalRes.message,
|
||||
},
|
||||
});
|
||||
|
||||
const paymentUrl = this.zibalService.getStartUrl(trackId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
trackId,
|
||||
paymentUrl,
|
||||
orderId: order.id,
|
||||
amount: amountTomans,
|
||||
};
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Error requesting payment from Zibal: ${err.message}`, err.stack);
|
||||
throw new BadRequestException(err.message || 'خطا در اتصال به درگاه پرداخت');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Initiate Online Wallet Top-Up via Zibal
|
||||
*/
|
||||
async initiateWalletTopup(
|
||||
userId: string,
|
||||
amountTomans: number,
|
||||
customCallbackUrl?: string,
|
||||
) {
|
||||
if (amountTomans < 1000) {
|
||||
throw new BadRequestException('حداقل مبلغ افزایش موجودی ۱,۰۰۰ تومان است');
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('کاربر یافت نشد');
|
||||
}
|
||||
|
||||
const amountRials = Math.round(amountTomans * 10);
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
const callbackUrl =
|
||||
customCallbackUrl || `${frontendUrl}/payment/verify?type=wallet`;
|
||||
|
||||
const transaction = await this.prisma.paymentTransaction.create({
|
||||
data: {
|
||||
userId,
|
||||
amount: new Prisma.Decimal(amountTomans),
|
||||
amountRials: BigInt(amountRials),
|
||||
gateway: 'zibal',
|
||||
status: 'PENDING',
|
||||
type: 'WALLET_TOPUP',
|
||||
description: `افزایش موجودی کیف پول کاربر ${user.mobile}`,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const zibalRes = await this.zibalService.requestPayment({
|
||||
amountRials,
|
||||
callbackUrl,
|
||||
mobile: user.mobile || undefined,
|
||||
description: `شارژ کیف پول - پت شاپ کانینا`,
|
||||
});
|
||||
|
||||
if (zibalRes.result !== 100) {
|
||||
const errorMsg = this.zibalService.getResultMessage(zibalRes.result);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: zibalRes.result,
|
||||
message: errorMsg,
|
||||
},
|
||||
});
|
||||
throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`);
|
||||
}
|
||||
|
||||
const trackId = String(zibalRes.trackId);
|
||||
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
trackId,
|
||||
resultCode: zibalRes.result,
|
||||
message: zibalRes.message,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
trackId,
|
||||
paymentUrl: this.zibalService.getStartUrl(trackId),
|
||||
amount: amountTomans,
|
||||
};
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Error requesting wallet topup from Zibal: ${err.message}`);
|
||||
throw new BadRequestException(err.message || 'خطا در ارتباط با درگاه بانکی');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. Verify & Process Callback from Zibal
|
||||
*/
|
||||
async verifyAndProcess(
|
||||
trackId: string,
|
||||
successParam?: string,
|
||||
statusParam?: string,
|
||||
orderIdParam?: string,
|
||||
) {
|
||||
this.logger.log(
|
||||
`Processing callback for trackId=${trackId}, success=${successParam}, status=${statusParam}, orderId=${orderIdParam}`,
|
||||
);
|
||||
|
||||
let transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { trackId },
|
||||
include: {
|
||||
order: {
|
||||
include: { user: true, orderItems: { include: { product: true } } },
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
// If transaction not found by trackId, check if orderId exists
|
||||
if (orderIdParam) {
|
||||
transaction = await this.prisma.paymentTransaction.findFirst({
|
||||
where: { orderId: orderIdParam },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
order: {
|
||||
include: { user: true, orderItems: { include: { product: true } } },
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش پرداخت در سیستم یافت نشد');
|
||||
}
|
||||
|
||||
// If transaction is already verified, return successful details immediately
|
||||
if (transaction.status === 'VERIFIED') {
|
||||
return {
|
||||
success: true,
|
||||
alreadyVerified: true,
|
||||
status: 'VERIFIED',
|
||||
trackId: transaction.trackId,
|
||||
refNumber: transaction.refNumber,
|
||||
cardNumber: transaction.cardNumber,
|
||||
amount: Number(transaction.amount),
|
||||
orderId: transaction.orderId,
|
||||
message: 'تراکنش قبلاً با موفقیت تایید و پردازش شده است',
|
||||
};
|
||||
}
|
||||
|
||||
// If user cancelled or Zibal signaled failure at the gate
|
||||
if (successParam === '0' || statusParam === '3') {
|
||||
const statusMessage = this.zibalService.getStatusMessage(statusParam || 3);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
message: statusMessage,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
trackId,
|
||||
message: statusMessage,
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
|
||||
// Call Zibal verify endpoint
|
||||
try {
|
||||
const verifyRes = await this.zibalService.verifyPayment(trackId);
|
||||
const isSuccess = verifyRes.result === 100 || verifyRes.result === 201;
|
||||
|
||||
if (!isSuccess) {
|
||||
const errorMsg = this.zibalService.getResultMessage(verifyRes.result);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
resultCode: verifyRes.result,
|
||||
message: errorMsg,
|
||||
cardNumber: verifyRes.cardNumber,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
trackId,
|
||||
resultCode: verifyRes.result,
|
||||
message: errorMsg,
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
|
||||
// SUCCESSFUL PAYMENT!
|
||||
const refNumber = verifyRes.refNumber ? String(verifyRes.refNumber) : undefined;
|
||||
const cardNumber = verifyRes.cardNumber || undefined;
|
||||
const paidDate = verifyRes.paidAt ? new Date(verifyRes.paidAt) : new Date();
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
// 1. Mark transaction as VERIFIED
|
||||
await tx.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'VERIFIED',
|
||||
resultCode: verifyRes.result,
|
||||
refNumber,
|
||||
cardNumber,
|
||||
paidAt: paidDate,
|
||||
message: 'پرداخت با موفقیت انجام و تایید شد',
|
||||
},
|
||||
});
|
||||
|
||||
// 2. If it's an Order payment
|
||||
if (transaction.type === 'ORDER' && transaction.orderId) {
|
||||
await tx.order.update({
|
||||
where: { id: transaction.orderId },
|
||||
data: {
|
||||
status: 'processing',
|
||||
paymentMethod: 'online',
|
||||
},
|
||||
});
|
||||
|
||||
// If charity donation was made, update user's total charity
|
||||
if (transaction.order && Number(transaction.order.charityDonation) > 0) {
|
||||
await tx.user.update({
|
||||
where: { id: transaction.userId },
|
||||
data: {
|
||||
charityDonationTotal: {
|
||||
increment: Number(transaction.order.charityDonation),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. If it's a Wallet Top-up
|
||||
if (transaction.type === 'WALLET_TOPUP') {
|
||||
await tx.user.update({
|
||||
where: { id: transaction.userId },
|
||||
data: {
|
||||
walletBalance: {
|
||||
increment: Number(transaction.amount),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.walletTransaction.create({
|
||||
data: {
|
||||
userId: transaction.userId,
|
||||
amount: transaction.amount,
|
||||
type: 'deposit',
|
||||
status: 'completed',
|
||||
transactionReference: refNumber || `ZBL-${trackId}`,
|
||||
description: `افزایش اعتبار آنلاین از طریق درگاه زیبال (شناسه: ${trackId})`,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Send SMS notification if order payment
|
||||
if (transaction.type === 'ORDER' && transaction.order?.user?.mobile) {
|
||||
const mobile = transaction.order.user.mobile;
|
||||
const trackingNum = transaction.order.trackingNumber || transaction.order.id;
|
||||
const formattedAmount = Number(transaction.amount).toLocaleString('fa-IR');
|
||||
|
||||
this.smsService
|
||||
.sendOrderConfirmation(mobile, trackingNum, formattedAmount)
|
||||
.catch((err) => {
|
||||
this.logger.warn(`Could not send SMS confirmation: ${err}`);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: 'VERIFIED',
|
||||
trackId,
|
||||
refNumber,
|
||||
cardNumber,
|
||||
amount: Number(transaction.amount),
|
||||
orderId: transaction.orderId,
|
||||
type: transaction.type,
|
||||
message: 'پرداخت با موفقیت انجام شد',
|
||||
};
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Error during verify: ${err.message}`, err.stack);
|
||||
return {
|
||||
success: false,
|
||||
status: 'ERROR',
|
||||
trackId,
|
||||
message: err.message || 'خطا در فرایند تایید تراکنش',
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Get Payment Transaction Details
|
||||
*/
|
||||
async getTransaction(trackId: string) {
|
||||
const transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { trackId },
|
||||
include: {
|
||||
order: {
|
||||
include: {
|
||||
orderItems: {
|
||||
include: { product: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
}
|
||||
|
||||
return {
|
||||
id: transaction.id,
|
||||
trackId: transaction.trackId,
|
||||
refNumber: transaction.refNumber,
|
||||
amount: Number(transaction.amount),
|
||||
status: transaction.status,
|
||||
message: transaction.message,
|
||||
gateway: transaction.gateway,
|
||||
type: transaction.type,
|
||||
cardNumber: transaction.cardNumber,
|
||||
paidAt: transaction.paidAt,
|
||||
createdAt: transaction.createdAt,
|
||||
order: transaction.order,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export interface ZibalRequestResponse {
|
||||
trackId: number;
|
||||
result: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ZibalVerifyResponse {
|
||||
paidAt?: string;
|
||||
amount?: number;
|
||||
result: number;
|
||||
message: string;
|
||||
status?: number;
|
||||
refNumber?: string;
|
||||
description?: string;
|
||||
cardNumber?: string;
|
||||
orderId?: string;
|
||||
}
|
||||
|
||||
export interface ZibalInquiryResponse {
|
||||
paidAt?: string;
|
||||
amount?: number;
|
||||
result: number;
|
||||
message: string;
|
||||
status?: number;
|
||||
refNumber?: string;
|
||||
description?: string;
|
||||
cardNumber?: string;
|
||||
orderId?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ZibalService {
|
||||
private readonly logger = new Logger(ZibalService.name);
|
||||
private readonly baseUrl = 'https://gateway.zibal.ir';
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/**
|
||||
* Retrieves active merchant code from settings (DB) or fallback to env / 'zibal' sandbox.
|
||||
*/
|
||||
async getMerchant(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_MERCHANT' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_MERCHANT from db: ${e}`);
|
||||
}
|
||||
|
||||
return process.env.ZIBAL_MERCHANT || 'zibal';
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves base frontend/app url for callbacks
|
||||
*/
|
||||
async getFrontendUrl(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'FRONTEND_URL' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim().replace(/\/+$/, '');
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read FRONTEND_URL from db: ${e}`);
|
||||
}
|
||||
|
||||
const envUrl = process.env.FRONTEND_URL || process.env.APP_URL;
|
||||
return envUrl ? envUrl.replace(/\/+$/, '') : 'https://canina.ir';
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. Request Payment (درخواست پرداخت)
|
||||
* Amount must be in Rials.
|
||||
*/
|
||||
async requestPayment(params: {
|
||||
amountRials: number;
|
||||
callbackUrl: string;
|
||||
description?: string;
|
||||
orderId?: string;
|
||||
mobile?: string;
|
||||
nationalCode?: string;
|
||||
allowedCards?: string[];
|
||||
}): Promise<ZibalRequestResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
|
||||
const payload = {
|
||||
merchant,
|
||||
amount: params.amountRials,
|
||||
callbackUrl: params.callbackUrl,
|
||||
description: params.description || 'پرداخت سفارش در پت شاپ کانینا',
|
||||
orderId: params.orderId,
|
||||
mobile: params.mobile,
|
||||
nationalCode: params.nationalCode,
|
||||
allowedCards: params.allowedCards,
|
||||
};
|
||||
|
||||
this.logger.log(
|
||||
`Sending payment request to Zibal for orderId=${params.orderId}, amount=${params.amountRials} Rials, merchant=${merchant}`,
|
||||
);
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/v1/request`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
this.logger.error(`Zibal request HTTP error ${response.status}: ${errorText}`);
|
||||
throw new Error(`خطا در اتصال به درگاه زیبال: کد وضعیت ${response.status}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalRequestResponse;
|
||||
this.logger.log(`Zibal request response: ${JSON.stringify(data)}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Generate Start Payment URL (آدرس هدایت به درگاه)
|
||||
*/
|
||||
getStartUrl(trackId: string | number): string {
|
||||
return `${this.baseUrl}/start/${trackId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. Verify Payment (تایید تراکنش)
|
||||
*/
|
||||
async verifyPayment(trackId: string | number): Promise<ZibalVerifyResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
|
||||
const payload = {
|
||||
merchant,
|
||||
trackId: String(trackId),
|
||||
};
|
||||
|
||||
this.logger.log(`Verifying payment on Zibal for trackId=${trackId}, merchant=${merchant}`);
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/v1/verify`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
this.logger.error(`Zibal verify HTTP error ${response.status}: ${errorText}`);
|
||||
throw new Error(`خطا در تایید تراکنش درگاه زیبال: کد وضعیت ${response.status}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalVerifyResponse;
|
||||
this.logger.log(`Zibal verify response: ${JSON.stringify(data)}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Inquiry Payment (استعلام وضعیت تراکنش)
|
||||
*/
|
||||
async inquiryPayment(trackId: string | number): Promise<ZibalInquiryResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
|
||||
const payload = {
|
||||
merchant,
|
||||
trackId: String(trackId),
|
||||
};
|
||||
|
||||
this.logger.log(`Inquiring payment on Zibal for trackId=${trackId}`);
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/v1/inquiry`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
this.logger.error(`Zibal inquiry HTTP error ${response.status}: ${errorText}`);
|
||||
throw new Error(`خطا در استعلام تراکنش زیبال: کد وضعیت ${response.status}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalInquiryResponse;
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates status codes from Zibal to Persian human-friendly messages
|
||||
*/
|
||||
getStatusMessage(status?: number | string): string {
|
||||
const statusNum = Number(status);
|
||||
const messages: Record<number, string> = {
|
||||
[-1]: 'در انتظار پرداخت',
|
||||
[-2]: 'خطای داخلی درگاه زیبال',
|
||||
1: 'پرداخت شده و تایید شده',
|
||||
2: 'پرداخت شده - در انتظار تایید',
|
||||
3: 'تراکنش توسط کاربر لغو شد',
|
||||
4: 'شماره کارت نامعتبر است',
|
||||
5: 'موجودی حساب کافی نیست',
|
||||
6: 'رمز وارد شده اشتباه است',
|
||||
7: 'تعداد درخواستها بیش از حد مجاز است',
|
||||
8: 'تعداد پرداخت اینترنتی روزانه بیش از حد مجاز است',
|
||||
9: 'مبلغ پرداخت اینترنتی روزانه بیش از حد مجاز است',
|
||||
10: 'صادرکننده کارت نامعتبر است',
|
||||
11: 'خطای سوئیچ بانکی',
|
||||
12: 'کارت قابل دسترسی نیست',
|
||||
15: 'تراکنش استرداد شده است',
|
||||
16: 'تراکنش در حال استرداد است',
|
||||
18: 'تراکنش ریورس شده است',
|
||||
21: 'پذیرنده نامعتبر است',
|
||||
};
|
||||
|
||||
return messages[statusNum] || 'وضعیت نامشخص';
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates verify result codes to Persian messages
|
||||
*/
|
||||
getResultMessage(result?: number): string {
|
||||
const messages: Record<number, string> = {
|
||||
100: 'با موفقیت تایید شد.',
|
||||
102: 'مرچنت یافت نشد.',
|
||||
103: 'مرچنت غیرفعال است یا قرارداد درگاه امضا نشده است.',
|
||||
104: 'مرچنت نامعتبر است.',
|
||||
105: 'مبلغ باید بزرگتر از ۱,۰۰۰ ریال باشد.',
|
||||
106: 'آدرس بازگشت (callbackUrl) نامعتبر است.',
|
||||
113: 'مبلغ تراکنش از سقف مجاز بیشتر است.',
|
||||
114: 'کد ملی ارسالی نامعتبر است.',
|
||||
115: 'آیپی سرور شما در پنل کاربری زیبال ثبت نشده است.',
|
||||
201: 'تراکنش قبلا تایید شده است.',
|
||||
202: 'سفارش پرداخت نشده یا ناموفق بوده است.',
|
||||
203: 'شناسه پیگیری (trackId) نامعتبر است.',
|
||||
};
|
||||
|
||||
return messages[result ?? 0] || 'نتیجه نامشخص تراکنش';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user