ekart/backend/app/Actions/Payment/ProcessOrderPaymentAction.php
2026-03-25 17:17:35 +05:30

52 lines
1.6 KiB
PHP

<?php
namespace App\Actions\Payment;
use App\Data\Payment\PaymentResponseDTO;
use App\Enums\Payment\PaymentModes;
use App\Enums\Payment\PaymentStatusEnum;
use App\Models\Order;
use App\Models\PaymentStatus;
use App\Services\Payment\PaymentGatewayFactory;
use DB;
use Log;
use Throwable;
final readonly class ProcessOrderPaymentAction
{
public function __construct(
private PaymentGatewayFactory $paymentGatewayFactory,
) {}
/**
* Execute the action.
*/
public function execute(Order $order, PaymentModes $mode): PaymentResponseDTO
{
$gateway = $this->paymentGatewayFactory->make($mode);
try {
DB::beginTransaction();
$response = $gateway->charge($order);
if ($response->isSuccess) {
$order->payments()->create(
[
'transaction_id' => $response->transactionId,
'amount' => $response->amount,
'currency' => $response->currency,
'payment_method' => $response->method->value,
'payment_status_id' => PaymentStatus::getIdByName(PaymentStatusEnum::Unpaid->value),
]
);
}
DB::commit();
return $response;
} catch (Throwable $e) {
DB::rollBack();
Log::error('Error occurred while processing the payment.', [$e->getMessage()]);
abort(500, 'Something went wrong. Please try again or contact us to get in touch with our support team. ');
}
}
}