From 87b73357b481f58cd93b740e88e471b585b6da75 Mon Sep 17 00:00:00 2001 From: David Torras Date: Sat, 29 Jan 2022 18:19:43 +0100 Subject: [PATCH] Cast amount from Redsys notification to float --- src/Casters/NotificationAmountCaster.php | 13 +++++++++++++ src/RedsysRequest.php | 19 ++++++++++++------- src/Support/NotificationParameters.php | 10 ++++------ tests/ResponseTest.php | 2 +- 4 files changed, 30 insertions(+), 14 deletions(-) create mode 100644 src/Casters/NotificationAmountCaster.php diff --git a/src/Casters/NotificationAmountCaster.php b/src/Casters/NotificationAmountCaster.php new file mode 100644 index 0000000..d3b5abe --- /dev/null +++ b/src/Casters/NotificationAmountCaster.php @@ -0,0 +1,13 @@ +parameters = $requestParameters ?? new RequestParameters(); - $this->parameters->amount = number_format(round($amount, 2) * 100, 0, '', ''); + $this->parameters->amount = $this->formatAmount($amount); $this->parameters->currency = $currency->value; $this->parameters->merchantCode = $this->redsysClient->merchantCode; $this->parameters->order = $orderNumber; @@ -49,6 +49,11 @@ public function createPaymentRequest( return $this->getRequestFieldsArray(); } + private function formatAmount(float $amount): int + { + return number_format(round($amount, 2) * 100, 0, '', ''); + } + #[ArrayShape(['Ds_SignatureVersion' => "string", 'Ds_MerchantParameters' => "string", 'Ds_Signature' => "string"])] public function getRequestFieldsArray(): array { @@ -67,13 +72,13 @@ public function getFormHtml(): string $formFields = $this->getRequestFieldsArray(); - return ' -
- - - + return << + + +
- '; + HTML; } } diff --git a/src/Support/NotificationParameters.php b/src/Support/NotificationParameters.php index 8790683..ec67bc2 100644 --- a/src/Support/NotificationParameters.php +++ b/src/Support/NotificationParameters.php @@ -2,6 +2,8 @@ namespace Creagia\Redsys\Support; +use Creagia\Redsys\Casters\NotificationAmountCaster; +use Spatie\DataTransferObject\Attributes\CastWith; use Spatie\DataTransferObject\DataTransferObject; class NotificationParameters extends DataTransferObject @@ -13,7 +15,8 @@ class NotificationParameters extends DataTransferObject public string $hour; #[MapTo('DS_AMOUNT')] - public int $amount; + #[CastWith(NotificationAmountCaster::class)] + public float $amount; #[MapTo('DS_CURRENCY')] public int $currency; @@ -85,9 +88,4 @@ public function toArray(): array { return array_filter(parent::toArray()); } - - public function getAmount(): float - { - return (float) $this->amount / 100; - } } diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php index ad0cc91..086f597 100644 --- a/tests/ResponseTest.php +++ b/tests/ResponseTest.php @@ -26,7 +26,7 @@ $redsysNotification->setParametersFromResponse($responsePost); $result = $redsysNotification->checkResponse(); - expect($result->getAmount())->toBe($this->paymentRequestAmount); + expect($result->amount)->toBe($this->paymentRequestAmount); }); it('fails if signatures differ', function () {