Files
Backend-Api/ServiceHost/Controllers/GeneralController.cs
mahan 8bd248c6a7 Integrate Sepehr payment gateway with Parbad
Added Parbad libraries and configured Sepehr gateway in `Program.cs`
and `appsettings.json`. Implemented payment request and verification
logic in `Index.cshtml.cs` and `GeneralController`. Updated
`ServiceHost.csproj` with required dependencies. Refactored roll call
logic and removed unused URLs in `launchSettings.json`. Enhanced
services with memory cache storage and added `Bogus` for data
generation.
2025-11-12 15:00:12 +03:30

169 lines
6.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using _0_Framework.Application;
using CompanyManagment.App.Contracts.PaymentTransaction;
using CompanyManagment.EFCore.Migrations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ServiceHost.BaseControllers;
using System.Globalization;
using _0_Framework.Application.PaymentGateway;
using Microsoft.Extensions.Options;
using CompanyManagment.App.Contracts.FinancialStatment;
using CompanyManagment.App.Contracts.FinancilTransaction;
using Parbad;
namespace ServiceHost.Controllers;
public class GeneralController : GeneralBaseController
{
private readonly IPaymentTransactionApplication _paymentTransactionApplication;
private readonly IPaymentGateway _paymentGateway;
private readonly IFinancialStatmentApplication _financialStatmentApplication;
private readonly IOnlinePayment _onlinePayment;
public GeneralController(IPaymentTransactionApplication paymentTransactionApplication,IHttpClientFactory clientFactory, IFinancialStatmentApplication financialStatmentApplication, IOptions<AppSettingConfiguration> appSetting, IOnlinePayment onlinePayment)
{
_paymentTransactionApplication = paymentTransactionApplication;
_paymentGateway = new AqayePardakhtPaymentGateway(clientFactory, appSetting);
_financialStatmentApplication = financialStatmentApplication;
_onlinePayment = onlinePayment;
}
/// <summary>
/// نمایش اطلاعات عمومی مانند تاریخ ها و سال ها
/// </summary>
/// <returns></returns>
[HttpGet("Dates")]
public IActionResult GetDates()
{
var pc = new PersianCalendar();
var now = DateTime.Now;
var currentYear = pc.GetYear(now);
var years = Enumerable.Range(1370, currentYear - 1370 + 1).ToList();
var months = Enumerable.Range(1, 12).ToList();
var currentDate = new { Year = currentYear, Month = pc.GetMonth(now), Day = pc.GetDayOfMonth(now) };
return new JsonResult(new
{
years,
months,
currentDate
});
}
[HttpGet("/api/callback"), HttpPost("/api/callback")]
public async Task<IActionResult> Verify()
{
var invoice = await _onlinePayment.FetchAsync();
string data = "";
foreach (var keyValuePair in invoice.AdditionalData)
{
data += keyValuePair.Key + "=" + keyValuePair.Value + ";";
}
await _onlinePayment.CancelAsync(invoice);
return Ok(data);
// Check if the invoice is new, or it's already processed before.
if (invoice.Status != PaymentFetchResultStatus.ReadyForVerifying)
{
// You can also see if the invoice is already verified before.
var isAlreadyVerified = invoice.IsAlreadyVerified;
return Content("The payment was not successful.");
}
var verifyResult = await _onlinePayment.VerifyAsync(invoice);
// Note: Save the verifyResult.TransactionCode in your database.
}
[HttpPost("/api/callback3232")]
public async Task<IActionResult> OnGetCallBack(string? transid, string? cardnumber, string? tracking_number,
string bank, string invoice_id, string? status,CancellationToken cancellationToken)
{
if (!long.TryParse(invoice_id, out var paymentTransactionId))
{
return BadRequest("Invalid invoice_id");
}
var transaction = await _paymentTransactionApplication.GetDetails(paymentTransactionId);
if (transaction == null)
{
return NotFound("Transaction not found");
}
if (transaction.Status != PaymentTransactionStatus.Pending)
{
return BadRequest("این تراکنش قبلا پرداخت شده است");
}
// اگر شماره کارت یا شماره پیگیری خالی باشد، تراکنش ناموفق است
if (string.IsNullOrWhiteSpace(cardnumber) || string.IsNullOrWhiteSpace(tracking_number))
{
return await HandleFailedTransaction(transaction, paymentTransactionId);
}
var verifyCommand = new VerifyPaymentGateWayRequest()
{
Amount = transaction.Amount/10,
TransactionId = transid
};
var verifyRes =await _paymentGateway.Verify(verifyCommand, cancellationToken);
// اگر استاتوس 1 باشد، تراکنش موفق است
if (verifyRes.IsSuccess)
{
var command = new CreateFinancialStatment()
{
ContractingPartyId = transaction.ContractingPartyId,
Deptor = 0,
Creditor = transaction.Amount,
DeptorString = "0",
TypeOfTransaction = "credit",
DescriptionOption = "بابت قرارداد مابین (روابط کار)",
Description = "درگاه بانکی",
};
var statementResult = _financialStatmentApplication.CreateFromBankGateway(command);
if (!statementResult.IsSuccedded)
{
return await HandleFailedTransaction(transaction, paymentTransactionId);
}
var setSuccessResult = _paymentTransactionApplication.SetSuccess(paymentTransactionId, cardnumber, bank);
if (!setSuccessResult.IsSuccedded)
{
return new JsonResult(setSuccessResult);
}
return Redirect(BuildCallbackUrl(transaction.CallBackUrl, true, transaction.Id));
}
// در غیر این صورت تراکنش ناموفق است
return await HandleFailedTransaction(transaction, paymentTransactionId);
}
private async Task<IActionResult> HandleFailedTransaction(PaymentTransactionDetailsViewModel transaction, long transactionId)
{
var result = _paymentTransactionApplication.SetFailed(transactionId);
if (!result.IsSuccedded)
{
return new JsonResult(result);
}
return Redirect(BuildCallbackUrl(transaction.CallBackUrl, false, transaction.Id));
}
private string BuildCallbackUrl(string baseUrl, bool isSuccess, long transactionId)
{
var statusCode = isSuccess ? "1" : "0";
return $"{baseUrl}/callback?Status={statusCode}&transactionId={transactionId}";
}
}