ldc-boutique-cnc/app/Lib/Payments/Adapters/SystemPayPaymentAdapter.php
2023-04-25 21:52:27 +02:00

208 lines
8.4 KiB
PHP

<?php
namespace App\Lib\Payments\Adapters;
use App\Enums\Order\PaymentModeEnum;
use App\Enums\Order\PaymentStatus;
use App\Enums\Order\TransactionStatus;
use App\Enums\Order\TransactionType;
use App\Lib\Payments\PaymentAdapter;
use App\Models\Customer\Customer;
use App\Models\Payment\Transaction;
use App\Models\Shop\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Illuminate\Validation\ValidationException;
use LDC\LaravelSystempay\LaravelSystempay;
use Money\Money;
use Symfony\Component\HttpFoundation\Response;
class SystemPayPaymentAdapter extends PaymentAdapter
{
/**
* Get Systempay adapter
*
* @return \LDC\LaravelSystempay\LaravelSystempay
*/
private function getPayment(): LaravelSystempay
{
return app('systempay');
}
/**
* Get success route
*
* ! Overload signed route more timeout delay.
*
* @param \App\Models\Shop\Transaction $transaction
* @param array $parameters
* @return string
*/
protected function successRoute(Transaction $transaction, array $parameters = []): string
{
$parameters['transaction'] = $transaction;
return \url(URL::temporarySignedRoute(
'order-tunnel.checkout',
\now()->addMinutes(5),
$parameters,
false
));
}
/**
* Generate the checkout reponse to initiate a transaction.
*
* * This is a unique transaction with qty 1 and the desired amount for the order.
*
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
* @phpcs:disable Generic.Files.LineLength.TooLong
* @param \App\Models\Customer\Customer $customer
* @param \App\Models\Shop\Order $order
* @param \App\Models\Payment\Transaction $transaction
* @param \Closure(\App\Models\Customer\Customer,\App\Models\Shop\Order,\App\Models\Payment\Transaction): void $succeed
* @param \Closure(\Exception): void $failed
* @return \Symfony\Component\HttpFoundation\Response
*/
public function checkout(
Customer $customer,
Order $order,
Transaction $transaction,
\Closure $succeed,
\Closure $failed
): Response {
return $this->wrapAction(function () use ($order, $transaction) {
// * Associate transaction to order
$transaction->order()->associate($order);
// * Enregistrement commande avant checkout.
if (!$order->save() or !$transaction->save()) {
report(new \RuntimeException('Order saving error happened.'));
throw ValidationException::withMessages([
'error' => trans('Une erreur est survenue, veuillez réssayer')
]);
}
$systemPay = $this->getPayment();
$request = $systemPay->checkout(
$transaction->amount,
$order->reference,
$order->email,
$this->successRoute($transaction),
$this->cancelRoute($order),
[
'order' => $order->reference,
'transaction' => $transaction->reference,
'order_label' => trans('Commande :ref', ['ref' => $order->reference]),
'transaction_label' => trans('Transaction :ref', ['ref' => $transaction->reference]),
]
);
/** @var \Lyranetwork\Field|null */
if (!($transIdField = $request->getFields()->get('vads_trans_id'))) {
throw new \RuntimeException('Missing vads_trans_id form lib');
}
// * Save transaction Id (generated by LIB)
$transaction->assignPaymentId($transIdField->getValue());
if (!$transaction->save()) {
throw new \RuntimeException('Failed to save transaction id');
}
// * Generate view response form.
return $systemPay->generateCheckoutRedirectView($request);
}, function () use ($succeed, $customer, $order, $transaction) {
$succeed($customer, $order, $transaction);
}, $failed);
}
// phpcs:ignore Squiz.Commenting.FunctionComment.MissingParamTag
/**
* @inheritDoc
*
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
* @phpcs:disable Squiz.Commenting.FunctionComment.MissingReturn
* @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.Missing
*/
public function checkoutIsResponseIsValid(Customer $customer, Transaction $transaction): ?Transaction
{
if (!request()->hasValidSignature(false)) {
return null;
}
// ! La validation se fait par IPN uniquement.
return $transaction;
}
/**
* Do a refund using the same payment method as the transaction.
*
* @param \App\Models\Payment\Transaction $transaction
* @param integer $amount
* @param object $items
* @return \App\Models\Payment\Transaction The new refund transaction.
* @phpcs:ignore Squiz.Commenting.FunctionComment.ThrowsNoFullStop
* @throws \Illuminate\Validation\ValidationException If doing the refund fails.
*/
public function doRefundCustomer(
Transaction $transaction,
int $amount,
object $items
): Transaction {
try {
return DB::transaction(function () use ($transaction, $amount, $items) {
$amountToRefund = new Money($amount, $transaction->currency);
$systemPay = $this->getPayment();
$client = $systemPay->generateRestClient();
$refundTransactionResponse = $client->cancelOrRefund(
$transaction->foreign_id,
$amountToRefund
);
/** @var \App\Models\Shop\Order */
$concernedOrder = $transaction->order;
$refund_foreign_id = Transaction::getPaymentForeignKeyName(
PaymentModeEnum::systemPay(),
data_get($refundTransactionResponse, 'answer.uuid')
);
// * Find an existing refund transaction or Create a new transaction as a refund.
/** @var \App\Models\Payment\Transaction|null */
$refundTransaction = Transaction::query()
->where('type', TransactionType::credit())
->where('foreign_refund_id', $refund_foreign_id)->first();
if ($refundTransaction) {
// * Mettre a jour le montant du remboursement.
$refundTransaction->amount = $refundTransaction->amount->add($amountToRefund);
} else {
$refundTransaction = Transaction::getNewInstance(
$transaction->payment_mode,
TransactionType::credit(),
$items,
\intval($amountToRefund->getAmount())
);
}
$refundTransaction->status = TransactionStatus::pending();
$refundTransaction->assignRefundId(data_get($refundTransactionResponse, 'answer.uuid'));
$refundTransaction->order()->associate($concernedOrder);
$refundTransaction->saveOrFail();
$concernedOrder->refresh();
$concernedOrder->total_refund = \intval($amountToRefund->getAmount()) +
\intval($concernedOrder->total_refund);
$concernedOrder->payment_status = $concernedOrder->can_be_refund ?
PaymentStatus::refundedPartial() : PaymentStatus::refunded();
$concernedOrder->saveQuietly();
return $refundTransaction->refresh();
});
} catch (\LDC\LaravelSystempay\Exceptions\LaravelSystempayException $e) {
report($e);
$message = \trans("Le remboursement via Systempay à échoué '{$e->getMessage()}',
veuillez vérifier via le backoffice de systempay");
throw ValidationException::withMessages(['error' => $message]);
}//end try
}
}