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) { /** @var \App\Models\Shop\Order */ $concernedOrder = $transaction->order; $orderTotal = new Money($concernedOrder->total_ttc, $transaction->currency); $orderRefunded = new Money($concernedOrder->total_refund, $transaction->currency); $amountToRefund = new Money($amount, $transaction->currency); $systemPay = $this->getPayment(); $client = $systemPay->generateRestClient(); $isPartialRefund = $orderTotal->subtract($orderRefunded)->subtract($amountToRefund)->isPositive(); $transactionIsRemise = $client->canBeRefunded($transaction->foreign_id); // ? Transaction can be partially refunded ? if (!$transactionIsRemise && $isPartialRefund) { throw ValidationException::withMessages([ 'error' => \trans('La transaction doit être remisée pour pouvoir effectuer un remboursement partiel') ]); } $refundTransactionResponse = $client->cancelOrRefund( $transaction->foreign_id, $amountToRefund ); if ( !\in_array( data_get($refundTransactionResponse, 'answer.detailedStatus'), [ // * Remboursé full 'CANCELLED', // * Remboursé partiel 'AUTHORISED' ] ) ) { Log::error($refundTransactionResponse->toJson()); throw ValidationException::withMessages([ 'error' => \trans('La transaction n\'a pas pu être remboursée') ]); } $wasFullyRefunded = data_get($refundTransactionResponse, 'answer.detailedStatus') === 'CANCELLED'; $wasPartiallyRefunded = !$wasFullyRefunded; // ! Just cancel the transaction (elle n'a pas été remisée). if (!$transactionIsRemise and $wasFullyRefunded) { $transaction->status = TransactionStatus::canceled(); $transaction->save(); return $transaction; } Log::info($refundTransactionResponse->toJson()); $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(); OrderIsRefunded::dispatch( $concernedOrder->refresh(), $refundTransaction->refresh() ); return $refundTransaction; }); } 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 } }