feat(payment): implement complete Zibal IPG, EBank, Wallets, Refunds and Trust Seals
Deploy Canina / deploy (push) Successful in 1m51s
Deploy Canina / deploy (push) Successful in 1m51s
This commit is contained in:
1 parent
7203915e15
commit
a2b8afccc3
21 files changed
+143035
-8553
No files matched your search
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
IsNotEmpty,
|
||||
IsString,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateEBankCheckoutDto {
|
||||
@ApiProperty({ description: 'مبلغ انتقال وجه به ریال' })
|
||||
@IsNumber()
|
||||
@Min(10000)
|
||||
amount: number;
|
||||
|
||||
@ApiProperty({ description: 'شماره شبا حساب مقصد (IR...)' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
iban: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه حساب مبدا پذیرنده' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
accountId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'کد دلیل انتقال وجه' })
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
reasonCode?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'میزان تاخیر به دقیقه' })
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
delay?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه یکتای اختصاصی' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
uniqueCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'توضیحات انتقال وجه' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه واریز' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
paymentNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس کالبک وبهوک' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
callbackUrl?: string;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Body,
|
||||
Query,
|
||||
Param,
|
||||
@@ -16,6 +17,8 @@ import {
|
||||
import type { Request, Response } from 'express';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { ZibalEBankService } from './zibal-ebank.service';
|
||||
import { CreateEBankCheckoutDto } from './dto/ebank-checkout.dto';
|
||||
import {
|
||||
InitiatePaymentDto,
|
||||
InitiateWalletTopupDto,
|
||||
@@ -39,6 +42,7 @@ export class PaymentController {
|
||||
constructor(
|
||||
private readonly paymentService: PaymentService,
|
||||
private readonly zibalService: ZibalService,
|
||||
private readonly zibalEBankService: ZibalEBankService,
|
||||
) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@@ -200,6 +204,258 @@ export class PaymentController {
|
||||
return this.paymentService.getTransaction(trackId);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// ADMIN: ZIBAL WALLETS, REFUNDS & GATEWAY REPORTS
|
||||
// ==========================================
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/wallets')
|
||||
@ApiOperation({ summary: 'دریافت لیست کیفپولهای زیبال و موجودی آنها' })
|
||||
async getAdminWallets() {
|
||||
return this.zibalService.getWalletList();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/refund')
|
||||
@ApiOperation({ summary: 'درخواست استرداد وجه تراکنش (Refund یا Reverse)' })
|
||||
async createRefund(
|
||||
@Body()
|
||||
body: {
|
||||
trackId: string | number;
|
||||
amount?: number;
|
||||
tryReverse?: boolean;
|
||||
cardNumber?: string;
|
||||
description?: string;
|
||||
},
|
||||
) {
|
||||
return this.zibalService.requestRefund(body);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/refund/inquiry')
|
||||
@ApiOperation({ summary: 'استعلام وضعیت استرداد وجه' })
|
||||
async inquireRefund(
|
||||
@Body() body: { refundId?: string | number; transactionTrackId?: string | number },
|
||||
) {
|
||||
return this.zibalService.inquireRefund(body);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/refund/list')
|
||||
@ApiOperation({ summary: 'گزارش لیست استردادهای انجام شده' })
|
||||
async getRefundList(
|
||||
@Body()
|
||||
body: {
|
||||
status?: number[];
|
||||
type?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
},
|
||||
) {
|
||||
return this.zibalService.getRefundList(body);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/gateway-report')
|
||||
@ApiOperation({ summary: 'گزارش مستقیم تراکنشهای درگاه زیبال از سرور زیبال' })
|
||||
async getGatewayReport(
|
||||
@Body()
|
||||
body: {
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
trackId?: number;
|
||||
status?: number;
|
||||
orderId?: string;
|
||||
mobile?: string;
|
||||
amount?: number;
|
||||
cardNumber?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
},
|
||||
) {
|
||||
return this.zibalService.getGatewayTransactionsReport(body);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// ADMIN: SUB-MERCHANTS (ذینفعهای تسهیم)
|
||||
// ==========================================
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/sub-merchants')
|
||||
@ApiOperation({ summary: 'لیست ذینفعهای ثبتشده در زیبال' })
|
||||
async getSubMerchants(
|
||||
@Query('page') page = '1',
|
||||
@Query('size') size = '20',
|
||||
) {
|
||||
return this.zibalService.getSubMerchantList(Number(page), Number(size));
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/sub-merchants')
|
||||
@ApiOperation({ summary: 'ثبت ذینفع جدید برای تسهیم' })
|
||||
async createSubMerchant(
|
||||
@Body() body: { bankAccount: string; name: string; callbackUrl?: string },
|
||||
) {
|
||||
return this.zibalService.createSubMerchant(body);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Put('admin/sub-merchants')
|
||||
@ApiOperation({ summary: 'ویرایش ذینفع غیرفعال' })
|
||||
async editSubMerchant(
|
||||
@Body() body: { id: string; bankAccount: string; name: string },
|
||||
) {
|
||||
return this.zibalService.editSubMerchant(body);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// ADMIN: CORPORATE BANKING (EBANK API)
|
||||
// ==========================================
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/accounts')
|
||||
@ApiOperation({ summary: 'لیست حسابهای متصل به بانکداری شرکتی زیبال' })
|
||||
async getEBankAccounts(@Query('active') active?: string) {
|
||||
const activeAccounts = active !== undefined ? active === 'true' : undefined;
|
||||
return this.zibalEBankService.getAccountList(activeAccounts);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/balance')
|
||||
@ApiOperation({ summary: 'دریافت موجودی حساب بانکداری شرکتی' })
|
||||
async getEBankBalance(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('update') update?: string,
|
||||
) {
|
||||
return this.zibalEBankService.getAccountBalance(accountId, update === 'true');
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/statements')
|
||||
@ApiOperation({ summary: 'دریافت صورتحساب بانکی حساب متصل' })
|
||||
async getEBankStatements(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('fromDate') fromDate?: string,
|
||||
@Query('toDate') toDate?: string,
|
||||
@Query('update') update?: string,
|
||||
@Query('size') size = '20',
|
||||
@Query('page') page = '1',
|
||||
) {
|
||||
return this.zibalEBankService.getStatementList({
|
||||
accountId,
|
||||
fromDate,
|
||||
toDate,
|
||||
update: update === 'true',
|
||||
size: Number(size),
|
||||
page: Number(page),
|
||||
});
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/ebank/checkout')
|
||||
@ApiOperation({ summary: 'ثبت انتقال وجه پایا / ساتنا / پل از حساب بانکی' })
|
||||
async createEBankCheckout(@Body() body: CreateEBankCheckoutDto) {
|
||||
return this.zibalEBankService.createCheckout(body);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/checkouts')
|
||||
@ApiOperation({ summary: 'لیست انتقال وجههای بانکداری شرکتی' })
|
||||
async getEBankCheckoutList(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('fromDate') fromDate?: string,
|
||||
@Query('toDate') toDate?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('size') size = '20',
|
||||
@Query('page') page = '1',
|
||||
) {
|
||||
return this.zibalEBankService.getCheckoutList({
|
||||
accountId,
|
||||
fromDate,
|
||||
toDate,
|
||||
status: status ? Number(status) : undefined,
|
||||
size: Number(size),
|
||||
page: Number(page),
|
||||
});
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/ebank/checkout/cancel')
|
||||
@ApiOperation({ summary: 'لغو انتقال وجههای در صف' })
|
||||
async cancelEBankCheckout(
|
||||
@Body() body: { checkoutIds: string[]; accountId?: string },
|
||||
) {
|
||||
return this.zibalEBankService.cancelCheckout(body.checkoutIds, body.accountId);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/identified-payments')
|
||||
@ApiOperation({ summary: 'لیست واریزیهای شناسه دار' })
|
||||
async getEBankIdentifiedPayments(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('fromDate') fromDate?: string,
|
||||
@Query('toDate') toDate?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('size') size = '20',
|
||||
@Query('page') page = '1',
|
||||
) {
|
||||
return this.zibalEBankService.getIdentifiedPaymentList({
|
||||
accountId,
|
||||
fromDate,
|
||||
toDate,
|
||||
status: status ? Number(status) : undefined,
|
||||
size: Number(size),
|
||||
page: Number(page),
|
||||
});
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/ebank/identified-payments/status')
|
||||
@ApiOperation({ summary: 'تایید یا رد واریزی شناسه دار' })
|
||||
async changeIdentifiedPaymentStatus(
|
||||
@Body() body: { transactionId: string; status: 2 | 3; accountId?: string },
|
||||
) {
|
||||
return this.zibalEBankService.changeIdentifiedPaymentStatus(
|
||||
body.transactionId,
|
||||
body.status,
|
||||
body.accountId,
|
||||
);
|
||||
}
|
||||
|
||||
// --- ADMIN ENDPOINTS FOR TRANSACTION LOGS, DIAGNOSTICS & HEALTH CHECK ---
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
|
||||
@@ -2,13 +2,14 @@ import { Module } from '@nestjs/common';
|
||||
import { PaymentController } from './payment.controller';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { ZibalEBankService } from './zibal-ebank.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],
|
||||
providers: [PaymentService, ZibalService, ZibalEBankService],
|
||||
exports: [PaymentService, ZibalService, ZibalEBankService],
|
||||
})
|
||||
export class PaymentModule {}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export interface EBankCheckoutOptions {
|
||||
amount: number; // Rial
|
||||
iban: string; // IR...
|
||||
accountId?: string;
|
||||
reasonCode?: number; // 1-19 (e.g. 18 for goods, 4 for debt settlement)
|
||||
delay?: number; // -1: instant, 0: closest cycle, 60: 1 hour, etc.
|
||||
uniqueCode?: string;
|
||||
description?: string;
|
||||
paymentNumber?: string;
|
||||
callbackUrl?: string;
|
||||
}
|
||||
|
||||
export interface EBankCheckoutListFilter {
|
||||
accountId?: string;
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
status?: number;
|
||||
size?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export interface EBankStatementFilter {
|
||||
accountId?: string;
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
update?: boolean;
|
||||
size?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
export interface EBankIdentifiedPaymentFilter {
|
||||
accountId?: string;
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
status?: number; // 0: pending, 2: verified, 3: rejected
|
||||
size?: number;
|
||||
page?: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ZibalEBankService {
|
||||
private readonly logger = new Logger(ZibalEBankService.name);
|
||||
private readonly baseUrl = 'https://api.zibal.ir';
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/**
|
||||
* Retrieves Bearer Access Token for Zibal EBank API
|
||||
*/
|
||||
async getAccessToken(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_EBANK_TOKEN' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_EBANK_TOKEN from db: ${e}`);
|
||||
}
|
||||
|
||||
return process.env.ZIBAL_EBANK_TOKEN || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves default Account ID for Zibal EBank API
|
||||
*/
|
||||
async getDefaultAccountId(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_EBANK_ACCOUNT_ID' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_EBANK_ACCOUNT_ID from db: ${e}`);
|
||||
}
|
||||
|
||||
return process.env.ZIBAL_EBANK_ACCOUNT_ID || '';
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
body?: Record<string, any>;
|
||||
params?: Record<string, any>;
|
||||
} = {},
|
||||
): Promise<T> {
|
||||
const token = await this.getAccessToken();
|
||||
if (!token) {
|
||||
throw new Error('توکن دسترسی بانکداری شرکتی زیبال (ZIBAL_EBANK_TOKEN) تنظیم نشده است.');
|
||||
}
|
||||
|
||||
let url = `${this.baseUrl}${endpoint}`;
|
||||
if (options.params) {
|
||||
const queryParams = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(options.params)) {
|
||||
if (v !== undefined && v !== null && v !== '') {
|
||||
queryParams.append(k, String(v));
|
||||
}
|
||||
}
|
||||
const qs = queryParams.toString();
|
||||
if (qs) {
|
||||
url += (url.includes('?') ? '&' : '?') + qs;
|
||||
}
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 15000);
|
||||
|
||||
try {
|
||||
this.logger.log(`[Zibal EBank API] ${options.method || 'GET'} ${url}`);
|
||||
const response = await fetch(url, {
|
||||
method: options.method || 'GET',
|
||||
headers,
|
||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
return data as T;
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.error(`[Zibal EBank API] Error requesting ${endpoint}: ${msg}`);
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 1. انتقال وجه (Checkouts & Payouts)
|
||||
// ==========================================
|
||||
|
||||
/**
|
||||
* ثبت درخواست انتقال وجه (پایا / ساتنا / پل)
|
||||
*/
|
||||
async createCheckout(options: EBankCheckoutOptions) {
|
||||
const accountId = options.accountId || (await this.getDefaultAccountId());
|
||||
if (!accountId) {
|
||||
throw new Error('شناسه حساب زیبال (accountId) الزامی است.');
|
||||
}
|
||||
|
||||
const payload = {
|
||||
accountId,
|
||||
amount: options.amount,
|
||||
iban: options.iban.replace(/\s+/g, '').toUpperCase(),
|
||||
reasonCode: options.reasonCode || 18, // 18: خرید کالا
|
||||
delay: options.delay ?? -1, // -1: instant
|
||||
uniqueCode: options.uniqueCode || `PAY-${Date.now()}`,
|
||||
description: options.description || 'انتقال وجه کنینا',
|
||||
paymentNumber: options.paymentNumber,
|
||||
callbackUrl: options.callbackUrl,
|
||||
};
|
||||
|
||||
return this.request<any>('/ebank/v1/account/checkout/create/', {
|
||||
method: 'POST',
|
||||
body: payload,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* استعلام انتقال وجه با uniqueCode یا trackerId
|
||||
*/
|
||||
async inquireCheckout(params: {
|
||||
accountId?: string;
|
||||
uniqueCode?: string;
|
||||
trackerId?: string;
|
||||
}) {
|
||||
const accountId = params.accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/checkout/inquire/', {
|
||||
method: 'GET',
|
||||
params: {
|
||||
accountId,
|
||||
uniqueCode: params.uniqueCode,
|
||||
trackerId: params.trackerId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* دریافت لیست انتقال وجهها
|
||||
*/
|
||||
async getCheckoutList(filter: EBankCheckoutListFilter) {
|
||||
const accountId = filter.accountId || (await this.getDefaultAccountId());
|
||||
const now = new Date();
|
||||
const defaultFrom = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString();
|
||||
const defaultTo = now.toISOString();
|
||||
|
||||
return this.request<any>('/ebank/v1/account/checkout/list/', {
|
||||
method: 'GET',
|
||||
params: {
|
||||
accountId,
|
||||
fromDate: filter.fromDate || defaultFrom,
|
||||
toDate: filter.toDate || defaultTo,
|
||||
status: filter.status,
|
||||
size: filter.size || 20,
|
||||
page: filter.page || 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* لغو انتقال وجههای در صف
|
||||
*/
|
||||
async cancelCheckout(checkoutIds: string[], accountId?: string) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/checkout/cancel/', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
accountId: targetAccountId,
|
||||
checkoutIds,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 2. حسابها (Bank Accounts & Statements)
|
||||
// ==========================================
|
||||
|
||||
/**
|
||||
* دریافت لیست حسابهای متصل به بانکداری شرکتی
|
||||
*/
|
||||
async getAccountList(activeAccounts?: boolean) {
|
||||
return this.request<any>('/ebank/v1/account/list/', {
|
||||
method: 'GET',
|
||||
params: {
|
||||
activeAccounts,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* دریافت موجودی حساب
|
||||
*/
|
||||
async getAccountBalance(accountId?: string, update = true) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/balance/', {
|
||||
method: 'GET',
|
||||
params: {
|
||||
accountId: targetAccountId,
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* دریافت صورتحساب بانکی حساب متصل
|
||||
*/
|
||||
async getStatementList(filter: EBankStatementFilter) {
|
||||
const accountId = filter.accountId || (await this.getDefaultAccountId());
|
||||
const now = new Date();
|
||||
const defaultFrom = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
|
||||
const defaultTo = now.toISOString();
|
||||
|
||||
return this.request<any>('/ebank/v1/account/statement/list/', {
|
||||
method: 'GET',
|
||||
params: {
|
||||
accountId,
|
||||
fromDate: filter.fromDate || defaultFrom,
|
||||
toDate: filter.toDate || defaultTo,
|
||||
update: filter.update ?? false,
|
||||
size: filter.size || 20,
|
||||
page: filter.page || 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 3. واریزیها و شناسههای واریز (Identified Payments)
|
||||
// ==========================================
|
||||
|
||||
/**
|
||||
* دریافت لیست واریزیهای شناسه دار
|
||||
*/
|
||||
async getIdentifiedPaymentList(filter: EBankIdentifiedPaymentFilter) {
|
||||
const accountId = filter.accountId || (await this.getDefaultAccountId());
|
||||
const now = new Date();
|
||||
const defaultFrom = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString();
|
||||
const defaultTo = now.toISOString();
|
||||
|
||||
return this.request<any>('/ebank/v1/account/identified-payment/list/', {
|
||||
method: 'GET',
|
||||
params: {
|
||||
accountId,
|
||||
fromDate: filter.fromDate || defaultFrom,
|
||||
toDate: filter.toDate || defaultTo,
|
||||
status: filter.status,
|
||||
size: filter.size || 20,
|
||||
page: filter.page || 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* تایید (2) یا رد (3) واریز
|
||||
*/
|
||||
async changeIdentifiedPaymentStatus(
|
||||
transactionId: string,
|
||||
status: 2 | 3,
|
||||
accountId?: string,
|
||||
) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/identified-payment/change-status/', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
accountId: targetAccountId,
|
||||
transactionId,
|
||||
status,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* استعلام وضعیت یک واریز شناسه دار
|
||||
*/
|
||||
async inquireIdentifiedPayment(transactionId: string, accountId?: string) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/identified-payment/inquire/', {
|
||||
method: 'GET',
|
||||
params: {
|
||||
accountId: targetAccountId,
|
||||
transactionId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -358,11 +358,353 @@ export class ZibalService implements IPaymentGateway {
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 6. متد Lazy Payment (درخواست و تایید لیزی)
|
||||
// ==========================================
|
||||
|
||||
/**
|
||||
* درخواست پرداخت در حالت Lazy (در صورت عدم وریفای تا ۲۰ دقیقه، پول برگشت داده میشود)
|
||||
*/
|
||||
async requestLazyPayment(
|
||||
params: PaymentRequestOptions & {
|
||||
nationalCode?: string;
|
||||
allowedCards?: string[];
|
||||
checkMobileWithCard?: boolean;
|
||||
},
|
||||
): Promise<ZibalRequestResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
const payload = {
|
||||
merchant,
|
||||
amount: params.amountRials,
|
||||
callbackUrl: params.callbackUrl,
|
||||
description: params.description || 'پرداخت سفارش (Lazy) در کنینا',
|
||||
orderId: params.orderId,
|
||||
mobile: params.mobile,
|
||||
nationalCode: params.nationalCode,
|
||||
allowedCards: params.allowedCards,
|
||||
checkMobileWithCard: params.checkMobileWithCard,
|
||||
};
|
||||
|
||||
return this.callWithRetry(async () => {
|
||||
this.logger.log(
|
||||
`Sending Lazy payment request to Zibal for orderId=${params.orderId}, amount=${params.amountRials} Rials`,
|
||||
);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/request/lazy`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Zibal Lazy request HTTP ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalRequestResponse;
|
||||
return data;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}, `requestLazyPayment(orderId=${params.orderId})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* تایید پرداخت در حالت Lazy
|
||||
*/
|
||||
async verifyLazyPayment(trackId: string | number): Promise<ZibalVerifyResponse> {
|
||||
const merchant = await this.getMerchant();
|
||||
const payload = {
|
||||
merchant,
|
||||
trackId: String(trackId),
|
||||
};
|
||||
|
||||
return this.callWithRetry(async () => {
|
||||
this.logger.log(`Verifying Lazy payment for trackId=${trackId}`);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/verify`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Zibal verify Lazy HTTP ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ZibalVerifyResponse;
|
||||
return data;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}, `verifyLazyPayment(trackId=${trackId})`);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 7. پلتفرم مالی، کیف پول و استرداد وجه (Refund & Wallets)
|
||||
// Base URL: https://api.zibal.ir with Bearer Token
|
||||
// ==========================================
|
||||
|
||||
private async getAccessToken(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_EBANK_TOKEN' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_EBANK_TOKEN: ${e}`);
|
||||
}
|
||||
return process.env.ZIBAL_EBANK_TOKEN || '';
|
||||
}
|
||||
|
||||
private async apiRequest<T>(
|
||||
endpoint: string,
|
||||
method: 'GET' | 'POST' = 'POST',
|
||||
body?: Record<string, any>,
|
||||
): Promise<T> {
|
||||
const token = await this.getAccessToken();
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const url = `https://api.zibal.ir${endpoint}`;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 15000);
|
||||
|
||||
try {
|
||||
this.logger.log(`[Zibal Core API] ${method} ${url}`);
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers,
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
return data as T;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* لیست کیف پولهای متصل در زیبال
|
||||
*/
|
||||
async getWalletList() {
|
||||
return this.apiRequest<any>('/v1/wallet/list', 'GET');
|
||||
}
|
||||
|
||||
/**
|
||||
* استعلام موجودی یک کیف پول مشخص
|
||||
*/
|
||||
async getWalletBalance(walletId: number) {
|
||||
return this.apiRequest<any>('/v1/wallet/balance', 'POST', { id: walletId });
|
||||
}
|
||||
|
||||
/**
|
||||
* درخواست استرداد وجه (Refund یا Reverse)
|
||||
*/
|
||||
async requestRefund(options: {
|
||||
trackId: number | string;
|
||||
accountId?: string;
|
||||
amount?: number; // Rial
|
||||
tryReverse?: boolean; // true = prioritize reverse
|
||||
cardNumber?: string;
|
||||
description?: string;
|
||||
}) {
|
||||
const accountId =
|
||||
options.accountId ||
|
||||
(await this.prisma.uiText.findUnique({ where: { key: 'ZIBAL_EBANK_ACCOUNT_ID' } }))?.value;
|
||||
|
||||
const payload = {
|
||||
trackId: Number(options.trackId),
|
||||
accountId: accountId || 'default',
|
||||
tryReverse: options.tryReverse ?? false,
|
||||
amount: options.amount,
|
||||
cardNumber: options.cardNumber,
|
||||
description: options.description || 'استرداد وجه سفارش در کنینا',
|
||||
};
|
||||
|
||||
return this.apiRequest<any>('/v1/account/refund', 'POST', payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* استعلام وضعیت استرداد وجه با refundId یا trackId
|
||||
*/
|
||||
async inquireRefund(params: {
|
||||
refundId?: number | string;
|
||||
transactionTrackId?: number | string;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/account/refund/inquiry', 'POST', {
|
||||
refundId: params.refundId ? Number(params.refundId) : undefined,
|
||||
transactionTrackId: params.transactionTrackId
|
||||
? Number(params.transactionTrackId)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* گزارش لیست استردادها
|
||||
*/
|
||||
async getRefundList(filter: {
|
||||
status?: number[];
|
||||
type?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/account/refund/list', 'POST', {
|
||||
status: filter.status,
|
||||
type: filter.type || 4,
|
||||
page: filter.page || 1,
|
||||
size: filter.size || 20,
|
||||
fromDate: filter.fromDate,
|
||||
toDate: filter.toDate,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* گزارش تراکنشهای درگاه پرداخت مستقیماً از زیبال
|
||||
*/
|
||||
async getGatewayTransactionsReport(filter: {
|
||||
merchantId?: string;
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
trackId?: number;
|
||||
status?: number;
|
||||
orderId?: string;
|
||||
mobile?: string;
|
||||
amount?: number;
|
||||
cardNumber?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
verbose?: boolean;
|
||||
}) {
|
||||
const merchantId = filter.merchantId || (await this.getMerchant());
|
||||
return this.apiRequest<any>('/v1/gateway/report/transaction', 'POST', {
|
||||
merchantId,
|
||||
fromDate: filter.fromDate,
|
||||
toDate: filter.toDate,
|
||||
trackId: filter.trackId,
|
||||
status: filter.status,
|
||||
orderId: filter.orderId,
|
||||
mobile: filter.mobile,
|
||||
amount: filter.amount,
|
||||
cardNumber: filter.cardNumber,
|
||||
page: filter.page || 1,
|
||||
size: filter.size || 20,
|
||||
verbose: filter.verbose ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* گزارش تسویههای درگاه و کیفپول
|
||||
*/
|
||||
async getCheckoutReport(filter: {
|
||||
fromDate?: string;
|
||||
toDate?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
transactionTrackId?: number;
|
||||
verbose?: boolean;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/report/checkout', 'POST', {
|
||||
fromDate: filter.fromDate,
|
||||
toDate: filter.toDate,
|
||||
page: filter.page || 1,
|
||||
size: filter.size || 20,
|
||||
transactionTrackId: filter.transactionTrackId,
|
||||
verbose: filter.verbose ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* گزارش صف تسویههای در انتظار
|
||||
*/
|
||||
async getCheckoutQueueReport(verbose = true) {
|
||||
return this.apiRequest<any>('/v1/report/checkout/queue', 'POST', { verbose });
|
||||
}
|
||||
|
||||
/**
|
||||
* استعلام تسویه مشخص با checkoutRequestId یا uniqueCode
|
||||
*/
|
||||
async inquireCheckoutReport(walletId: string, checkoutRequestId?: string, uniqueCode?: string) {
|
||||
return this.apiRequest<any>('/v1/report/checkout/inquire', 'POST', {
|
||||
walletId,
|
||||
checkoutRequestId,
|
||||
uniqueCode,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* ثبت ذینفع جدید برای تسهیم (SubMerchant)
|
||||
*/
|
||||
async createSubMerchant(data: {
|
||||
bankAccount: string;
|
||||
name: string;
|
||||
callbackUrl?: string;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/subMerchant/create', 'POST', {
|
||||
bankAccount: data.bankAccount.replace(/\s+/g, '').toUpperCase(),
|
||||
name: data.name,
|
||||
callbackUrl: data.callbackUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* لیست ذینفعهای ثبت شده
|
||||
*/
|
||||
async getSubMerchantList(page = 1, size = 20) {
|
||||
return this.apiRequest<any>('/v1/subMerchant/list', 'POST', { page, size });
|
||||
}
|
||||
|
||||
/**
|
||||
* ویرایش ذینفع غیرفعال
|
||||
*/
|
||||
async editSubMerchant(data: {
|
||||
id: string;
|
||||
bankAccount: string;
|
||||
name: string;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/subMerchant/edit', 'POST', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-friendly Persian messages for Zibal result codes
|
||||
*/
|
||||
getResultMessage(resultCode: number): string {
|
||||
const messages: Record<number, string> = {
|
||||
1: 'موفق',
|
||||
2: 'API Key به درستی ارسال نشده است',
|
||||
3: 'API Key صحیح نیست',
|
||||
4: 'اجازه دسترسی به این سرویس صادر نشده است',
|
||||
5: 'آدرس callbackUrl نامعتبر است',
|
||||
6: 'مقدار ورودی نامعتبر است',
|
||||
7: 'IP ارسالکننده درخواست نامعتبر است',
|
||||
8: 'API Key غیرفعال است',
|
||||
9: 'حداقل مبلغ باید ۱,۰۰۰ ریال باشد',
|
||||
14: 'درخواست انتقال وجه یا تسویه یافت نشد',
|
||||
21: 'شماره شبای وارد شده معتبر نیست',
|
||||
29: 'موجودی کیفپول کارمزد کافی نیست',
|
||||
44: 'شبای مورد نظر یافت نشد',
|
||||
45: 'سرویسدهندهها برای استعلام در دسترس نیستند',
|
||||
100: 'با موفقیت تایید شد',
|
||||
102: 'merchant یافت نشد',
|
||||
103: 'merchant غیرفعال است',
|
||||
@@ -401,6 +743,10 @@ export class ZibalService implements IPaymentGateway {
|
||||
'10': 'صادرکننده کارت نامعتبر است',
|
||||
'11': 'خطای سوییچ بانک صادرکننده',
|
||||
'12': 'کارت یا حساب مسدود است',
|
||||
'15': 'تراکنش استرداد شده',
|
||||
'16': 'تراکنش در حال استرداد',
|
||||
'18': 'تراکنش ریورس شده',
|
||||
'21': 'پذیرنده نامعتبر است',
|
||||
};
|
||||
|
||||
return messages[code] || `وضعیت نامشخص (${statusCode})`;
|
||||
|
||||
Reference in new issue
Block a user