update payment
This commit is contained in:
@@ -1,23 +1,111 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CreatePaymentDto } from '../dto/create-payment.dto';
|
||||
import { UpdatePaymentDto } from '../dto/update-payment.dto';
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { RestaurantPaymentMethod } from '../entities/restaurant-payment-method.entity';
|
||||
import axios from 'axios';
|
||||
import { IPaymentRequest, IPaymentResponse, PaymentStatus } from '../interface/payment-status';
|
||||
import { Payment } from '../entities/payment.entity';
|
||||
import { EntityManager, RequiredEntityData } from '@mikro-orm/core';
|
||||
import { Order } from '../../orders/entities/order.entity';
|
||||
|
||||
@Injectable()
|
||||
export class PaymentsService {
|
||||
create(createPaymentDto: CreatePaymentDto) {
|
||||
return 'This action adds a new payment';
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
|
||||
async initializePayment(
|
||||
restaurantPaymentMethodId: string,
|
||||
amount: number,
|
||||
orderId: string,
|
||||
): Promise<{ paymentUrl: string }> {
|
||||
// Validate amount
|
||||
if (amount <= 0) {
|
||||
throw new BadRequestException('Amount must be greater than zero');
|
||||
}
|
||||
|
||||
// Validate order exists
|
||||
const order = await this.em.findOne(Order, { id: orderId });
|
||||
if (!order) {
|
||||
throw new NotFoundException('Order not found');
|
||||
}
|
||||
|
||||
// Load restaurant payment method with payment method relationship
|
||||
const restaurantPaymentMethod = await this.em.findOne(
|
||||
RestaurantPaymentMethod,
|
||||
{ id: restaurantPaymentMethodId },
|
||||
{ populate: ['paymentMethod'] },
|
||||
);
|
||||
if (!restaurantPaymentMethod) {
|
||||
throw new NotFoundException('Restaurant payment method not found');
|
||||
}
|
||||
|
||||
if (!restaurantPaymentMethod.paymentMethod?.isOnline) {
|
||||
throw new BadRequestException('Payment method is not online');
|
||||
}
|
||||
|
||||
if (!restaurantPaymentMethod.callbackUrl) {
|
||||
throw new BadRequestException('Callback URL is not configured');
|
||||
}
|
||||
|
||||
if (!restaurantPaymentMethod.merchantId) {
|
||||
throw new BadRequestException('Merchant ID is not provided');
|
||||
}
|
||||
|
||||
if (!restaurantPaymentMethod.paymentMethod?.paymentUrl) {
|
||||
throw new BadRequestException('Payment URL is not configured');
|
||||
}
|
||||
|
||||
// Request to payment gateway with error handling
|
||||
let gatewayResponse: IPaymentResponse;
|
||||
try {
|
||||
gatewayResponse = await this.requestToPaymentGateway(restaurantPaymentMethod.paymentMethod.paymentUrl, {
|
||||
amount,
|
||||
callbackUrl: restaurantPaymentMethod.callbackUrl,
|
||||
merchantId: restaurantPaymentMethod.merchantId,
|
||||
description: `Payment for order #${orderId}`,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
throw new BadRequestException(`Failed to connect to payment gateway: ${errorMessage}`);
|
||||
}
|
||||
|
||||
// Check gateway response code (typically 100 means success for Iranian gateways)
|
||||
if (gatewayResponse.code !== 100 && gatewayResponse.code !== 0) {
|
||||
throw new BadRequestException(`Payment gateway error: ${gatewayResponse.message || 'Unknown error'}`);
|
||||
}
|
||||
|
||||
if (!gatewayResponse.authority) {
|
||||
throw new BadRequestException('Payment gateway did not return an authority token');
|
||||
}
|
||||
|
||||
// Create payment record and save authority
|
||||
const payment = this.em.create(Payment, {
|
||||
amount,
|
||||
authority: gatewayResponse.authority,
|
||||
order: this.em.getReference(Order, orderId),
|
||||
gateway: restaurantPaymentMethod.paymentMethod.name,
|
||||
status: PaymentStatus.Pending,
|
||||
} as RequiredEntityData<Payment>);
|
||||
|
||||
await this.em.persistAndFlush(payment);
|
||||
|
||||
// Return payment URL
|
||||
const paymentUrl = `${restaurantPaymentMethod.paymentMethod.paymentUrl}/${gatewayResponse.authority}`;
|
||||
return { paymentUrl };
|
||||
}
|
||||
|
||||
private async requestToPaymentGateway(
|
||||
gatewayPaymentUrl: string,
|
||||
requestPayment: IPaymentRequest,
|
||||
): Promise<IPaymentResponse> {
|
||||
const response = await axios.post<IPaymentResponse>(gatewayPaymentUrl, requestPayment);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
update(_id: number, _updatePaymentDto: unknown) {
|
||||
return `This action updates a #${_id} payment`;
|
||||
}
|
||||
|
||||
findAll() {
|
||||
return `This action returns all payments`;
|
||||
}
|
||||
|
||||
findOne(id: number) {
|
||||
return `This action returns a #${id} payment`;
|
||||
}
|
||||
|
||||
update(id: number, updatePaymentDto: UpdatePaymentDto) {
|
||||
return `This action updates a #${id} payment`;
|
||||
return this.em.find(Payment, {});
|
||||
}
|
||||
|
||||
remove(id: number) {
|
||||
|
||||
Reference in New Issue
Block a user