50 lines
1.5 KiB
PHP
50 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Actions;
|
|
|
|
use App\Data\PaymentResponseDTO;
|
|
use App\Enums\PaymentModes;
|
|
use App\Enums\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. ');
|
|
}
|
|
}
|
|
}
|