diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..6d18804 --- /dev/null +++ b/.babelrc @@ -0,0 +1,4 @@ +{ + "presets": ["@babel/preset-env"], + "plugins": ["@babel/plugin-transform-async-to-generator", "@babel/plugin-transform-runtime"] +} diff --git a/Bootstrap.php b/Bootstrap.php index 2371768..9106039 100644 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -1,8 +1,10 @@ listen('shop.hook.' . \HOOK_BESTELLABSCHLUSS_INC_BESTELLUNGINDB, function (array $args) { - /** - * Handle Pending Orders. - * - * Prevent the WaWi from collection an order that is currently PENDING. - * Therefore, we mark the order as already collected (not great but JTL does not have a pending state). - */ try { + /** @var Bestellung $order */ + $order = $args['oBestellung']; + + /** @var SessionHelper $sessionHelper */ + $sessionHelper = Shop::Container()->get(SessionHelper::class); + + // update cBestellNummer because we might already have generated it but bestellungInDB() has generated + // a new one, resulting in a wrong order number in the confirmation mail for example! + $orderNumber = $sessionHelper->get(SessionHelper::KEY_ORDER_ID); + if (!empty($orderNumber) && $orderNumber != $order->cBestellNr) { + $order->cBestellNr = $orderNumber; + } elseif ($sessionHelper->get(SessionHelper::KEY_CHECKOUT_SESSION)) { + $sessionHelper->set(SessionHelper::KEY_ORDER_ID, $order->cBestellNr); + } + + /** + * Handle Pending Orders. + * + * Prevent the WaWi from collection an order that is currently PENDING. + * Therefore, we mark the order as already collected (not great but JTL does not have a pending state). + */ if (Shop::has('360HpOrderPending')) { - $args['oBestellung']->cAbgeholt = 'Y'; + $order->cAbgeholt = 'Y'; } } catch (Throwable $th) { Logger::error( @@ -114,6 +139,23 @@ public function boot(Dispatcher $dispatcher): void } }); + $dispatcher->listen('shop.hook.' . \HOOK_IO_HANDLE_REQUEST, function (array $args) { + // Hook into ajax request handling for apple pay merchant validation + try { + $controller = new ApplePayController( + $this->getPlugin(), + Shop::Container()->get(CertificationService::class), + $args['io'] + ); + $controller->handle(); + } catch (Throwable $th) { + Logger::error( + 'Error ' . $th->getCode() . ':' . $th->getMessage() . ', Exception in Hook ' + . \HOOK_IO_HANDLE_REQUEST + ); + } + }); + // Backend Hooks if (!Shop::isFrontend()) { $dispatcher->listen('backend.notification', function () { @@ -152,8 +194,9 @@ public function installed() // Deactivate Invoice Factoring Payment Method by setting nNutzbar to 0 foreach ($this->getPlugin()->getPaymentMethods()->getMethods() as $method) { - if ($method->getActive() && $method->getUsable() && - $method->getClassName() === HeidelpayInvoiceFactoring::class + if ( + ($method->getActive() || $method->getUsable()) && + in_array($method->getClassName(), $this->getDeprecatedPaymentMethods()) ) { $this->getDB()->update( 'tzahlungsart', @@ -180,8 +223,9 @@ public function updated($oldVersion, $newVersion) { // Deactivate Invoice Factoring Payment Method by setting nNutzbar to 0 foreach ($this->getPlugin()->getPaymentMethods()->getMethods() as $method) { - if (($method->getActive() || $method->getUsable()) && - $method->getClassName() === HeidelpayInvoiceFactoring::class + if ( + ($method->getActive() || $method->getUsable()) && + in_array($method->getClassName(), $this->getDeprecatedPaymentMethods()) ) { $this->getDB()->update( 'tzahlungsart', @@ -219,18 +263,48 @@ public function renderAdminMenuTab(string $tabName, int $menuID, JTLSmarty $smar $controller->setModel($model); $controller->handleAjax(); } catch (Throwable $th) { - return json_encode([ + echo json_encode([ 'status' => 'error', 'messages' => [$th->getMessage()] ]); + die; } } $controller = new AdminOrdersController($this->getPlugin(), $smarty); $controller->setModel($model); + return $controller->handle(); + case JtlLinkHelper::ADMIN_TAB_APPLE_PAY: + /** @var Config $config */ + $config = Shop::Container()->get(Config::class); + if (!$config->get(Config::PRIVATE_KEY)) { + return 'Missing API Key'; + } + $controller = new AdminApplePayController($this->getPlugin(), $smarty); + $controller->setCertService(Shop::Container()->get(CertificationService::class)); + return $controller->handle(); case JtlLinkHelper::ADMIN_TAB_SETTINGS: $controller = new AdminSettingsController($this->getPlugin(), $smarty); + return $controller->handle(); + case JtlLinkHelper::ADMIN_TAB_KEYPAIRS: + $model = new KeyPairModel($this->getDB()); + $controller = new AdminKeyPairsController($this->getPlugin(), $smarty); + $controller->setModel($model); + + // Handle Ajax Requests + if (Request::isAjaxRequest() && Request::getVar('controller') == 'KeyPairs') { + try { + $controller->handleAjax(); + } catch (Throwable $th) { + echo json_encode([ + 'status' => 'error', + 'messages' => [$th->getMessage()] + ]); + die; + } + } + return $controller->handle(); default: return parent::renderAdminMenuTab($tabName, $menuID, $smarty); @@ -240,4 +314,13 @@ public function renderAdminMenuTab(string $tabName, int $menuID, JTLSmarty $smar return $th->getMessage(); } } + + private function getDeprecatedPaymentMethods(): array + { + return [ + HeidelpayInvoiceFactoring::class, + HeidelpayHirePurchaseDirectDebit::class, + HeidelpayFlexiPayDirect::class + ]; + } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 315c744..2055bd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,116 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [1.4.1] (April 2024) +### Changed +- reduce Unzer UI Component fields if they are already filled by the shop +- Unzer Direct Debit only available for EUR + +### Fixed +- Validation of the Unzer UI Components +- use correct currency factor for instalments + +## [1.4.0] (April 2024) +### Added +- New Payment Method **Unzer Direct Debit** +- Missing Translations + +### Fixed +- prefill birthday field if alreay set by shop +- fixed issue with unzer ui component validation +- fixed issue with session new being cleared correctly when changing shipping/billing address in the checkout + +### Changed +- updated payment and system requirements in the documenation + +## [1.3.2] (January 2024) +### Fixed: +- Fixed issue with API Call in Settings after fresh install + +## [1.3.1] (January 2024) +### Added +- Added Key Pair Management +- Added new payment method **Unzer Instalment** +- Added support for PHP 8.2 und PHP 8.3 +- Added improved error handling for api errors + +## Changed +- updated Unzer SDK +- highlight deprecated payment methods + + +## [1.3.0] (August 2023) +### Added +- Added LICENSE and NOTICE + +### Changed +- Changed Payment Method name from Unzer Invoice to Unzer Invoice (Paylater) + +### Fixed +- Clear Plugin Session on the order status page in case that a user aborted its payment process + +### Removed +- Removed deprecated Payment Method **Unzer Instalment**/**Unzer Ratenkauf** +- Removed deprecated Payment Method **Unzer Bank Transfer**/**Unzer Direktüberweisung** + +## [1.2.1] (February 2023) +### Added +- Added compatability for **JTL 5.2 and PHP 8.1** +- Added debug logs for the shipping API call +- Added Reference Text for cancellations + +## Changed +- Show Invoice ID in Order Detail only if either local invoice id or invoice id from the API response is available +- Hide Unzer Insight Portal Button as the correct link to the order cannot be determined reliably + +### Fixed +- Locale Mapping for Unzer UI Component +- Fixed unzer applepay debugging when in sandbox mode +- Fixed issue with submit button staying disabled on invalid input on the additional checkout step +- Fixed rounding issue in total gross amount API field + +## [1.2.0] (November 2022) +### Added +- Added Bancontact as payment method +- Added Unzer Rechnung (Buy Now, Pay Later) as payment method +- Added option to disable automatic setting of incoming payments + +### Changed +- Unzer SDK version updated to 1.2.0.0 + +## [1.1.0] (July 2022) +### Added +- Added company info to customer object +- Added verification and notification if frontend URLs have changed due to JTL/plugin updates and how to correct them +- Added VAT amount to shopping cart object +- Added ApplePay payment method + +### Changed +- Unzer SDK version updated to 1.1.4.2 +- Remove default value for payment method selection, as the NOVA theme already has a back button in the additional payment step. + +### Fixed +- Fixed an issue with instalments sending incorrect/temporary order numbers to Unzer +- Fixed an unhandled error when retrieving refunds in the backend +- Fixed problem with umlauts in intermediate payment step encoded with HTML entities instead of UTF-8 +- Fixed problem with cancelling Invoice (Secured) orders before they are completed +- Fixed problem with wrong order number in order confirmation emails + +## [1.0.2] (March 2022) +### Added +- add minimum customer info (name and email) to all payments + +### Changed +- use short id as transaction id in payment history (WaWi) + +### Fixed +- set default db engine and charset when creating database tables to avoid issues due to weird defaults +- add error handling to avoid issues in the frontend when API is not callable *(ie missing keys)* +- fix issue with -0.0 beeing interpreted as negative in the unzer api +- potential fix for mismatch of order ids between the unzer insight portal and the shop +- error in the placeholder of the public key setting in the backend + + ## [1.0.1] (November 2021) ### Added - JTL Shop 5.1 Compatability @@ -17,6 +127,3 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) a ## [1.0.0] (July 2021) ### Added - Initial Release - -[1.0.1]: https://github.com/unzerdev/jtl5/compare/1.0.0...1.0.1 -[1.0.0]: https://github.com/unzerdev/jtl5 \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..086a99c --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 - today Unzer GmbH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/Migrations/Migration20201027083900.php b/Migrations/Migration20201027083900.php index ef5c81d..9b8aeed 100644 --- a/Migrations/Migration20201027083900.php +++ b/Migrations/Migration20201027083900.php @@ -22,7 +22,7 @@ public function up() $this->execute('CREATE TABLE IF NOT EXISTS ' . Config::TABLE . ' ( `key` VARCHAR(255) NOT NULL PRIMARY KEY, `value` VARCHAR(255) NOT NULL - );'); + ) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;'); // Create Order Mapping Table $this->execute( @@ -36,7 +36,7 @@ public function up() `payment_type_name` VARCHAR(255), /* payment type name from heidelpay */ `payment_type_id` VARCHAR(255), /* payment type id from heidelpay */ PRIMARY KEY (`jtl_order_id`, `payment_id`) - );' + ) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;' ); // Create Charge Mapping Table @@ -46,7 +46,7 @@ public function up() `order_id` INT(10) NOT NULL, /* jtl order table id (kBestellung) */ `charge_id` VARCHAR(255), /* charge id from heidelpay */ `payment_id` VARCHAR(255) /* payment id from heidelpay */ - );' + ) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;' ); } diff --git a/Migrations/Migration20220511114913.php b/Migrations/Migration20220511114913.php new file mode 100644 index 0000000..7428384 --- /dev/null +++ b/Migrations/Migration20220511114913.php @@ -0,0 +1,28 @@ +execute( + 'ALTER TABLE ' . Config::TABLE . ' + CHANGE `value` `value` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;' + ); + } + + public function down() + { + } +} diff --git a/Migrations/Migration20221006103000.php b/Migrations/Migration20221006103000.php new file mode 100644 index 0000000..45e5a75 --- /dev/null +++ b/Migrations/Migration20221006103000.php @@ -0,0 +1,28 @@ +execute( + 'ALTER TABLE ' . ChargeMappingModel::CHARGE_TABLE . ' + ADD `delivery_id` INT(10) DEFAULT NULL AFTER `payment_id`;' + ); + } + + public function down() + { + } +} diff --git a/Migrations/Migration20230919100000.php b/Migrations/Migration20230919100000.php new file mode 100644 index 0000000..25a2765 --- /dev/null +++ b/Migrations/Migration20230919100000.php @@ -0,0 +1,35 @@ +execute( + 'CREATE TABLE IF NOT EXISTS ' . KeyPairModel::TABLE . ' ( + `id` INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY, + `private_key` VARCHAR(255) NOT NULL, + `public_key` VARCHAR(255) NOT NULL, + `is_b2b` TINYINT(1) DEFAULT 0, + `currency_id` INT(10) NOT NULL, + `payment_method_id` INT(10) NOT NULL + ) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;' + ); + } + + public function down() + { + if ($this->doDeleteData()) { + $this->execute('DROP TABLE IF EXISTS `' . KeyPairModel::TABLE . '`', ReturnType::DEFAULT); + } + } +} diff --git a/Migrations/Migration20230925100000.php b/Migrations/Migration20230925100000.php new file mode 100644 index 0000000..64f8a8a --- /dev/null +++ b/Migrations/Migration20230925100000.php @@ -0,0 +1,43 @@ +columnExists()) { + $this->execute( + 'ALTER TABLE ' . OrderMappingModel::ORDER_TABLE . ' + ADD COLUMN `payment_method_id` INT(10) NULL' + ); + } + } + + public function down() + { + if ($this->doDeleteData() && $this->columnExists()) { + $this->execute( + 'ALTER TABLE `' . OrderMappingModel::ORDER_TABLE . '` DROP COLUMN payment_method_id', + ReturnType::DEFAULT + ); + } + } + + private function columnExists(): bool + { + return !empty( + $this->getDB()->executeQuery( + 'SHOW COLUMNS FROM ' . OrderMappingModel::ORDER_TABLE . ' LIKE \'payment_method_id\'', + ReturnType::AFFECTED_ROWS + ) + ); + } +} diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..e789e5d --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +Copyright (C) 2020 - today Unzer GmbH + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index e06314f..62fa308 100644 --- a/README.md +++ b/README.md @@ -1,51 +1,56 @@ -# Unzer payment methods (JTL shop 5) +# Unzer Zahlungsarten (JTL-Shop 5) -This plugin integrates the following Unzer payment methods in the JTL Shop: +Dieses Plugin integriert die folgenden Unzer-Zahlungsarten im JTL Shop: - Alipay +- ApplePay +- Bancontact +- Direktüberweisung - EPS - Giropay - iDEAL -- Credit Card / Debit Card +- Kreditkarte +- Lastschrift +- SEPA Lastschrift - PayPal - Przelewy24 +- Ratenkauf +- Rechnungskauf - SOFORT +- Vorkasse - WeChat Pay -- Invoice -- Sepa Direct Debit -- Unzer Bank Transfer -- Unzer Instalment -- Unzer Invoice secured -- Unzer Direct Debit secured -- Unzer Prepayment +- (Veraltet) Unzer Ratenkauf +- (Veraltet) Unzer Rechnungskauf +- (Veraltet) Unzer Rechnungskauf (secured) +- (Veraltet) Unzer Lastschrift Gesichert ## Installation / Update -### System requirements -- JTL-Shop 5.0.0+ and its requirements -- PHP 7.1 - 7.4 -- The following PHP extensions +### Systemvoraussetzungen +- JTL-Shop 5.0.0+ und dessen Vorraussetzungen +- PHP Version: 7.4 - 8.3 +- Die folgenden PHP Erweiterungen - ext-json - ext-curl -- In order to avoid rounding errors when transmitting floating point values to the API we recommend you to set the following value in your `php.ini`, which will select an enhanced algorithm for rounding such numbers. -~~~ini -// php.ini -; When floats & doubles are serialized store serialize_precision significant -; digits after the floating point. The default value ensures that when floats -; are decoded with unserialize, the data will remain the same. -serialize_precision = -1 -~~~ +### Weitere Voraussetzungen +Sie müssen bei Unzer registriert sein. -### Further requirements -You must be registered with Unzer. +#### Apple Pay +Wenn Sie Apple Pay auf Ihrer Seite anbieten möchten, müssen Sie außerdem die folgenden Voraussetzungen erfüllen: -### Plugin installation -The installation of the plugin is done in the standard procedure for JTL-Shop 5 as described [here](https://jtl-devguide.readthedocs.io/projects/jtl-shop/de/latest/shop_plugins/allgemein.html#pluginverwaltung-im-backend-von-jtl-shop). +- Apple Developer Account mit Teilnahme am Apple Developer Program, siehe Mitgliedschaft auswählen - Support - Apple Developer -### Plugin update -For an update, upload the plugin to the `./plugins/` folder or via the plugin manager in the shop backend in the latest version as for an installation (and overwrite all existing plugin files if necessary) or follow the instructions of the Extension Store. -Then go to the plugin manager in the shop backend and press the update button. +> **Ohne Teilnahme am am Apple Developer Program kann Apple Pay im Plugin nicht genutzt werden! Der einfache und kostenlose Apple Developer Account reicht nicht aus!** -## Configuration -After the actual plugin installation, it is necessary to activate the new payment methods and add them to the desired shipping methods. -Further information and configuration can be found in the [Instructions](https://redirect.solution360.de/?r=docsunzerjtl5). \ No newline at end of file +### Plugin-Installation +Die Installation des Plugins erfolgt im Standardverfahren für JTL-Shop 5, wie es [hier](https://jtl-devguide.readthedocs.io/projects/jtl-shop/de/latest/shop_plugins/allgemein.html#pluginverwaltung-im-backend-von-jtl-shop) beschrieben ist. + +### Plugin-Update +Für ein Update laden Sie das Plugin wie bei einer Installation in der neuesten Version hoch (und überschreiben ggf. alle vorhandenen Plugindateien) oder folgen Sie den Hinweisen des Extension Stores. + +Gehen Sie dann in die Pluginverwaltung und betätigen Sie den Update-Button. + +## Konfiguration +Nach der eigentlichen Plugin-Installation ist es notwendig, die neuen Zahlungsmethoden zu aktivieren und zu den gewünschten Versandarten hinzuzufügen. + +Weitere Informationen und Konfiguration finden Sie in der [Anleitung](https://redirect.solution360.de/?r=docsunzerjtl5) \ No newline at end of file diff --git a/adminmenu/js/admin.js b/adminmenu/js/admin.js index 9c1f36c..7e82476 100644 --- a/adminmenu/js/admin.js +++ b/adminmenu/js/admin.js @@ -109,9 +109,13 @@ ); }; - $(document).ready(function () { + $(function () { // Colored Input $('.form-colored').each(previewColor).on('change keyup blur input focus', previewColor); window.hpAdmin = new HeidelpayAdmin(window.hpAdminAjaxUrl); + + $('.hp-admin-content .custom-file-input').on('change',function(e) { + $(this).next('.custom-file-label').html(e.target.files[0].name); + }); }); })(jQuery, window); \ No newline at end of file diff --git a/adminmenu/js/keypairs.js b/adminmenu/js/keypairs.js new file mode 100644 index 0000000..2b8543a --- /dev/null +++ b/adminmenu/js/keypairs.js @@ -0,0 +1,102 @@ +(function ($, window, undefined) { + $(function () { + // Setup + const admin = window.hpAdmin; + const $keyPairs = $('.hp-keypairs'); + const $modal = $('#hp-keypair-modal'); + const $addTrigger = $('#hp-keypairs-add'); + + /** + * + * @param {{template: ?String}} response + */ + const setModalContent = (response) => { + if (response && response.template) { + const $body = $modal.find('.modal-body'); + + var show = () => { + $body.html(response.template); + $modal.modal('show'); + }; + + if ($modal.hasClass('modal-loaded')) { + $modal.modal('hide'); + show(); + } else { + show(); + $modal.addClass('modal-loaded'); + } + } + }; + + /** + * @param {JQuery.Event} e + */ + const onDelete = (e) => { + const form = $(e.target); + const data = { + id: form.closest('tr').data('id'), + jtl_token: form.find('.jtl_token').val() + }; + + e.preventDefault(); + admin.doAjaxCall('KeyPairs:delete', data, (response) => { + if (response && response.listing) { + $('#modal-footer-delete-confirm').modal('hide'); + $keyPairs.html(response.listing); + deleteConfirmation(); + } + }); + }; + + /** + * @param {JQuery.Event} e + */ + const onAdd = (e) => { + e.preventDefault(); + admin.doAjaxCall('KeyPairs:edit', { id: null }, setModalContent); + }; + + /** + * @param {JQuery.Event} e + */ + const onSave = (e) => { + e.preventDefault(); + + const fields = $(e.target).find('input,select'); + const data = {}; + fields.each((i, el) => { + data[el.name] = $(el).is(':checkbox') ? $(el).is(':checked') : $(el).val(); + }); + + admin.doAjaxCall('KeyPairs:save', data, (response) => { + if (response.status !== 'success') { + return; + } + + if (response.template) { + $modal.find('.modal-body').html(response.template); + } + + if (response.listing) { + $keyPairs.html(response.listing); + deleteConfirmation(); + } + }); + }; + + /** + * @param {JQuery.Event} e + */ + const onEdit = (e) => { + e.preventDefault(); + admin.doAjaxCall('KeyPairs:edit', { id: $(e.target).closest('tr').data('id') }, setModalContent); + }; + + // Register Events + $keyPairs.on('submit', '.keypair-action-form', onDelete); + $addTrigger.on('click', onAdd); + $modal.find('form').on('submit', onSave); + $keyPairs.on('click', '[data-edit]', onEdit); + }); +})(jQuery, window); \ No newline at end of file diff --git a/adminmenu/template/applepay.tpl b/adminmenu/template/applepay.tpl new file mode 100644 index 0000000..b711ba2 --- /dev/null +++ b/adminmenu/template/applepay.tpl @@ -0,0 +1,177 @@ +{include file="{$hpAdmin.adminTemplatePath}partials/_header.tpl"} + +
+
+
+
+ {$jtl_token} + + {* General Config Data *} +
+
+

{__('hpApplePayPaymentGeneral')}

+
+ +
+ {* Merchant ID *} +
+
+ +
+
+ + {__('hpApplePayPaymentGeneralMerchantIdHelp')} +
+
+ + {* Merchant Domain *} +
+
+ +
+
+ + {__('hpApplePayPaymentGeneralMerchantDomainHelp')} +
+
+
+
+ + {* Payment Processing *} +
+
+

{__('hpApplePayPaymentProcessingCertificate')}

+
+ +
+ {* CSR*} +
+
+ +
+
+ + {__('hpApplePayPaymentProcessingCertificateCSRHelp')} +
+
+ + +   {__('hpApplePayDownloadCert')} + +
+
+ + {* Apple Cert *} +
+
+ +
+
+ + {__('hpApplePayPaymentProcessingCertificateAppleHelp')} +
+
+
+
+ + +
+ +
+ +
+
+
+
+ + {* Unzer IDs *} +
+
+ +
+
+ + +
+
+ +
+
+
+
+ + {* Merchant Identity *} +
+
+

{__('hpApplePayMerchantIdentityCertificate')}

+
+ +
+ {* CSR *} +
+
+ +
+
+ + {__('hpApplePayMerchantIdentityCertificateCSRHelp')} +
+
+ + +   {__('hpApplePayDownloadCert')} + +
+
+ + {* Apple Cert *} +
+
+ +
+
+ + {__('hpApplePayMerchantIdentityCertificateAppleHelp')} +
+
+
+
+ + +
+ +
+ +
+
+
+
+
+
+ + {* Save Button *} +
+
+
+
+
+ +
+
+
+
+
+
+
+
+
\ No newline at end of file diff --git a/adminmenu/template/keypairs.tpl b/adminmenu/template/keypairs.tpl new file mode 100644 index 0000000..3b297f7 --- /dev/null +++ b/adminmenu/template/keypairs.tpl @@ -0,0 +1,49 @@ +{include file="{$hpAdmin.adminTemplatePath}partials/_header.tpl"} + +
+
+ + + + + + + + + + + + + {include file="./partials/_keypair_list.tpl"} + +
{__('hpSettingsPrivateKeyLabel')}{__('hpSettingsPublicKeyLabel')}{__('hpKeypairIsB2B')}{__('currency')}{__('hpPaymentMethod')}
+
+
+ + + +
+
+
+ +
+
+
\ No newline at end of file diff --git a/adminmenu/template/partials/_includes.tpl b/adminmenu/template/partials/_includes.tpl index d0df63c..7a6736e 100644 --- a/adminmenu/template/partials/_includes.tpl +++ b/adminmenu/template/partials/_includes.tpl @@ -9,3 +9,4 @@ + diff --git a/adminmenu/template/partials/_keypair_item.tpl b/adminmenu/template/partials/_keypair_item.tpl new file mode 100644 index 0000000..3a0be27 --- /dev/null +++ b/adminmenu/template/partials/_keypair_item.tpl @@ -0,0 +1,82 @@ + +
+ +{include file="./_header.tpl"} + + + + {* Private Key *} +
+
+ +
+
+ {* Hash current private key to avoid leaking it *} + + {__('hpSettingsPrivateKeyHelp')} +
+
+ + {* Public Key *} +
+
+ +
+
+ + {__('hpSettingsPublicKeyHelp')} +
+
+ + {* Is B2B *} +
+
+ +
+
+ isB2B()}checked{/if} /> + {__('yes')} + {__('hpKeypairIsB2BHelp')} +
+
+ + {* Currency *} +
+
+ +
+
+ + {__('hpKeypairCurrencyHelp')} +
+
+ + {* Payment Methods *} +
+
+ +
+
+ + {__('hpKeypairPaymentMethodsHelp')} +
+
+
\ No newline at end of file diff --git a/adminmenu/template/partials/_keypair_list.tpl b/adminmenu/template/partials/_keypair_list.tpl new file mode 100644 index 0000000..310dda2 --- /dev/null +++ b/adminmenu/template/partials/_keypair_list.tpl @@ -0,0 +1,50 @@ +{foreach from=$unzerKeypairs.items item=$item} + + + {* Hide last 16 chars to prevent misuse from unauthorized users *} + {substr($item->getPrivateKey(), 0, -16)}{str_repeat('•', 16)} + + + {$item->getPublicKey()} + + + {if $item->isB2B()} + + {else} + + {/if} + + + {if isset($unzerKeypairs.currencies[$item->getCurrencyId()])} + {$unzerKeypairs.currencies[$item->getCurrencyId()].name} + {/if} + + + {if isset($unzerKeypairs.paymentMethods[$item->getPaymentMethodId()])} + {__($unzerKeypairs.paymentMethods[$item->getPaymentMethodId()]->getName())} + {/if} + + +
+ {$jtl_token} + + + + +
+ + +{foreachelse} + + {__('noData')} + +{/foreach} \ No newline at end of file diff --git a/adminmenu/template/partials/_order_detail.tpl b/adminmenu/template/partials/_order_detail.tpl index 86bf823..a5cd74e 100644 --- a/adminmenu/template/partials/_order_detail.tpl +++ b/adminmenu/template/partials/_order_detail.tpl @@ -1,18 +1,24 @@ {strip}
-
+ {*
{if $hpPortalUrl} - - {__('hpOpenInPortal')} - + {if $hpPayment->getPaymentType()->getResourceName() === 'paylater-invoice'} + + {__('hpOpenInPaylaterPortal')} + + {else} + + {__('hpOpenInPortal')} + + {/if} {/if}
-
+
*}
@@ -144,8 +150,24 @@ {/if} -
{__('hpInvoiceNumber')}
-
{$hpPayment->getInvoiceId()}
+ {if $hpPayment->getInvoiceId()} +
{__('hpInvoiceNumber')}
+
+ {$hpPayment->getInvoiceId()} +
+ {elseif $hpOrderMapping->getInvoiceId()} +
{__('hpInvoiceNumber')}
+
+ {$hpOrderMapping->getInvoiceId()} +
+ {/if} + + {if !empty($hpPayment->getAuthorization()) && !empty($hpPayment->getAuthorization()->getDescriptor())} +
{__('hpPaymentReference')}
+
+ {$hpPayment->getAuthorization()->getDescriptor()} +
+ {/if}
{__('hpPaymentId')}
{$hpPayment->getId()}
@@ -154,44 +176,44 @@
{if $hpPayment->getPaymentType()->getResourceName() == 'card'} {__('hpPaymentmethodCard')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'sepa-direct-debit'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'sepa-direct-debit'} {__('hpPaymentmethodSEPA')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'sepa-direct-debit-guaranteed'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'sepa-direct-debit-guaranteed'} {__('hpPaymentmethodSEPAGuaranteed')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'sepa-direct-debit-secured'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'sepa-direct-debit-secured'} {__('hpPaymentmethodSEPAGuaranteed')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'invoice'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'invoice'} {__('hpPaymentmethodInvoice')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'invoice-guaranteed'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'invoice-guaranteed'} {__('hpPaymentmethodInvoiceGuaranteed')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'invoice-secured'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'invoice-secured'} {__('hpPaymentmethodInvoiceGuaranteed')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'invoice-factoring'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'invoice-factoring'} {__('hpPaymentmethodInvoiceFactoring')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'paypal'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'paypal'} {__('hpPaymentmethodPayPal')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'sofort'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'sofort'} {__('hpPaymentmethodSOFORT')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'giropay'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'giropay'} {__('hpPaymentmethodGiropay')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'prepayment'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'prepayment'} {__('hpPaymentmethodPrepayment')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'eps'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'eps'} {__('hpPaymentmethodEPS')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'pis'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'pis'} {__('hpPaymentmethodFlexiPayDirect')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'alipay'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'alipay'} {__('hpPaymentmethodAlipay')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'wechatpay'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'wechatpay'} {__('hpPaymentmethodWeChatPay')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'ideal'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'ideal'} {__('hpPaymentmethodiDEAL')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'hire-purchase-direct-debit'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'hire-purchase-direct-debit'} {__('hpPaymentmethodHirePurchaseDirectDebit')} - {else if $hpPayment->getPaymentType()->getResourceName() == 'installment-secured'} + {elseif $hpPayment->getPaymentType()->getResourceName() == 'installment-secured'} {__('hpPaymentmethodHirePurchaseDirectDebit')} {else} - {$hpPayment->getPaymentType()->getResourceName()} + {__($hpPayment->getPaymentType()->getResourceName())} {/if} ({$hpPayment->getPaymentType()->getId()}) @@ -210,9 +232,7 @@

{__('hpTransactions')}

- - {if !empty($hpPayment->getCharges())} - {*
*} + {if !empty($hpPayment->getAuthorization() || !empty($hpPayment->getCharges()))} @@ -223,31 +243,55 @@ - {foreach from=$hpPayment->getCharges() item='charge' name='charges'} - - - + {if !empty($hpPayment->getAuthorization())} + + + + - {/foreach} + {/if} + + {if !empty($hpPayment->getCharges())} + {foreach from=$hpPayment->getCharges() item='charge' name='charges'} + + + + + + {/foreach} + {/if}
{$charge->getId()}{$charge->getShortId()}
{$hpPayment->getAuthorization()->getId()}{$hpPayment->getAuthorization()->getShortId()} - {if $charge->isPending()} + {if $hpPayment->getAuthorization()->isPending()} {__('hpStatePending')} - {elseif $charge->isError()} + {elseif $hpPayment->getAuthorization()->isError()} {__('hpStateFailure')} - {elseif $charge->isSuccess()} + {elseif $hpPayment->getAuthorization()->isSuccess()} {__('hpStateSuccessful')} {else} - {/if} - {if $charge->getMessage()} -   + {if $hpPayment->getAuthorization()->getMessage()} +   {/if} - {if isset($charge->getAmount())}{($charge->getAmount())|number_format:2}{else} - {/if}{if isset($charge->getCurrency())} {$charge->getCurrency()}{/if}{if isset($hpPayment->getAuthorization()->getAmount())}{number_format($hpPayment->getAuthorization()->getAmount(), 2)}{else} - {/if}{if isset($hpPayment->getAuthorization()->getCurrency())} {$hpPayment->getAuthorization()->getCurrency()}{/if}
{$charge->getId()}{$charge->getShortId()} + {if $charge->isPending()} + {__('hpStatePending')} + {elseif $charge->isError()} + {__('hpStateFailure')} + {elseif $charge->isSuccess()} + {__('hpStateSuccessful')} + {else} + - + {/if} + + {if $charge->getMessage()} +   + {/if} + + {if isset($charge->getAmount())}{number_format($charge->getAmount(), 2)}{else} - {/if}{if isset($charge->getCurrency())} {$charge->getCurrency()}{/if}
- {*
*} {else}
{__('hpEmptyResult')}
{/if} @@ -300,7 +344,7 @@
{/if} - {if !empty($hpPayment->getCancellations())} + {if !empty($hpCancellations)}
@@ -319,7 +363,7 @@ - {foreach from=$hpPayment->getCancellations() item='cancelation' name='cancelations'} + {foreach from=$hpCancellations item='cancelation' name='cancelations'} {$cancelation->getId()} {$cancelation->getShortId()} @@ -339,7 +383,7 @@ {/if}
{if isset($cancelation->getPaymentReference())}{$cancelation->getPaymentReference()}{else} - {/if} - {if isset($cancelation->getAmount())}{($cancelation->getAmount())|number_format:2}{else} - {/if} + {if isset($cancelation->getAmount())}{number_format($cancelation->getAmount(), 2)}{else} - {/if} {/foreach} diff --git a/adminmenu/template/partials/_order_item.tpl b/adminmenu/template/partials/_order_item.tpl index 71a5b48..6aa1843 100644 --- a/adminmenu/template/partials/_order_item.tpl +++ b/adminmenu/template/partials/_order_item.tpl @@ -1,5 +1,5 @@ {strip} - + {if $hpOrder->getJtlOrderNumber()}{$hpOrder->getJtlOrderNumber()}{elseif $hpOrder->getId()}{$hpOrder->getId()}{else} - {/if} @@ -24,8 +24,8 @@ - {/if} - {if $hpOrder->getPaymentId()}{$hpOrder->getPaymentId()}{else} - {/if} - + {if $hpOrder->getPaymentId()}{$hpOrder->getPaymentId()}{else} - {/if} + {if $hpOrder->getPaymentState()} {if $hpOrder->getPaymentState() === \UnzerSDK\Constants\PaymentState::STATE_NAME_PENDING} {__('hpStatePending')} @@ -50,44 +50,44 @@ {if $hpOrder->getPaymentTypeName()} {if $hpOrder->getPaymentTypeName() == 'card'} {__('hpPaymentmethodCard')} - {else if $hpOrder->getPaymentTypeName() == 'sepa-direct-debit'} + {elseif $hpOrder->getPaymentTypeName() == 'sepa-direct-debit'} {__('hpPaymentmethodSEPA')} - {else if $hpOrder->getPaymentTypeName() == 'sepa-direct-debit-guaranteed'} + {elseif $hpOrder->getPaymentTypeName() == 'sepa-direct-debit-guaranteed'} {__('hpPaymentmethodSEPAGuaranteed')} - {else if $hpOrder->getPaymentTypeName() == 'sepa-direct-debit-secured'} + {elseif $hpOrder->getPaymentTypeName() == 'sepa-direct-debit-secured'} {__('hpPaymentmethodSEPAGuaranteed')} - {else if $hpOrder->getPaymentTypeName() == 'invoice'} + {elseif $hpOrder->getPaymentTypeName() == 'invoice'} {__('hpPaymentmethodInvoice')} - {else if $hpOrder->getPaymentTypeName() == 'invoice-guaranteed'} + {elseif $hpOrder->getPaymentTypeName() == 'invoice-guaranteed'} {__('hpPaymentmethodInvoiceGuaranteed')} - {else if $hpOrder->getPaymentTypeName() == 'invoice-secured'} + {elseif $hpOrder->getPaymentTypeName() == 'invoice-secured'} {__('hpPaymentmethodInvoiceGuaranteed')} - {else if $hpOrder->getPaymentTypeName() == 'invoice-factoring'} + {elseif $hpOrder->getPaymentTypeName() == 'invoice-factoring'} {__('hpPaymentmethodInvoiceFactoring')} - {else if $hpOrder->getPaymentTypeName() == 'paypal'} + {elseif $hpOrder->getPaymentTypeName() == 'paypal'} {__('hpPaymentmethodPayPal')} - {else if $hpOrder->getPaymentTypeName() == 'sofort'} + {elseif $hpOrder->getPaymentTypeName() == 'sofort'} {__('hpPaymentmethodSOFORT')} - {else if $hpOrder->getPaymentTypeName() == 'giropay'} + {elseif $hpOrder->getPaymentTypeName() == 'giropay'} {__('hpPaymentmethodGiropay')} - {else if $hpOrder->getPaymentTypeName() == 'prepayment'} + {elseif $hpOrder->getPaymentTypeName() == 'prepayment'} {__('hpPaymentmethodPrepayment')} - {else if $hpOrder->getPaymentTypeName() == 'eps'} + {elseif $hpOrder->getPaymentTypeName() == 'eps'} {__('hpPaymentmethodEPS')} - {else if $hpOrder->getPaymentTypeName() == 'pis'} + {elseif $hpOrder->getPaymentTypeName() == 'pis'} {__('hpPaymentmethodFlexiPayDirect')} - {else if $hpOrder->getPaymentTypeName() == 'alipay'} + {elseif $hpOrder->getPaymentTypeName() == 'alipay'} {__('hpPaymentmethodAlipay')} - {else if $hpOrder->getPaymentTypeName() == 'wechatpay'} + {elseif $hpOrder->getPaymentTypeName() == 'wechatpay'} {__('hpPaymentmethodWeChatPay')} - {else if $hpOrder->getPaymentTypeName() == 'ideal'} + {elseif $hpOrder->getPaymentTypeName() == 'ideal'} {__('hpPaymentmethodiDEAL')} - {else if $hpOrder->getPaymentTypeName() == 'hire-purchase-direct-debit'} + {elseif $hpOrder->getPaymentTypeName() == 'hire-purchase-direct-debit'} {__('hpPaymentmethodHirePurchaseDirectDebit')} - {else if $hpOrder->getPaymentTypeName() == 'installment-secured'} + {elseif $hpOrder->getPaymentTypeName() == 'installment-secured'} {__('hpPaymentmethodHirePurchaseDirectDebit')} {else} - {$hpOrder->getPaymentTypeName() } + {__($hpOrder->getPaymentTypeName())} {/if} {/if} @@ -95,15 +95,17 @@ ({$hpOrder->getPaymentTypeId()}) {/if} - {gibPreisStringLocalized($hpOrder->getOrder()->fGesamtsumme)} - {if isset($hpOrder->getOrder()->dErstellt)}{$hpOrder->getOrder()->dErstellt|strtotime|date_format:"d.m.Y H:i:s"}{else} - {/if} + + {\JTL\Catalog\Product\Preise::getLocalizedPriceString($hpOrder->getOrder()->fGesamtsumme, $hpOrder->getOrder()->Waehrung)} + + {if isset($hpOrder->getOrder()->dErstellt)}{strtotime($hpOrder->getOrder()->dErstellt)|date_format:"d.m.Y H:i:s"}{else} - {/if}
- {if $hpPortalUrl} + {* {if $hpPortalUrl} - {/if} + {/if} *}
diff --git a/adminmenu/template/settings.tpl b/adminmenu/template/settings.tpl index ebe0425..fe1befc 100644 --- a/adminmenu/template/settings.tpl +++ b/adminmenu/template/settings.tpl @@ -14,12 +14,18 @@
{* Private Key *} + {* Hide last 16 chars to prevent misuse from unauthorized users *}
- +
- + {__('hpSettingsPrivateKeyHelp')}
@@ -30,7 +36,7 @@
- + {__('hpSettingsPublicKeyHelp')}
@@ -94,6 +100,19 @@
+ {* Add Incming Payments *} +
+
+ +
+
+ + {__('hpSettingsActive')} + {__('hpSettingsAddIncomingPaymentsHelp')} +
+
+ + {* PQ Selector Submit Button *}
@@ -111,7 +130,7 @@
- + {__('hpSettingsPqSelectorChangePaymentMethodHelp')}
@@ -216,6 +235,34 @@ {__('hpSettingsPqMethodPaymentInformationHelp')}
+ + {* PQ Selector Instalment Information *} +
+
+ +
+
+ + {__('hpSettingsPqSelectorInstalmentInfoHelp')} +
+
+ + {* PQ Method Instalment Information *} +
+
+ +
+
+ + {__('hpSettingsPqMethodInstalmentInfoHelp')} +
+
diff --git a/composer.json b/composer.json index cced485..994921c 100644 --- a/composer.json +++ b/composer.json @@ -8,6 +8,7 @@ } ], "require": { - "unzerdev/php-sdk": "~1.1.0" + "unzerdev/php-sdk": "~3.5.0", + "phpseclib/phpseclib": "~3.0" } } diff --git a/composer.lock b/composer.lock index 1d1c0e6..d8e7341 100644 --- a/composer.lock +++ b/composer.lock @@ -4,28 +4,255 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1bb1d0bc104cc6f166d9deba276ff8ba", + "content-hash": "be6ccc8080da00e4b98c05d6f11aeb65", "packages": [ + { + "name": "paragonie/constant_time_encoding", + "version": "v2.6.3", + "source": { + "type": "git", + "url": "https://github.com/paragonie/constant_time_encoding.git", + "reference": "58c3f47f650c94ec05a151692652a868995d2938" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/58c3f47f650c94ec05a151692652a868995d2938", + "reference": "58c3f47f650c94ec05a151692652a868995d2938", + "shasum": "" + }, + "require": { + "php": "^7|^8" + }, + "require-dev": { + "phpunit/phpunit": "^6|^7|^8|^9", + "vimeo/psalm": "^1|^2|^3|^4" + }, + "type": "library", + "autoload": { + "psr-4": { + "ParagonIE\\ConstantTime\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com", + "role": "Maintainer" + }, + { + "name": "Steve 'Sc00bz' Thomas", + "email": "steve@tobtu.com", + "homepage": "https://www.tobtu.com", + "role": "Original Developer" + } + ], + "description": "Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)", + "keywords": [ + "base16", + "base32", + "base32_decode", + "base32_encode", + "base64", + "base64_decode", + "base64_encode", + "bin2hex", + "encoding", + "hex", + "hex2bin", + "rfc4648" + ], + "support": { + "email": "info@paragonie.com", + "issues": "https://github.com/paragonie/constant_time_encoding/issues", + "source": "https://github.com/paragonie/constant_time_encoding" + }, + "time": "2022-06-14T06:56:20+00:00" + }, + { + "name": "paragonie/random_compat", + "version": "v9.99.100", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a", + "shasum": "" + }, + "require": { + "php": ">= 7" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*", + "vimeo/psalm": "^1" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "type": "library", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "polyfill", + "pseudorandom", + "random" + ], + "support": { + "email": "info@paragonie.com", + "issues": "https://github.com/paragonie/random_compat/issues", + "source": "https://github.com/paragonie/random_compat" + }, + "time": "2020-10-15T08:29:30+00:00" + }, + { + "name": "phpseclib/phpseclib", + "version": "3.0.37", + "source": { + "type": "git", + "url": "https://github.com/phpseclib/phpseclib.git", + "reference": "cfa2013d0f68c062055180dd4328cc8b9d1f30b8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/cfa2013d0f68c062055180dd4328cc8b9d1f30b8", + "reference": "cfa2013d0f68c062055180dd4328cc8b9d1f30b8", + "shasum": "" + }, + "require": { + "paragonie/constant_time_encoding": "^1|^2", + "paragonie/random_compat": "^1.4|^2.0|^9.99.99", + "php": ">=5.6.1" + }, + "require-dev": { + "phpunit/phpunit": "*" + }, + "suggest": { + "ext-dom": "Install the DOM extension to load XML formatted public keys.", + "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", + "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", + "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", + "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." + }, + "type": "library", + "autoload": { + "files": [ + "phpseclib/bootstrap.php" + ], + "psr-4": { + "phpseclib3\\": "phpseclib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jim Wigginton", + "email": "terrafrost@php.net", + "role": "Lead Developer" + }, + { + "name": "Patrick Monnerat", + "email": "pm@datasphere.ch", + "role": "Developer" + }, + { + "name": "Andreas Fischer", + "email": "bantu@phpbb.com", + "role": "Developer" + }, + { + "name": "Hans-Jürgen Petrich", + "email": "petrich@tronic-media.com", + "role": "Developer" + }, + { + "name": "Graham Campbell", + "email": "graham@alt-three.com", + "role": "Developer" + } + ], + "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", + "homepage": "http://phpseclib.sourceforge.net", + "keywords": [ + "BigInteger", + "aes", + "asn.1", + "asn1", + "blowfish", + "crypto", + "cryptography", + "encryption", + "rsa", + "security", + "sftp", + "signature", + "signing", + "ssh", + "twofish", + "x.509", + "x509" + ], + "support": { + "issues": "https://github.com/phpseclib/phpseclib/issues", + "source": "https://github.com/phpseclib/phpseclib/tree/3.0.37" + }, + "funding": [ + { + "url": "https://github.com/terrafrost", + "type": "github" + }, + { + "url": "https://www.patreon.com/phpseclib", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib", + "type": "tidelift" + } + ], + "time": "2024-03-03T02:14:58+00:00" + }, { "name": "unzerdev/php-sdk", - "version": "1.1.4.0", + "version": "3.5.0", "source": { "type": "git", "url": "https://github.com/unzerdev/php-sdk.git", - "reference": "e18bf5e598f1f6160d373904b4a4b79758033fd5" + "reference": "818cb1fb02ef65278221a95d82663ca11ec459e5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/unzerdev/php-sdk/zipball/e18bf5e598f1f6160d373904b4a4b79758033fd5", - "reference": "e18bf5e598f1f6160d373904b4a4b79758033fd5", + "url": "https://api.github.com/repos/unzerdev/php-sdk/zipball/818cb1fb02ef65278221a95d82663ca11ec459e5", + "reference": "818cb1fb02ef65278221a95d82663ca11ec459e5", "shasum": "" }, "require": { "ext-json": "*", - "php": "~7.1.0|~7.2.0|~7.3.0|~7.4.0|~8.0.0" + "php": "~7.4.0|~8.0.0|~8.1.0|~8.2.0|~8.3.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^2.0", + "friendsofphp/php-cs-fixer": "^3.0", "phpunit/phpunit": ">6.5 <10.0" }, "suggest": { @@ -42,12 +269,12 @@ "license": [ "Apache-2.0" ], - "description": "This is the php sdk to connect to the Unzer rest api.", + "description": "This is the php sdk to connect to the Unzer rest API.", "support": { "email": "support@unzer.com", - "source": "https://github.com/unzerdev/php-sdk/tree/1.1.4.0" + "source": "https://github.com/unzerdev/php-sdk/tree/3.5.0" }, - "time": "2021-08-31T09:58:12+00:00" + "time": "2024-02-08T11:12:26+00:00" } ], "packages-dev": [], @@ -58,5 +285,5 @@ "prefer-lowest": false, "platform": [], "platform-dev": [], - "plugin-api-version": "2.1.0" + "plugin-api-version": "2.3.0" } diff --git a/frontend/css/unzer.min.css b/frontend/css/unzer.min.css new file mode 100644 index 0000000..29a2e4d --- /dev/null +++ b/frontend/css/unzer.min.css @@ -0,0 +1 @@ +.unzerUI .field{position:relative}.label-slide .form-group:not(.exclude-from-label-slide):not(.checkbox) .unzerUI.form label{position:relative;top:initial;left:initial;font-size:1rem;margin:0 0 .28571429rem;padding:0;transform:none;line-height:30px;pointer-events:all;text-overflow:initial;white-space:normal;overflow:initial;max-width:none}.label-slide .form-group:not(.exclude-from-label-slide):not(.checkbox) .unzerUI.checkbox .box,.label-slide .form-group:not(.exclude-from-label-slide):not(.checkbox) .unzerUI.checkbox label{cursor:pointer;padding-left:2.5em} diff --git a/frontend/css/unzer.min.css.map b/frontend/css/unzer.min.css.map new file mode 100644 index 0000000..faa5606 --- /dev/null +++ b/frontend/css/unzer.min.css.map @@ -0,0 +1,7 @@ +{ +"version": 3, +"mappings": "AAEI,eAAO,CACH,QAAQ,CAAE,QAAQ,CAOlB,0FAAM,CACF,QAAQ,CAAE,QAAQ,CAClB,GAAG,CAAE,OAAO,CACZ,IAAI,CAAE,OAAO,CACb,SAAS,CAAE,IAAI,CACf,MAAM,CAAE,gBAAgB,CACxB,OAAO,CAAE,CAAC,CACV,SAAS,CAAE,IAAI,CACf,WAAW,CAAE,IAAI,CACjB,cAAc,CAAE,GAAG,CACnB,aAAa,CAAE,OAAO,CACtB,WAAW,CAAE,MAAM,CACnB,QAAQ,CAAE,OAAO,CACjB,SAAS,CAAE,IAAI,CAKnB,4LAAY,CACR,MAAM,CAAE,OAAO,CACf,YAAY,CAAE,KAAK", +"sources": ["../src/scss/unzer.scss"], +"names": [], +"file": "unzer.min.css" +} diff --git a/frontend/js/unzer.js b/frontend/js/unzer.js new file mode 100644 index 0000000..aacde9d --- /dev/null +++ b/frontend/js/unzer.js @@ -0,0 +1,1321 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i Init Payment Type]', { + paymentRequest: this.applePayPaymentRequest + }); + + session.onvalidatemerchant = function (event) { + _this.merchantValidationCallback(event, session); + }; + + session.onpaymentauthorized = function (event) { + _this.applePayAuthorizedCallback(event, session); + }; + + session.oncancel = function (event) { + _this.debugging.log('[> Cancel]', { + event: event + }); + + _this.errorHandler.show(_this.snippets.CANCEL_BY_USER); + }; + + session.begin(); + } + /** + * Call the merchant validation in the server-side integration (apple_pay_merchantvalidation) + * @param {Event} event + * @param {ApplePaySession} session + */ + + }, { + key: "merchantValidationCallback", + value: function merchantValidationCallback(event, session) { + var _this2 = this; + + var validationUrl = JSON.stringify(event.validationURL); + this.debugging.log('[> Merchant Validation]', { + event: event + }); + $.ajax({ + 'url': $.evo.io().options.ioUrl, + 'method': 'POST', + 'dataType': 'json', + 'data': 'io={"name":"apple_pay_merchantvalidation", "params":[' + validationUrl + ']}' + }).done(function (validationResponse) { + _this2.debugging.log('[> Merchant Validation Response]', validationResponse); + + try { + session.completeMerchantValidation(validationResponse); + } catch (e) { + alert(e.message); + } + }).fail(function (error) { + _this2.debugging.log('[> Merchant Validation Error]', error); + + _this2.errorHandler.show(JSON.stringify(error.statusText)); + + session.abort(); + }); + } + /** + * Create Apple Pay resource with unzer and save the resource id to charge it later. + * + * We do this here via AJAX instead of the validateAdditional method in the payment method to set the apple pay + * session state accordingly. + * + * @param {Event} event + * @param {ApplePaySession} session + */ + + }, { + key: "applePayAuthorizedCallback", + value: function applePayAuthorizedCallback(event, session) { + // Get payment data from event. + // "event.payment" also contains contact information, if they were set via Apple Pay. + var self = this; + var unzerApplePayInstance = this.unzerInstance.ApplePay(); + var paymentData = event.payment.token.paymentData; + this.debugging.log('[> Payment Authorization]', { + unzerApplePayInstance: unzerApplePayInstance, + event: event, + paymentData: paymentData + }); // Create an Unzer instance with your public key + + unzerApplePayInstance.createResource(paymentData).then(function (createdResource) { + // Hand over the type ID to your backend. + var typeId = JSON.stringify(createdResource.id); + $.ajax({ + 'url': $.evo.io().options.ioUrl, + 'method': 'POST', + 'dataType': 'json', + 'data': 'io={"name":"apple_pay_payment_authorized", "params":[' + typeId + ']}' + }).done(function (result) { + // Handle the transaction respone from backend. + self.debugging.log('[> Payment Authorization Response]', { + result: result, + typeId: typeId + }); + var status = result.transactionStatus; + + if (status === 'success' || status === 'pending') { + session.completePayment({ + status: window.ApplePaySession.STATUS_SUCCESS + }); // Append Payment Resource Id + + var hiddenInput = document.createElement('input'); + hiddenInput.setAttribute('type', 'hidden'); + hiddenInput.setAttribute('name', 'paymentData[resourceId]'); + hiddenInput.setAttribute('value', typeId); + self.form.appendChild(hiddenInput); // Submitting the form + + self.form.removeEventListener('submit', self.initPaymentType); + self.form.submit(); + } else { + self.abortPaymentSession(session); + } + }).fail(function (error) { + self.errorHandler.show(error.statusText); + self.abortPaymentSession(session); + }); + })["catch"](function (error) { + self.debugging.log('[> Payment Authorization Error]', error); + self.errorHandler.show(error.message); + self.abortPaymentSession(session); + }); + } + /** + * Handle Unsupported devices + */ + + }, { + key: "unsupportedDevice", + value: function unsupportedDevice() { + this.settings.submitButton.disabled = true; + this.settings.submitButton.ariaDisabled = true; + this.errorHandler.show(this.snippets.NOT_SUPPORTED); + } + /** + * abort current payment session. + * @param {ApplePaySession} session + */ + + }, { + key: "abortPaymentSession", + value: function abortPaymentSession(session) { + this.debugging.log('[> Abort Payment Session]', { + status: window.ApplePaySession.STATUS_FAILURE + }); + session.completePayment({ + status: window.ApplePaySession.STATUS_FAILURE + }); + session.abort(); + } + }]); + return ApplePay; +}(); + +exports["default"] = ApplePay; + +},{"../utils/debugging":5,"../utils/errors":6,"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":10}],3:[function(require,module,exports){ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); + +var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); + +var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); + +var _errors = _interopRequireDefault(require("../utils/errors")); + +var UnzerPayment = /*#__PURE__*/function () { + /** + * Heidelpay Payment Class + * + * @param {string} pubKey Public Key + * @param {string} type Payment Type + * @param {PaymentSettings} settings + */ + function UnzerPayment(pubKey, type, settings) { + (0, _classCallCheck2["default"])(this, UnzerPayment); + + /** @type {PaymentSettings} */ + this.settings = settings || {}; + var options = { + locale: this.settings.locale || 'de-DE' + }; + this.unzerInstance = new unzer(pubKey, options); + this.errorHandler = new _errors["default"](this.settings.$errorContainer, this.settings.$errorMessage); + /** @type {?string} customerId */ + + this.customerId = settings.customerId || null; + /** @type {{createCustomer: Function, updateCustomer: Function}|null} customerResource */ + + this.customerResource = null; + /** @type {{createResource: Function}} paymentType */ + + this.paymentType = this.initPaymentType(type); + /** @type {HTMLElement} form Form in which the customer enters additional details */ + + this.form = this.settings.form || document.getElementById('form_payment_extra'); // Register Events + + this.handleFormSubmit = this.handleFormSubmit.bind(this); // it's a trick! needed in order to overcome the remove event listener + + this.form.addEventListener('submit', this.handleFormSubmit); + + if (this.settings.autoSubmit) { + // this.form.dispatchEvent(new Event('submit')); // Causes endless redirects in some browsers like FF, so we call the callback directly... + this.handleFormSubmit(new Event('submit')); + } + } + /** + * Init Payment Type + * + * @param {string} type + * @returns {object} payment type + * @throws Error if there is an unkown payment type + */ + + + (0, _createClass2["default"])(UnzerPayment, [{ + key: "initPaymentType", + value: function initPaymentType(type) { + switch (type) { + case UnzerPayment.PAYMENT_TYPES.CARD: + return this.createCard(); + + case UnzerPayment.PAYMENT_TYPES.INVOICE: + return this.createInvoice(); + + case UnzerPayment.PAYMENT_TYPES.INVOICE_GUARANTEED: + return this.createInvoiceGuaranteed(); + + case UnzerPayment.PAYMENT_TYPES.INVOICE_FACTORING: + return this.createInvoiceFactoring(); + + case UnzerPayment.PAYMENT_TYPES.SEPA: + return this.createSepa(); + + case UnzerPayment.PAYMENT_TYPES.SEPA_GUARANTEED: + return this.createSepaGuaranteed(); + + case UnzerPayment.PAYMENT_TYPES.PAYPAL: + return this.createPaypal(); + + case UnzerPayment.PAYMENT_TYPES.SOFORT: + return this.createSofort(); + + case UnzerPayment.PAYMENT_TYPES.GIROPAY: + return this.createGiropay(); + + case UnzerPayment.PAYMENT_TYPES.PRZELEWY24: + return this.createPrzelewy24(); + + case UnzerPayment.PAYMENT_TYPES.IDEAL: + return this.createIdeal(); + + case UnzerPayment.PAYMENT_TYPES.PREPAYMENT: + return this.createPrepayment(); + + case UnzerPayment.PAYMENT_TYPES.EPS: + return this.createEPS(); + + case UnzerPayment.PAYMENT_TYPES.FLEXIPAY_DIRECT: + return this.createFlexiPayDirect(); + + case UnzerPayment.PAYMENT_TYPES.ALIPAY: + return this.createAlipay(); + + case UnzerPayment.PAYMENT_TYPES.WECHAT_PAY: + return this.createWeChatPay(); + + case UnzerPayment.PAYMENT_TYPES.HIRE_PURCHASE: + return this.createHirePurchase(); + + case UnzerPayment.PAYMENT_TYPES.PAYLATER_INVOICE: + return this.createPaylaterInvoice(); + + case UnzerPayment.PAYMENT_TYPES.BANCONTACT: + return this.createBancontact(); + + case UnzerPayment.PAYMENT_TYPES.PAYLATER_INSTALLMENT: + return this.createPaylaterInstallment(); + + case UnzerPayment.PAYMENT_TYPES.PAYLATER_DIRECT_DEBIT: + return this.createPaylaterDirectDebit(); + + default: + throw new Error('Unkown Payment Type: ' + type); + } + } + /** + * Handle the form submit + * + * @param {Event} event Submit Event + */ + + }, { + key: "handleFormSubmit", + value: function handleFormSubmit(event) { + var self = this; + event.preventDefault(); // Creating a Payment resource and (optional) Customer Resource + + var resources = [this.paymentType.createResource()]; + + if (this.customerResource) { + resources.push(this.customerId ? this.customerResource.updateCustomer() : this.customerResource.createCustomer()); + } + + Promise.all(resources).then(function (result) { + // Append Payment Resource Id + var hiddenInput = document.createElement('input'); + hiddenInput.setAttribute('type', 'hidden'); + hiddenInput.setAttribute('name', 'paymentData[resourceId]'); + hiddenInput.setAttribute('value', result[0].id); + self.form.appendChild(hiddenInput); // Append Customer Id + + if (result.length >= 2) { + var hiddenCstInput = document.createElement('input'); + hiddenCstInput.setAttribute('type', 'hidden'); + hiddenCstInput.setAttribute('name', 'paymentData[customerId]'); + hiddenCstInput.setAttribute('value', result[1].id); + self.form.appendChild(hiddenCstInput); + } // Submitting the form + + + self.form.removeEventListener('submit', self.handleFormSubmit); + self.form.submit(); + })["catch"](function (error) { + self.errorHandler.show(error.message); + }); + } + /** + * Handle Paylater Input Validation + * @param {Event} event + * @param {boolean} isValid + * @param {String} paymentMethodName + * @param {HTMLElement} continueButton + * @returns + */ + + }, { + key: "onPaylaterInputValidation", + value: function onPaylaterInputValidation(event, isValid, paymentMethodName, continueButton) { + // console.log(paymentMethodName, { event, isValid, continueButton, 's360-valid': continueButton.getAttribute('data-s360-valid') }); + if (isValid) { + // everything is still valid + if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.removeAttribute('disabled'); + return; + } // Customer is already valid -> everything is valid + + + if (continueButton.getAttribute('data-s360-valid') == 'customer') { + continueButton.setAttribute('data-s360-valid', 'all'); + continueButton.removeAttribute('disabled'); + return; + } // mark payment method as valid + + + continueButton.setAttribute('data-s360-valid', paymentMethodName); + return; + } + + continueButton.setAttribute('disabled', true); // only invalidate if the paymentMethodName was valid before + + if (continueButton.getAttribute('data-s360-valid') == paymentMethodName) { + continueButton.setAttribute('data-s360-valid', 0); + } else if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.setAttribute('data-s360-valid', 'customer'); + } + } + /** + * Create (or update) customer resource. + * + * @param {?String} paymentTypeName + * @param {?String} multipleValidation + * @see https://docs.heidelpay.com/docs/customer-ui-integration + * @returns {{createCustomer: Function, updateCustomer: Function}} Customer Resource + */ + + }, { + key: "createCustomer", + value: function createCustomer() { + var paymentTypeName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var multipleValidation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var Customer = this.settings.isB2B ? this.unzerInstance.B2BCustomer() : this.unzerInstance.Customer(); + var customerObj = this.settings.customer || {}; + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + var options = { + containerId: 'customer', + showInfoBox: false, + showHeader: false, + fields: ['name', 'birthdate'] + }; + + if (paymentTypeName) { + options.paymentTypeName = paymentTypeName; + } + + Customer.initFormFields(customerObj); + + if (multipleValidation) { + continueButton.setAttribute('data-s360-valid', 0); + Customer.addEventListener('validate', function (e) { + // console.log('customer validate', e, continueButton, continueButton.getAttribute('data-s360-valid')); + continueButton.setAttribute('disabled', true); + + if (e.success) { + // everything is still valid + if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.removeAttribute('disabled'); + return; + } // payment method is already valid -> everything is valid + + + if (continueButton.getAttribute('data-s360-valid') == paymentTypeName) { + continueButton.setAttribute('data-s360-valid', 'all'); + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('data-s360-valid', 'customer'); + return; + } // only invalidate if the customer was valid before + + + if (continueButton.getAttribute('data-s360-valid') == 'customer') { + continueButton.setAttribute('data-s360-valid', 0); + } else if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.setAttribute('data-s360-valid', paymentTypeName); + } + }); + } else { + Customer.addEventListener('validate', function (e) { + if (e.success) { + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('disabled', true); + }); + } + + if (this.settings.isB2B) { + options.fields = ['companyInfo']; // options = {containerId: 'customer'}; + } + + if (this.customerId) { + Customer.update(this.customerId, options); + return Customer; + } + + Customer.create(options); + return Customer; + } + /** + * Hide form fields from unzer ui component because they are already filled by the shop + * @param {string} paymentMethodName + */ + + }, { + key: "hideFormFields", + value: function hideFormFields(paymentMethodName) { + var field = $('#customer'); + field.find('.field').filter('.city, .company, :has(.country), .street, .zip, .firstname, .lastname').hide(); + field.find('.salutation-customer').hide(); + field.find('.firstname, .lastname').parent('.fields').hide(); + field.find('.unzerUI.divider-horizontal:eq(0)').hide(); + field.find('.unzerUI.message.downArrow').hide(); + + if (paymentMethodName) { + field.find('.field').filter('.checkbox-billingAddress, .email').hide(); + field.find('.field').filter('.billing-name, .billing-street, .billing-zip, .billing-city, :has(.billing-country)').hide(); + field.find('.unzerUI.form>.checkboxLabel').hide(); + field.find('.unzerUI.form>.salutation-unzer-' + paymentMethodName + '-customer').hide(); + } + } + /** + * Create Paylayter Installment Payment Type + * + * @see https://docs.unzer.com/payment-methods/unzer-installment-upl/accept-unzer-installment-ui-component/ + * @returns {{createResource: Function}} + */ + + }, { + key: "createPaylaterInstallment", + value: function createPaylaterInstallment() { + var _this = this; + + this.customerResource = this.createCustomer('paylater-installment', true); + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + var paylaterInstallment = this.unzerInstance.PaylaterInstallment(); + this.hideFormFields('paylater-installment'); + paylaterInstallment.create({ + containerId: 'paylater-installment', + amount: this.settings.amount, + currency: this.settings.currency, + country: this.settings.country + }); + paylaterInstallment.addEventListener('paylaterInstallmentEvent', function (e) { + switch (e.currentStep) { + case 'plan-list': + continueButton.setAttribute('disabled', true); + break; + + case 'plan-detail': + continueButton.setAttribute('disabled', false); + break; + + default: + break; + } + + var isValid = e.action === 'validate' && e.success; + + _this.onPaylaterInputValidation(e, isValid, 'paylater-installment', continueButton); + }); + return paylaterInstallment; + } + /** + * Create Paylayter Invoice Payment Type + * + * @see https://docs.unzer.com/payment-methods/unzer-invoice-upl/accept-unzer-invoice-upl-ui-component/ + * @returns {{createResource: Function}} + */ + + }, { + key: "createPaylaterInvoice", + value: function createPaylaterInvoice() { + var _this2 = this; + + this.customerResource = this.createCustomer('paylater-invoice', true); + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + var paylaterInvoice = this.unzerInstance.PaylaterInvoice(); + this.hideFormFields('paylater-invoice'); + paylaterInvoice.create({ + containerId: 'paylater-invoice', + customerType: this.settings.isB2B ? 'B2B' : 'B2C' + }); + paylaterInvoice.addEventListener('change', function (e) { + return _this2.onPaylaterInputValidation(e, e.success, 'paylater-invoice', continueButton); + }); + return paylaterInvoice; + } + /** + * Create Paylayter Invoice Payment Type + * + * @see https://docs.unzer.com/payment-methods/direct-debit-secured/accept-direct-debit-secured-ui-component/ + * @returns {{createResource: Function}} + */ + + }, { + key: "createPaylaterDirectDebit", + value: function createPaylaterDirectDebit() { + var _this3 = this; + + this.customerResource = this.createCustomer('paylater-direct-debit', true); + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + var paylaterDirectDebit = this.unzerInstance.PaylaterDirectDebit(); + this.hideFormFields('paylater-direct-debit'); + paylaterDirectDebit.create('paylater-direct-debit', { + containerId: 'paylater-direct-debit', + customerType: this.settings.isB2B ? 'B2B' : 'B2C' + }); + paylaterDirectDebit.addEventListener('change', function (e) { + return _this3.onPaylaterInputValidation(e, e.success, 'paylater-direct-debit', continueButton); + }); + return paylaterDirectDebit; + } + /** + * Create Bancontact Payment Type + * + * @see https://docs.unzer.com/payment-methods/bancontact/accept-bancontact-ui-component/ + * @returns {{createResource: Function}} + */ + + }, { + key: "createBancontact", + value: function createBancontact() { + var bancontact = this.unzerInstance.Bancontact(); + var styling = { + fontSize: null, + fontColor: null, + fontFamily: null + }; + + if (this.settings.styling) { + styling.fontColor = this.settings.styling.fontColor || null; + styling.fontSize = this.settings.styling.fontSize || null; + styling.fontFamily = this.settings.styling.fontFamily || null; + } + + bancontact.create('holder', { + containerId: 'bancontact-holder', + fontSize: styling.fontSize, + fontColor: styling.fontColor, + fontFamily: styling.fontFamily + }); + return bancontact; + } + /** + * Create a new Card Payment Type. + * + * @see https://docs.heidelpay.com/docs/credit-card-ui-integration + * @returns {{createResource: Function}} Card Payment Type + */ + + }, { + key: "createCard", + value: function createCard() { + var Card = this.unzerInstance.Card(); + var styling = { + fontSize: null, + fontColor: null, + fontFamily: null + }; + + if (this.settings.styling) { + styling.fontColor = this.settings.styling.fontColor || null; + styling.fontSize = this.settings.styling.fontSize || null; + styling.fontFamily = this.settings.styling.fontFamily || null; + } + + Card.create('number', { + containerId: 'card-element-id-number', + onlyIframe: false, + fontSize: styling.fontSize, + fontColor: styling.fontColor, + fontFamily: styling.fontFamily + }); + Card.create('expiry', { + containerId: 'card-element-id-expiry', + onlyIframe: false, + fontSize: styling.fontSize, + fontColor: styling.fontColor, + fontFamily: styling.fontFamily + }); + Card.create('cvc', { + containerId: 'card-element-id-cvc', + onlyIframe: false, + fontSize: styling.fontSize, + fontColor: styling.fontColor // fontFamily: styling.fontFamily // messes with hidden font in firefox + + }); // Enable pay button initially + + var self = this; + var formFieldValid = {}; + /** @type {HTMLElement} continueButton */ + + var continueButton = self.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + + var eventHandlerCardInput = function eventHandlerCardInput(e) { + if (e.success) { + formFieldValid[e.type] = true; + self.errorHandler.hide(); + } + + if (e.error) { + formFieldValid[e.type] = false; + self.errorHandler.show(e.error); + } + + if (formFieldValid.number && formFieldValid.expiry && formFieldValid.cvc) { + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('disabled', true); + }; + + Card.addEventListener('change', eventHandlerCardInput); + return Card; + } + /** + * Create a new Invoice Payment Type. + * + * @see https://docs.heidelpay.com/docs/invoice-ui-integration + * @returns {{createResource: Function}} Invoice Payment Type + */ + + }, { + key: "createInvoice", + value: function createInvoice() { + return this.unzerInstance.Invoice(); + } + /** + * Create a new Invoice Guaranteed Payment Type. + * + * @see https://docs.heidelpay.com/docs/invoice-ui-integration + * @returns {{createResource: Function}} Invoice Payment Type + */ + + }, { + key: "createInvoiceGuaranteed", + value: function createInvoiceGuaranteed() { + this.customerResource = this.createCustomer(); + return this.unzerInstance.InvoiceSecured(); + } + /** + * Create a new Invoice Factoring Payment Type. + * + * @see https://docs.heidelpay.com/docs/invoice-ui-integration + * @returns {{createResource: Function}} Invoice Payment Type + */ + + }, { + key: "createInvoiceFactoring", + value: function createInvoiceFactoring() { + this.customerResource = this.createCustomer(); + return this.unzerInstance.InvoiceSecured(); + } + /** + * Create a new SEPA Direct Debit Payment Type. + * + * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration + * @returns {{createResource: Function}} SEPA Direct Debit Payment Type + */ + + }, { + key: "createSepa", + value: function createSepa() { + var _this4 = this; + + var Sepa = this.unzerInstance.SepaDirectDebit(); + Sepa.create('sepa-direct-debit', { + containerId: 'sepa-IBAN' + }); + /** @type {HTMLElement} continueButton */ + + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + Sepa.addEventListener('change', function (e) { + if (e.success) { + continueButton.removeAttribute('disabled'); + + _this4.errorHandler.hide(); + + return; + } + + continueButton.setAttribute('disabled', true); + }); + return Sepa; + } + /** + * Create a new SEPA Direct Debit (guaranteed) Payment Type. + * + * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration + * @returns {{createResource: Function}} SEPA Direct Debit (guaranteed) Payment Type + */ + + }, { + key: "createSepaGuaranteed", + value: function createSepaGuaranteed() { + var _this5 = this; + + var SepaGuaranteed = this.unzerInstance.SepaDirectDebitSecured(); + SepaGuaranteed.create('sepa-direct-debit-guaranteed', { + containerId: 'sepa-guaranteed-IBAN' + }); + /** @type {HTMLElement} continueButton */ + + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + SepaGuaranteed.addEventListener('change', function (e) { + if (e.success) { + continueButton.removeAttribute('disabled'); + + _this5.errorHandler.hide(); + + return; + } + + continueButton.setAttribute('disabled', true); + }); + this.customerResource = this.createCustomer(); + return SepaGuaranteed; + } + /** + * Create a new PayPal Payment Type. + * + * @see https://docs.heidelpay.com/docs/paypal-ui-integration + * @returns {{createResource: Function}} Papal Payment Type + */ + + }, { + key: "createPaypal", + value: function createPaypal() { + var Paypal = this.unzerInstance.Paypal(); + Paypal.create('email', { + containerId: 'paypal-element-email' + }); + return Paypal; + } + /** + * Create a new SOFORT Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#sofort + * @returns {{createResource: Function}} Sofort Payment Type + */ + + }, { + key: "createSofort", + value: function createSofort() { + return this.unzerInstance.Sofort(); + } + /** + * Create a new Giropay Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#giropay + * @returns {{createResource: Function}} Giropay Payment Type + */ + + }, { + key: "createGiropay", + value: function createGiropay() { + return this.unzerInstance.Giropay(); + } + /** + * Create a new Przelewy24 Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#przelewy24 + * @returns {{createResource: Function}} Przelewy24 Payment Type + */ + + }, { + key: "createPrzelewy24", + value: function createPrzelewy24() { + return this.unzerInstance.Przelewy24(); + } + /** + * Create a new iDEAL Payment Type. + * + * @see https://docs.heidelpay.com/docs/ideal-ui-integration + * @returns {{createResource: Function}} iDEAL Payment Type + */ + + }, { + key: "createIdeal", + value: function createIdeal() { + var _this6 = this; + + var Ideal = this.unzerInstance.Ideal(); + Ideal.create('ideal', { + containerId: 'ideal-element' + }); + /** @type {HTMLElement} continueButton */ + + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + Ideal.addEventListener('change', function (e) { + if (e.value) { + continueButton.removeAttribute('disabled'); + + _this6.errorHandler.hide(); + + return; + } + + continueButton.setAttribute('disabled', true); + }); + return Ideal; + } + /** + * Create a new Prepayment Payment Type. + * + * @see https://docs.heidelpay.com/docs/prepayment-ui-integration + * @returns {{createResource: Function}} Prepayment Payment Type + */ + + }, { + key: "createPrepayment", + value: function createPrepayment() { + return this.unzerInstance.Prepayment(); + } + /** + * Create a new EPS Payment Type. + * + * @see https://docs.heidelpay.com/docs/eps-ui-integration + * @returns {{createResource: Function}} EPS Payment Type + */ + + }, { + key: "createEPS", + value: function createEPS() { + var EPS = this.unzerInstance.EPS(); + EPS.create('eps', { + containerId: 'eps-element' + }); + return EPS; + } + /** + * Create a new FlexiPay Direct Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#flexipay-direct + * @returns {{createResource: Function}} Alipay Payment Type + */ + + }, { + key: "createFlexiPayDirect", + value: function createFlexiPayDirect() { + return this.unzerInstance.FlexiPayDirect(); + } + /** + * Create a new Alipay Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#alipay + * @returns {{createResource: Function}} Alipay Payment Type + */ + + }, { + key: "createAlipay", + value: function createAlipay() { + return this.unzerInstance.Alipay(); + } + /** + * Create an new WeChat Pay Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#wechat-pay + * @returns {{createResource: Function}} WeChat Pay Payment Type + */ + + }, { + key: "createWeChatPay", + value: function createWeChatPay() { + return this.unzerInstance.Wechatpay(); + } + /** + * Create a new Hire Purchase Payment Type. + * + * @see https:://docs.heidelpay.com/docs/hire-purchase-ui-integration + * @returns {{createResource: Function}} Hire Purchase Payment Type + */ + + }, { + key: "createHirePurchase", + value: function createHirePurchase() { + var InstallmentSecured = this.unzerInstance.InstallmentSecured(); + var self = this; + this.customerResource = this.createCustomer(); + /** @type {HTMLElement} continueButton */ + + var continueButton = self.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('style', 'display: none'); + continueButton.setAttribute('disabled', true); + InstallmentSecured.create({ + containerId: 'hire-purchase-element', + amount: this.settings.amount || null, + currency: this.settings.currency || null, + effectiveInterest: this.settings.effectiveInterest || null, + orderDate: this.settings.orderDate || null + }).then(function (data) {// if successful, notify the user that the list of installments was fetched successfully + // in case you were using a loading element during the fetching process, + // you can remove it inside this callback function + })["catch"](function (response) { + // sent an error message to the user (fetching installment list failed) + var msg = ''; + console.error(response.message); + response.error.details.forEach(function (err) { + console.error('API-Error: ' + err.code); + msg += err.customerMessage; + }); + self.errorHandler.show(msg); + }); // Listen to UI events + + InstallmentSecured.addEventListener('installmentSecuredEvent', function (e) { + if (e.action === 'validate') { + if (e.success) { + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('disabled', true); + } + + if (e.action === 'change-step') { + if (e.currentSteep === 'plan-list') { + continueButton.setAttribute('style', 'display: none'); + continueButton.setAttribute('disabled', true); + return; + } + + continueButton.setAttribute('style', 'display: inline-block'); + } + }); + return InstallmentSecured; + } + }]); + return UnzerPayment; +}(); + +exports["default"] = UnzerPayment; +(0, _defineProperty2["default"])(UnzerPayment, "PAYMENT_TYPES", { + ALIPAY: 'Alipay', + CARD: 'Card', + EPS: 'EPS', + FLEXIPAY_DIRECT: 'FlexiPay Direct', + HIRE_PURCHASE: 'Hire Purchase', + PAYPAL: 'Paypal', + INVOICE: 'Invoice', + INVOICE_FACTORING: 'Invoice Factoring', + INVOICE_GUARANTEED: 'Invoice Guaranteed', + SEPA: 'SEPA', + SEPA_GUARANTEED: 'SEPA (guaranteed)', + SOFORT: 'SOFORT', + GIROPAY: 'Giropay', + PRZELEWY24: 'Przelewy24', + IDEAL: 'iDEAL', + PREPAYMENT: 'Prepayment', + WECHAT_PAY: 'WeChat Pay', + PAYLATER_INVOICE: 'Paylater Invoice', + BANCONTACT: 'Bancontact', + PAYLATER_INSTALLMENT: 'Paylater Installment', + PAYLATER_DIRECT_DEBIT: 'Paylater Direct Debit' +}); + +},{"../utils/errors":6,"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":10}],4:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +/** + * Heidelpay Installment Modal Window Handler + * + * @param {string} modalSelector + * @param {HTMLElement} btn Submit Trigger + * @param {JQuery} $form + */ +var Installment = function Installment(modalSelector, btn, $form) { + var modal = $(modalSelector); + btn.addEventListener('click', function () { + $form.trigger('submit'); + }); + $form.on('submit', function (e) { + if (!modal.is(':visible')) { + e.preventDefault(); + modal.modal('show'); + return false; + } + + return true; + }); +}; + +var _default = Installment; +exports["default"] = _default; + +},{}],5:[function(require,module,exports){ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); + +var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); + +var Debugging = /*#__PURE__*/function () { + function Debugging($container) { + (0, _classCallCheck2["default"])(this, Debugging); + this.$container = $container; + this.$log = null; + + if (!window.UNZER_DEBUG) { + return; + } + + this.createLogTemplate(); + } + + (0, _createClass2["default"])(Debugging, [{ + key: "log", + value: function log(context) { + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!window.UNZER_DEBUG) { + return; + } + + if (!this.$log) { + this.createLogTemplate(); + } + + this.$log.append('
  • ' + context + '
    ' + JSON.stringify(data, null, '  ') + '
  • '); + } + }, { + key: "createLogTemplate", + value: function createLogTemplate() { + this.$container.append($('
      ')); + this.$log = this.$container.find('.debug-log > ul'); + } + }]); + return Debugging; +}(); + +exports["default"] = Debugging; + +},{"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":10}],6:[function(require,module,exports){ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); + +var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); + +var ErrorHandler = /*#__PURE__*/function () { + /** + * @param {JQuery|null} $wrapper Wrapper for Container to display error messages in + * @param {JQuery|null} $holder Container to display error messages in + */ + function ErrorHandler($wrapper, $holder) { + (0, _classCallCheck2["default"])(this, ErrorHandler); + this.$wrapper = $wrapper || $('#error-container'); + this.$holder = $holder || this.$wrapper.find('.alert'); + } + /** + * Show Error message + * @param {String} message + */ + + + (0, _createClass2["default"])(ErrorHandler, [{ + key: "show", + value: function show(message) { + this.$wrapper.show(); + this.$holder.html(message); + } + /** + * Hide error message + */ + + }, { + key: "hide", + value: function hide() { + this.$wrapper.hide(); + this.$holder.html(); + } + }]); + return ErrorHandler; +}(); + +exports["default"] = ErrorHandler; + +},{"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":10}],7:[function(require,module,exports){ +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],8:[function(require,module,exports){ +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; +} + +module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],9:[function(require,module,exports){ +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],10:[function(require,module,exports){ +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} + +module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}]},{},[1]) +//# sourceMappingURL=unzer.js.map diff --git a/frontend/js/unzer.js.map b/frontend/js/unzer.js.map new file mode 100644 index 0000000..9f908d8 --- /dev/null +++ b/frontend/js/unzer.js.map @@ -0,0 +1,33 @@ +{ + "version": 3, + "sources": [ + "node_modules/browser-pack/_prelude.js", + "frontend/src/js/app.js", + "frontend/src/js/payments/applepay.js", + "frontend/src/js/payments/general.js", + "frontend/src/js/payments/instalment.js", + "frontend/src/js/utils/debugging.js", + "frontend/src/js/utils/errors.js", + "node_modules/@babel/runtime/helpers/classCallCheck.js", + "node_modules/@babel/runtime/helpers/createClass.js", + "node_modules/@babel/runtime/helpers/defineProperty.js", + "node_modules/@babel/runtime/helpers/interopRequireDefault.js" + ], + "names": [], + "mappings": "AAAA;;;;;ACAA;;AACA;;AACA;;AAEA,MAAM,CAAC,SAAP,GAAmB,mBAAnB;AACA,MAAM,CAAC,YAAP,GAAsB,sBAAtB;AACA,MAAM,CAAC,aAAP,GAAuB,oBAAvB;;;;;;;;;;;;;;;;ACNA;;AACA;;AAEA;AACA,IAAM,wBAAwB,GAAG;EAC7B,aAAa,EAAE,yCADc;EAE7B,cAAc,EAAE;AAFa,CAAjC;;IAKqB,Q;EACjB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACI,kBAAY,MAAZ,EAAoB,sBAApB,EAA4C,QAA5C,EAAsD,QAAtD,EAAgE;IAAA;;IAC5D;IACA,KAAK,QAAL,GAAgB,QAAQ,IAAI,EAA5B;IAEA;;IACA,KAAK,QAAL,GAAgB,MAAM,CAAC,MAAP,CAAc,wBAAd,EAAwC,QAAxC,CAAhB;IAEA,IAAI,OAAO,GAAG;MACV,MAAM,EAAE,KAAK,QAAL,CAAc,MAAd,IAAwB;IADtB,CAAd;IAIA;;IACA,KAAK,sBAAL,GAA8B,sBAA9B;IACA,KAAK,aAAL,GAAqB,IAAI,KAAJ,CAAU,MAAV,EAAkB,OAAlB,CAArB;IACA,KAAK,YAAL,GAAoB,IAAI,kBAAJ,CAAiB,KAAK,QAAL,CAAc,eAA/B,EAAgD,KAAK,QAAL,CAAc,aAA9D,CAApB;IACA,KAAK,SAAL,GAAiB,IAAI,qBAAJ,CAAc,CAAC,CAAC,UAAD,CAAf,CAAjB;IACA,MAAM,CAAC,WAAP,GAAqB,CAAC,CAAC,KAAK,aAAL,CAAmB,UAArB,IAAmC,KAAK,aAAL,CAAmB,MAAnB,CAA0B,aAAlF,CAhB4D,CAgBqC;;IAEjG,IAAI,CAAC,MAAM,CAAC,eAAR,IAA0B,CAAC,MAAM,CAAC,eAAP,CAAuB,eAAvB,EAA/B,EAAyE;MACrE,KAAK,iBAAL;MACA;IACH;IAED;;;IACA,KAAK,IAAL,GAAY,KAAK,QAAL,CAAc,IAAd,IAAsB,QAAQ,CAAC,cAAT,CAAwB,oBAAxB,CAAlC,CAxB4D,CA0B5D;;IACA,KAAK,eAAL,GAAuB,KAAK,eAAL,CAAqB,IAArB,CAA0B,IAA1B,CAAvB,CA3B4D,CA2BJ;;IACxD,KAAK,IAAL,CAAU,gBAAV,CAA2B,QAA3B,EAAqC,KAAK,eAA1C;IACA,CAAC,CAAC,mBAAD,CAAD,CAAuB,EAAvB,CAA0B,OAA1B,EAAmC,KAAK,eAAL,CAAqB,IAArB,CAA0B,IAA1B,CAAnC;EACH;EAED;AACJ;AACA;AACA;;;;;WACI,yBAAgB,KAAhB,EAAuB;MAAA;;MACnB,KAAK,CAAC,cAAN;;MAEA,IAAI,CAAC,MAAM,CAAC,eAAR,IAA2B,CAAC,MAAM,CAAC,eAAP,CAAuB,eAAvB,EAAhC,EAA0E;QACtE,KAAK,iBAAL;QACA;MACH,CANkB,CAQnB;;;MACA,IAAM,OAAO,GAAG,IAAI,eAAJ,CAAoB,CAApB,EAAuB,KAAK,sBAA5B,CAAhB;MACA,KAAK,SAAL,CAAe,GAAf,CAAmB,uBAAnB,EAA4C;QAAC,cAAc,EAAE,KAAK;MAAtB,CAA5C;;MAEA,OAAO,CAAC,kBAAR,GAA6B,UAAC,KAAD,EAAW;QACpC,KAAI,CAAC,0BAAL,CAAgC,KAAhC,EAAuC,OAAvC;MACH,CAFD;;MAIA,OAAO,CAAC,mBAAR,GAA8B,UAAC,KAAD,EAAW;QACrC,KAAI,CAAC,0BAAL,CAAgC,KAAhC,EAAuC,OAAvC;MACH,CAFD;;MAIA,OAAO,CAAC,QAAR,GAAmB,UAAC,KAAD,EAAW;QAC1B,KAAI,CAAC,SAAL,CAAe,GAAf,CAAmB,YAAnB,EAAiC;UAAC,KAAK,EAAL;QAAD,CAAjC;;QACA,KAAI,CAAC,YAAL,CAAkB,IAAlB,CAAuB,KAAI,CAAC,QAAL,CAAc,cAArC;MACH,CAHD;;MAKA,OAAO,CAAC,KAAR;IACH;IAED;AACJ;AACA;AACA;AACA;;;;WACI,oCAA2B,KAA3B,EAAkC,OAAlC,EAA2C;MAAA;;MACvC,IAAI,aAAa,GAAG,IAAI,CAAC,SAAL,CAAe,KAAK,CAAC,aAArB,CAApB;MAEA,KAAK,SAAL,CAAe,GAAf,CAAmB,yBAAnB,EAA8C;QAAC,KAAK,EAAL;MAAD,CAA9C;MAEA,CAAC,CAAC,IAAF,CAAO;QACH,OAAO,CAAC,CAAC,GAAF,CAAM,EAAN,GAAW,OAAX,CAAmB,KADvB;QAEH,UAAU,MAFP;QAGH,YAAY,MAHT;QAIH,QAAQ,0DAA0D,aAA1D,GAA0E;MAJ/E,CAAP,EAKG,IALH,CAKQ,UAAC,kBAAD,EAAwB;QAC5B,MAAI,CAAC,SAAL,CAAe,GAAf,CAAmB,kCAAnB,EAAuD,kBAAvD;;QAEA,IAAI;UACA,OAAO,CAAC,0BAAR,CAAmC,kBAAnC;QACH,CAFD,CAEE,OAAO,CAAP,EAAU;UACR,KAAK,CAAC,CAAC,CAAC,OAAH,CAAL;QACH;MACJ,CAbD,EAcC,IAdD,CAcM,UAAC,KAAD,EAAW;QACb,MAAI,CAAC,SAAL,CAAe,GAAf,CAAmB,+BAAnB,EAAoD,KAApD;;QACA,MAAI,CAAC,YAAL,CAAkB,IAAlB,CAAuB,IAAI,CAAC,SAAL,CAAe,KAAK,CAAC,UAArB,CAAvB;;QACA,OAAO,CAAC,KAAR;MACH,CAlBD;IAmBH;IAED;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;WACI,oCAA2B,KAA3B,EAAkC,OAAlC,EAA2C;MACvC;MACA;MACA,IAAI,IAAI,GAAG,IAAX;MACA,IAAI,qBAAqB,GAAG,KAAK,aAAL,CAAmB,QAAnB,EAA5B;MACA,IAAI,WAAW,GAAG,KAAK,CAAC,OAAN,CAAc,KAAd,CAAoB,WAAtC;MAEA,KAAK,SAAL,CAAe,GAAf,CAAmB,2BAAnB,EAAgD;QAAC,qBAAqB,EAArB,qBAAD;QAAwB,KAAK,EAAL,KAAxB;QAA+B,WAAW,EAAX;MAA/B,CAAhD,EAPuC,CASvC;;MACA,qBAAqB,CAAC,cAAtB,CAAqC,WAArC,EACK,IADL,CACU,UAAU,eAAV,EAA2B;QAC7B;QACA,IAAI,MAAM,GAAG,IAAI,CAAC,SAAL,CAAe,eAAe,CAAC,EAA/B,CAAb;QACA,CAAC,CAAC,IAAF,CAAO;UACH,OAAO,CAAC,CAAC,GAAF,CAAM,EAAN,GAAW,OAAX,CAAmB,KADvB;UAEH,UAAU,MAFP;UAGH,YAAY,MAHT;UAIH,QAAQ,0DAA0D,MAA1D,GAAmE;QAJxE,CAAP,EAKG,IALH,CAKQ,UAAU,MAAV,EAAkB;UACtB;UACA,IAAI,CAAC,SAAL,CAAe,GAAf,CAAmB,oCAAnB,EAAyD;YAAC,MAAM,EAAN,MAAD;YAAS,MAAM,EAAN;UAAT,CAAzD;UACA,IAAI,MAAM,GAAG,MAAM,CAAC,iBAApB;;UACA,IAAI,MAAM,KAAK,SAAX,IAAwB,MAAM,KAAK,SAAvC,EAAkD;YAC9C,OAAO,CAAC,eAAR,CAAwB;cAAE,MAAM,EAAE,MAAM,CAAC,eAAP,CAAuB;YAAjC,CAAxB,EAD8C,CAG9C;;YACA,IAAM,WAAW,GAAG,QAAQ,CAAC,aAAT,CAAuB,OAAvB,CAApB;YACA,WAAW,CAAC,YAAZ,CAAyB,MAAzB,EAAiC,QAAjC;YACA,WAAW,CAAC,YAAZ,CAAyB,MAAzB,EAAiC,yBAAjC;YACA,WAAW,CAAC,YAAZ,CAAyB,OAAzB,EAAkC,MAAlC;YACA,IAAI,CAAC,IAAL,CAAU,WAAV,CAAsB,WAAtB,EAR8C,CAU9C;;YACA,IAAI,CAAC,IAAL,CAAU,mBAAV,CAA8B,QAA9B,EAAwC,IAAI,CAAC,eAA7C;YACA,IAAI,CAAC,IAAL,CAAU,MAAV;UACH,CAbD,MAaO;YACH,IAAI,CAAC,mBAAL,CAAyB,OAAzB;UACH;QACJ,CAzBD,EAyBG,IAzBH,CAyBQ,UAAU,KAAV,EAAiB;UACrB,IAAI,CAAC,YAAL,CAAkB,IAAlB,CAAuB,KAAK,CAAC,UAA7B;UACA,IAAI,CAAC,mBAAL,CAAyB,OAAzB;QACH,CA5BD;MA6BH,CAjCL,WAkCW,UAAU,KAAV,EAAiB;QACpB,IAAI,CAAC,SAAL,CAAe,GAAf,CAAmB,iCAAnB,EAAsD,KAAtD;QACA,IAAI,CAAC,YAAL,CAAkB,IAAlB,CAAuB,KAAK,CAAC,OAA7B;QACA,IAAI,CAAC,mBAAL,CAAyB,OAAzB;MACH,CAtCL;IAuCH;IAED;AACJ;AACA;;;;WACI,6BAAoB;MAChB,KAAK,QAAL,CAAc,YAAd,CAA2B,QAA3B,GAAsC,IAAtC;MACA,KAAK,QAAL,CAAc,YAAd,CAA2B,YAA3B,GAA0C,IAA1C;MACA,KAAK,YAAL,CAAkB,IAAlB,CAAuB,KAAK,QAAL,CAAc,aAArC;IACH;IAED;AACJ;AACA;AACA;;;;WACI,6BAAoB,OAApB,EAA6B;MACzB,KAAK,SAAL,CAAe,GAAf,CAAmB,2BAAnB,EAAgD;QAAE,MAAM,EAAE,MAAM,CAAC,eAAP,CAAuB;MAAjC,CAAhD;MACA,OAAO,CAAC,eAAR,CAAwB;QAAE,MAAM,EAAE,MAAM,CAAC,eAAP,CAAuB;MAAjC,CAAxB;MACA,OAAO,CAAC,KAAR;IACH;;;;;;;;;;;;;;;;;;;;;;;AChML;;IAEqB,Y;EAyBjB;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,sBAAY,MAAZ,EAAoB,IAApB,EAA0B,QAA1B,EAAoC;IAAA;;IAChC;IACA,KAAK,QAAL,GAAgB,QAAQ,IAAI,EAA5B;IAEA,IAAI,OAAO,GAAG;MACV,MAAM,EAAE,KAAK,QAAL,CAAc,MAAd,IAAwB;IADtB,CAAd;IAIA,KAAK,aAAL,GAAqB,IAAI,KAAJ,CAAU,MAAV,EAAkB,OAAlB,CAArB;IACA,KAAK,YAAL,GAAoB,IAAI,kBAAJ,CAAiB,KAAK,QAAL,CAAc,eAA/B,EAAgD,KAAK,QAAL,CAAc,aAA9D,CAApB;IAEA;;IACA,KAAK,UAAL,GAAkB,QAAQ,CAAC,UAAT,IAAuB,IAAzC;IAEA;;IACA,KAAK,gBAAL,GAAwB,IAAxB;IAEA;;IACA,KAAK,WAAL,GAAmB,KAAK,eAAL,CAAqB,IAArB,CAAnB;IAEA;;IACA,KAAK,IAAL,GAAY,KAAK,QAAL,CAAc,IAAd,IAAsB,QAAQ,CAAC,cAAT,CAAwB,oBAAxB,CAAlC,CArBgC,CAuBhC;;IACA,KAAK,gBAAL,GAAwB,KAAK,gBAAL,CAAsB,IAAtB,CAA2B,IAA3B,CAAxB,CAxBgC,CAwB0B;;IAC1D,KAAK,IAAL,CAAU,gBAAV,CAA2B,QAA3B,EAAqC,KAAK,gBAA1C;;IAEA,IAAI,KAAK,QAAL,CAAc,UAAlB,EAA8B;MAC1B;MACA,KAAK,gBAAL,CAAsB,IAAI,KAAJ,CAAU,QAAV,CAAtB;IACH;EACJ;EAED;AACJ;AACA;AACA;AACA;AACA;AACA;;;;;WACI,yBAAgB,IAAhB,EAAsB;MAClB,QAAQ,IAAR;QACI,KAAK,YAAY,CAAC,aAAb,CAA2B,IAAhC;UACI,OAAO,KAAK,UAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,OAAhC;UACI,OAAO,KAAK,aAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,kBAAhC;UACI,OAAO,KAAK,uBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,iBAAhC;UACI,OAAO,KAAK,sBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,IAAhC;UACI,OAAO,KAAK,UAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,eAAhC;UACI,OAAO,KAAK,oBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,MAAhC;UACI,OAAO,KAAK,YAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,MAAhC;UACI,OAAO,KAAK,YAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,OAAhC;UACI,OAAO,KAAK,aAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,UAAhC;UACI,OAAO,KAAK,gBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,KAAhC;UACI,OAAO,KAAK,WAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,UAAhC;UACI,OAAO,KAAK,gBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,GAAhC;UACI,OAAO,KAAK,SAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,eAAhC;UACI,OAAO,KAAK,oBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,MAAhC;UACI,OAAO,KAAK,YAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,UAAhC;UACI,OAAO,KAAK,eAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,aAAhC;UACI,OAAO,KAAK,kBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,gBAAhC;UACI,OAAO,KAAK,qBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,UAAhC;UACI,OAAO,KAAK,gBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,oBAAhC;UACI,OAAO,KAAK,yBAAL,EAAP;;QAEJ,KAAK,YAAY,CAAC,aAAb,CAA2B,qBAAhC;UACI,OAAO,KAAK,yBAAL,EAAP;;QAEJ;UACI,MAAM,IAAI,KAAJ,CAAU,0BAA0B,IAApC,CAAN;MAjER;IAmEH;IAED;AACJ;AACA;AACA;AACA;;;;WACI,0BAAiB,KAAjB,EAAwB;MACpB,IAAI,IAAI,GAAG,IAAX;MACA,KAAK,CAAC,cAAN,GAFoB,CAIpB;;MACA,IAAI,SAAS,GAAG,CAAC,KAAK,WAAL,CAAiB,cAAjB,EAAD,CAAhB;;MAEA,IAAI,KAAK,gBAAT,EAA2B;QACvB,SAAS,CAAC,IAAV,CAAe,KAAK,UAAL,GAAkB,KAAK,gBAAL,CAAsB,cAAtB,EAAlB,GAA2D,KAAK,gBAAL,CAAsB,cAAtB,EAA1E;MACH;;MAED,OAAO,CAAC,GAAR,CAAY,SAAZ,EAAuB,IAAvB,CAA4B,UAAU,MAAV,EAAkB;QAC1C;QACA,IAAI,WAAW,GAAG,QAAQ,CAAC,aAAT,CAAuB,OAAvB,CAAlB;QACA,WAAW,CAAC,YAAZ,CAAyB,MAAzB,EAAiC,QAAjC;QACA,WAAW,CAAC,YAAZ,CAAyB,MAAzB,EAAiC,yBAAjC;QACA,WAAW,CAAC,YAAZ,CAAyB,OAAzB,EAAkC,MAAM,CAAC,CAAD,CAAN,CAAU,EAA5C;QACA,IAAI,CAAC,IAAL,CAAU,WAAV,CAAsB,WAAtB,EAN0C,CAQ1C;;QACA,IAAI,MAAM,CAAC,MAAP,IAAiB,CAArB,EAAwB;UACpB,IAAI,cAAc,GAAG,QAAQ,CAAC,aAAT,CAAuB,OAAvB,CAArB;UACA,cAAc,CAAC,YAAf,CAA4B,MAA5B,EAAoC,QAApC;UACA,cAAc,CAAC,YAAf,CAA4B,MAA5B,EAAoC,yBAApC;UACA,cAAc,CAAC,YAAf,CAA4B,OAA5B,EAAqC,MAAM,CAAC,CAAD,CAAN,CAAU,EAA/C;UACA,IAAI,CAAC,IAAL,CAAU,WAAV,CAAsB,cAAtB;QACH,CAfyC,CAiB1C;;;QACA,IAAI,CAAC,IAAL,CAAU,mBAAV,CAA8B,QAA9B,EAAwC,IAAI,CAAC,gBAA7C;QACA,IAAI,CAAC,IAAL,CAAU,MAAV;MACH,CApBD,WAqBO,UAAU,KAAV,EAAiB;QACpB,IAAI,CAAC,YAAL,CAAkB,IAAlB,CAAuB,KAAK,CAAC,OAA7B;MACH,CAvBD;IAwBH;IAED;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;;;;WACI,mCAA0B,KAA1B,EAAiC,OAAjC,EAA0C,iBAA1C,EAA6D,cAA7D,EAA6E;MACzE;MAEA,IAAI,OAAJ,EAAa;QACT;QACA,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,KAAtD,EAA6D;UACzD,cAAc,CAAC,eAAf,CAA+B,UAA/B;UACA;QACH,CALQ,CAOT;;;QACA,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,UAAtD,EAAkE;UAC9D,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,KAA/C;UACA,cAAc,CAAC,eAAf,CAA+B,UAA/B;UACA;QACH,CAZQ,CAcT;;;QACA,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,iBAA/C;QACA;MACH;;MAED,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC,EAtByE,CAwBzE;;MACA,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,iBAAtD,EAAyE;QACrE,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,CAA/C;MACH,CAFD,MAEO,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,KAAtD,EAA6D;QAChE,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,UAA/C;MACH;IACJ;IAED;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;;;;WACI,0BAAmE;MAAA,IAApD,eAAoD,uEAAlC,IAAkC;MAAA,IAA5B,kBAA4B,uEAAP,KAAO;MAC/D,IAAI,QAAQ,GAAG,KAAK,QAAL,CAAc,KAAd,GAAsB,KAAK,aAAL,CAAmB,WAAnB,EAAtB,GAAyD,KAAK,aAAL,CAAmB,QAAnB,EAAxE;MACA,IAAI,WAAW,GAAG,KAAK,QAAL,CAAc,QAAd,IAA0B,EAA5C;MACA,IAAI,cAAc,GAAG,KAAK,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAAnD;MACA,IAAI,OAAO,GAAG;QACV,WAAW,EAAE,UADH;QAEV,WAAW,EAAE,KAFH;QAGV,UAAU,EAAE,KAHF;QAIV,MAAM,EAAE,CAAC,MAAD,EAAS,WAAT;MAJE,CAAd;;MAOA,IAAI,eAAJ,EAAqB;QACjB,OAAO,CAAC,eAAR,GAA0B,eAA1B;MACH;;MAED,QAAQ,CAAC,cAAT,CAAwB,WAAxB;;MACA,IAAI,kBAAJ,EAAwB;QACpB,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,CAA/C;QAEA,QAAQ,CAAC,gBAAT,CAA0B,UAA1B,EAAsC,UAAC,CAAD,EAAO;UACzC;UACA,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;;UAEA,IAAI,CAAC,CAAC,OAAN,EAAe;YACX;YACA,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,KAAtD,EAA6D;cACzD,cAAc,CAAC,eAAf,CAA+B,UAA/B;cACA;YACH,CALU,CAOX;;;YACA,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,eAAtD,EAAuE;cACnE,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,KAA/C;cACA,cAAc,CAAC,eAAf,CAA+B,UAA/B;cACA;YACH;;YAED,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,UAA/C;YACA;UACH,CApBwC,CAsBzC;;;UACA,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,UAAtD,EAAkE;YAC9D,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,CAA/C;UACH,CAFD,MAEO,IAAI,cAAc,CAAC,YAAf,CAA4B,iBAA5B,KAAkD,KAAtD,EAA6D;YAChE,cAAc,CAAC,YAAf,CAA4B,iBAA5B,EAA+C,eAA/C;UACH;QACJ,CA5BD;MA6BH,CAhCD,MAgCO;QACH,QAAQ,CAAC,gBAAT,CAA0B,UAA1B,EAAsC,UAAC,CAAD,EAAO;UACzC,IAAI,CAAC,CAAC,OAAN,EAAe;YACX,cAAc,CAAC,eAAf,CAA+B,UAA/B;YACA;UACH;;UAED,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;QACH,CAPD;MAQH;;MAED,IAAI,KAAK,QAAL,CAAc,KAAlB,EAAyB;QACrB,OAAO,CAAC,MAAR,GAAiB,CAAC,aAAD,CAAjB,CADqB,CAErB;MACH;;MAED,IAAI,KAAK,UAAT,EAAqB;QACjB,QAAQ,CAAC,MAAT,CAAgB,KAAK,UAArB,EAAiC,OAAjC;QACA,OAAO,QAAP;MACH;;MAED,QAAQ,CAAC,MAAT,CAAgB,OAAhB;MAEA,OAAO,QAAP;IACH;IAED;AACJ;AACA;AACA;;;;WACI,wBAAe,iBAAf,EAAkC;MAC9B,IAAM,KAAK,GAAG,CAAC,CAAC,WAAD,CAAf;MAEA,KAAK,CAAC,IAAN,CAAW,QAAX,EAAqB,MAArB,CACI,uEADJ,EAEE,IAFF;MAGA,KAAK,CAAC,IAAN,CAAW,sBAAX,EAAmC,IAAnC;MACA,KAAK,CAAC,IAAN,CAAW,uBAAX,EAAoC,MAApC,CAA2C,SAA3C,EAAsD,IAAtD;MACA,KAAK,CAAC,IAAN,CAAW,mCAAX,EAAgD,IAAhD;MACA,KAAK,CAAC,IAAN,CAAW,4BAAX,EAAyC,IAAzC;;MAEA,IAAI,iBAAJ,EAAuB;QACnB,KAAK,CAAC,IAAN,CAAW,QAAX,EAAqB,MAArB,CAA4B,kCAA5B,EAAgE,IAAhE;QACA,KAAK,CAAC,IAAN,CAAW,QAAX,EAAqB,MAArB,CACI,qFADJ,EAEE,IAFF;QAGA,KAAK,CAAC,IAAN,CAAW,8BAAX,EAA2C,IAA3C;QACA,KAAK,CAAC,IAAN,CAAW,qCAAqC,iBAArC,GAAyD,WAApE,EAAiF,IAAjF;MACH;IACJ;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,qCAA4B;MAAA;;MACxB,KAAK,gBAAL,GAAwB,KAAK,cAAL,CAAoB,sBAApB,EAA4C,IAA5C,CAAxB;MACA,IAAM,cAAc,GAAG,KAAK,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAArD;MACA,IAAM,mBAAmB,GAAG,KAAK,aAAL,CAAmB,mBAAnB,EAA5B;MAEA,KAAK,cAAL,CAAoB,sBAApB;MAEA,mBAAmB,CAAC,MAApB,CAA2B;QACvB,WAAW,EAAE,sBADU;QAEvB,MAAM,EAAE,KAAK,QAAL,CAAc,MAFC;QAGvB,QAAQ,EAAE,KAAK,QAAL,CAAc,QAHD;QAIvB,OAAO,EAAE,KAAK,QAAL,CAAc;MAJA,CAA3B;MAOA,mBAAmB,CAAC,gBAApB,CAAqC,0BAArC,EAAiE,UAAC,CAAD,EAAO;QACpE,QAAQ,CAAC,CAAC,WAAV;UACI,KAAK,WAAL;YACI,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;YACA;;UAEJ,KAAK,aAAL;YACI,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,KAAxC;YACA;;UAEJ;YACI;QAVR;;QAaA,IAAM,OAAO,GAAG,CAAC,CAAC,MAAF,KAAa,UAAb,IAA2B,CAAC,CAAC,OAA7C;;QACA,KAAI,CAAC,yBAAL,CAA+B,CAA/B,EAAkC,OAAlC,EAA2C,sBAA3C,EAAmE,cAAnE;MACH,CAhBD;MAkBA,OAAO,mBAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,iCAAwB;MAAA;;MACpB,KAAK,gBAAL,GAAwB,KAAK,cAAL,CAAoB,kBAApB,EAAwC,IAAxC,CAAxB;MACA,IAAM,cAAc,GAAG,KAAK,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAArD;MACA,IAAM,eAAe,GAAG,KAAK,aAAL,CAAmB,eAAnB,EAAxB;MAEA,KAAK,cAAL,CAAoB,kBAApB;MAEA,eAAe,CAAC,MAAhB,CAAuB;QACnB,WAAW,EAAE,kBADM;QAEnB,YAAY,EAAE,KAAK,QAAL,CAAc,KAAd,GAAsB,KAAtB,GAA8B;MAFzB,CAAvB;MAKA,eAAe,CAAC,gBAAhB,CAAiC,QAAjC,EAA2C,UAAC,CAAD;QAAA,OACvC,MAAI,CAAC,yBAAL,CACI,CADJ,EAEI,CAAC,CAAC,OAFN,EAGI,kBAHJ,EAII,cAJJ,CADuC;MAAA,CAA3C;MASA,OAAO,eAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,qCAA4B;MAAA;;MACxB,KAAK,gBAAL,GAAwB,KAAK,cAAL,CAAoB,uBAApB,EAA6C,IAA7C,CAAxB;MACA,IAAM,cAAc,GAAG,KAAK,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAArD;MACA,IAAM,mBAAmB,GAAG,KAAK,aAAL,CAAmB,mBAAnB,EAA5B;MAEA,KAAK,cAAL,CAAoB,uBAApB;MAEA,mBAAmB,CAAC,MAApB,CAA2B,uBAA3B,EAAoD;QAChD,WAAW,EAAE,uBADmC;QAEhD,YAAY,EAAE,KAAK,QAAL,CAAc,KAAd,GAAsB,KAAtB,GAA8B;MAFI,CAApD;MAKA,mBAAmB,CAAC,gBAApB,CAAqC,QAArC,EAA+C,UAAC,CAAD;QAAA,OAC3C,MAAI,CAAC,yBAAL,CACI,CADJ,EAEI,CAAC,CAAC,OAFN,EAGI,uBAHJ,EAII,cAJJ,CAD2C;MAAA,CAA/C;MASA,OAAO,mBAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,4BAAmB;MACf,IAAM,UAAU,GAAG,KAAK,aAAL,CAAmB,UAAnB,EAAnB;MACA,IAAM,OAAO,GAAG;QAAE,QAAQ,EAAE,IAAZ;QAAkB,SAAS,EAAE,IAA7B;QAAmC,UAAU,EAAE;MAA/C,CAAhB;;MAEA,IAAI,KAAK,QAAL,CAAc,OAAlB,EAA2B;QACvB,OAAO,CAAC,SAAR,GAAoB,KAAK,QAAL,CAAc,OAAd,CAAsB,SAAtB,IAAmC,IAAvD;QACA,OAAO,CAAC,QAAR,GAAmB,KAAK,QAAL,CAAc,OAAd,CAAsB,QAAtB,IAAkC,IAArD;QACA,OAAO,CAAC,UAAR,GAAqB,KAAK,QAAL,CAAc,OAAd,CAAsB,UAAtB,IAAoC,IAAzD;MACH;;MAED,UAAU,CAAC,MAAX,CAAkB,QAAlB,EAA4B;QACxB,WAAW,EAAE,mBADW;QAExB,QAAQ,EAAE,OAAO,CAAC,QAFM;QAGxB,SAAS,EAAE,OAAO,CAAC,SAHK;QAIxB,UAAU,EAAE,OAAO,CAAC;MAJI,CAA5B;MAOA,OAAO,UAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,sBAAa;MACT,IAAI,IAAI,GAAG,KAAK,aAAL,CAAmB,IAAnB,EAAX;MACA,IAAI,OAAO,GAAG;QAAC,QAAQ,EAAE,IAAX;QAAiB,SAAS,EAAE,IAA5B;QAAkC,UAAU,EAAE;MAA9C,CAAd;;MAEA,IAAI,KAAK,QAAL,CAAc,OAAlB,EAA2B;QACvB,OAAO,CAAC,SAAR,GAAoB,KAAK,QAAL,CAAc,OAAd,CAAsB,SAAtB,IAAmC,IAAvD;QACA,OAAO,CAAC,QAAR,GAAmB,KAAK,QAAL,CAAc,OAAd,CAAsB,QAAtB,IAAkC,IAArD;QACA,OAAO,CAAC,UAAR,GAAqB,KAAK,QAAL,CAAc,OAAd,CAAsB,UAAtB,IAAoC,IAAzD;MACH;;MAED,IAAI,CAAC,MAAL,CAAY,QAAZ,EAAsB;QAClB,WAAW,EAAE,wBADK;QAElB,UAAU,EAAE,KAFM;QAGlB,QAAQ,EAAE,OAAO,CAAC,QAHA;QAIlB,SAAS,EAAE,OAAO,CAAC,SAJD;QAKlB,UAAU,EAAE,OAAO,CAAC;MALF,CAAtB;MAOA,IAAI,CAAC,MAAL,CAAY,QAAZ,EAAsB;QAClB,WAAW,EAAE,wBADK;QAElB,UAAU,EAAE,KAFM;QAGlB,QAAQ,EAAE,OAAO,CAAC,QAHA;QAIlB,SAAS,EAAE,OAAO,CAAC,SAJD;QAKlB,UAAU,EAAE,OAAO,CAAC;MALF,CAAtB;MAOA,IAAI,CAAC,MAAL,CAAY,KAAZ,EAAmB;QACf,WAAW,EAAE,qBADE;QAEf,UAAU,EAAE,KAFG;QAGf,QAAQ,EAAE,OAAO,CAAC,QAHH;QAIf,SAAS,EAAE,OAAO,CAAC,SAJJ,CAKf;;MALe,CAAnB,EAxBS,CAgCT;;MACA,IAAI,IAAI,GAAG,IAAX;MACA,IAAI,cAAc,GAAG,EAArB;MAEA;;MACA,IAAI,cAAc,GAAG,IAAI,CAAC,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAAnD;MACA,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;;MAEA,IAAI,qBAAqB,GAAG,SAAxB,qBAAwB,CAAU,CAAV,EAAa;QACrC,IAAI,CAAC,CAAC,OAAN,EAAe;UACX,cAAc,CAAC,CAAC,CAAC,IAAH,CAAd,GAAyB,IAAzB;UACA,IAAI,CAAC,YAAL,CAAkB,IAAlB;QACH;;QAED,IAAI,CAAC,CAAC,KAAN,EAAa;UACT,cAAc,CAAC,CAAC,CAAC,IAAH,CAAd,GAAyB,KAAzB;UACA,IAAI,CAAC,YAAL,CAAkB,IAAlB,CAAuB,CAAC,CAAC,KAAzB;QACH;;QAED,IAAI,cAAc,CAAC,MAAf,IAAyB,cAAc,CAAC,MAAxC,IAAkD,cAAc,CAAC,GAArE,EAA0E;UACtE,cAAc,CAAC,eAAf,CAA+B,UAA/B;UACA;QACH;;QAED,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MACH,CAjBD;;MAmBA,IAAI,CAAC,gBAAL,CAAsB,QAAtB,EAAgC,qBAAhC;MAEA,OAAO,IAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,yBAAgB;MACZ,OAAO,KAAK,aAAL,CAAmB,OAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,mCAA0B;MACtB,KAAK,gBAAL,GAAwB,KAAK,cAAL,EAAxB;MAEA,OAAO,KAAK,aAAL,CAAmB,cAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,kCAAyB;MACrB,KAAK,gBAAL,GAAwB,KAAK,cAAL,EAAxB;MAEA,OAAO,KAAK,aAAL,CAAmB,cAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,sBAAa;MAAA;;MACT,IAAI,IAAI,GAAG,KAAK,aAAL,CAAmB,eAAnB,EAAX;MACA,IAAI,CAAC,MAAL,CAAY,mBAAZ,EAAiC;QAC7B,WAAW,EAAE;MADgB,CAAjC;MAIA;;MACA,IAAM,cAAc,GAAG,KAAK,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAArD;MACA,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MAEA,IAAI,CAAC,gBAAL,CAAsB,QAAtB,EAAgC,UAAC,CAAD,EAAO;QACnC,IAAI,CAAC,CAAC,OAAN,EAAe;UACX,cAAc,CAAC,eAAf,CAA+B,UAA/B;;UACA,MAAI,CAAC,YAAL,CAAkB,IAAlB;;UACA;QACH;;QAED,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MACH,CARD;MAUA,OAAO,IAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,gCAAuB;MAAA;;MACnB,IAAI,cAAc,GAAG,KAAK,aAAL,CAAmB,sBAAnB,EAArB;MACA,cAAc,CAAC,MAAf,CAAsB,8BAAtB,EAAsD;QAClD,WAAW,EAAE;MADqC,CAAtD;MAIA;;MACA,IAAM,cAAc,GAAG,KAAK,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAArD;MACA,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MAEA,cAAc,CAAC,gBAAf,CAAgC,QAAhC,EAA0C,UAAC,CAAD,EAAO;QAC7C,IAAI,CAAC,CAAC,OAAN,EAAe;UACX,cAAc,CAAC,eAAf,CAA+B,UAA/B;;UACA,MAAI,CAAC,YAAL,CAAkB,IAAlB;;UACA;QACH;;QAED,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MACH,CARD;MAUA,KAAK,gBAAL,GAAwB,KAAK,cAAL,EAAxB;MAEA,OAAO,cAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACG,wBAAe;MACV,IAAI,MAAM,GAAG,KAAK,aAAL,CAAmB,MAAnB,EAAb;MACA,MAAM,CAAC,MAAP,CAAc,OAAd,EAAuB;QACnB,WAAW,EAAE;MADM,CAAvB;MAIA,OAAO,MAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,wBAAe;MACX,OAAO,KAAK,aAAL,CAAmB,MAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,yBAAiB;MACb,OAAO,KAAK,aAAL,CAAmB,OAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,4BAAmB;MACf,OAAO,KAAK,aAAL,CAAmB,UAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,uBAAc;MAAA;;MACV,IAAI,KAAK,GAAG,KAAK,aAAL,CAAmB,KAAnB,EAAZ;MAEA,KAAK,CAAC,MAAN,CAAa,OAAb,EAAsB;QAClB,WAAW,EAAE;MADK,CAAtB;MAIA;;MACA,IAAM,cAAc,GAAG,KAAK,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAArD;MACA,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MAEA,KAAK,CAAC,gBAAN,CAAuB,QAAvB,EAAiC,UAAC,CAAD,EAAO;QACpC,IAAI,CAAC,CAAC,KAAN,EAAa;UACT,cAAc,CAAC,eAAf,CAA+B,UAA/B;;UACA,MAAI,CAAC,YAAL,CAAkB,IAAlB;;UACA;QACH;;QAED,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MACH,CARD;MAUA,OAAO,KAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,4BAAmB;MACf,OAAO,KAAK,aAAL,CAAmB,UAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,qBAAY;MACR,IAAI,GAAG,GAAG,KAAK,aAAL,CAAmB,GAAnB,EAAV;MAEA,GAAG,CAAC,MAAJ,CAAW,KAAX,EAAkB;QACd,WAAW,EAAE;MADC,CAAlB;MAIA,OAAO,GAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,gCAAuB;MACnB,OAAO,KAAK,aAAL,CAAmB,cAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,wBAAe;MACX,OAAO,KAAK,aAAL,CAAmB,MAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACI,2BAAkB;MACd,OAAO,KAAK,aAAL,CAAmB,SAAnB,EAAP;IACH;IAED;AACJ;AACA;AACA;AACA;AACA;;;;WACG,8BAAqB;MAChB,IAAI,kBAAkB,GAAG,KAAK,aAAL,CAAmB,kBAAnB,EAAzB;MACA,IAAI,IAAI,GAAG,IAAX;MACA,KAAK,gBAAL,GAAwB,KAAK,cAAL,EAAxB;MAEA;;MACA,IAAI,cAAc,GAAG,IAAI,CAAC,QAAL,CAAc,YAAd,IAA8B,QAAQ,CAAC,cAAT,CAAwB,eAAxB,CAAnD;MACA,cAAc,CAAC,YAAf,CAA4B,OAA5B,EAAqC,eAArC;MACA,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;MAEA,kBAAkB,CAAC,MAAnB,CAA0B;QACtB,WAAW,EAAE,uBADS;QAEtB,MAAM,EAAE,KAAK,QAAL,CAAc,MAAd,IAAwB,IAFV;QAGtB,QAAQ,EAAE,KAAK,QAAL,CAAc,QAAd,IAA0B,IAHd;QAItB,iBAAiB,EAAE,KAAK,QAAL,CAAc,iBAAd,IAAmC,IAJhC;QAKtB,SAAS,EAAE,KAAK,QAAL,CAAc,SAAd,IAA2B;MALhB,CAA1B,EAMG,IANH,CAMQ,UAAU,IAAV,EAAgB,CACpB;QACA;QACA;MACH,CAVD,WAWO,UAAU,QAAV,EAAoB;QACvB;QACA,IAAI,GAAG,GAAG,EAAV;QACA,OAAO,CAAC,KAAR,CAAc,QAAQ,CAAC,OAAvB;QAEA,QAAQ,CAAC,KAAT,CAAe,OAAf,CAAuB,OAAvB,CAA+B,UAAS,GAAT,EAAc;UACzC,OAAO,CAAC,KAAR,CAAc,gBAAgB,GAAG,CAAC,IAAlC;UACA,GAAG,IAAI,GAAG,CAAC,eAAX;QACH,CAHD;QAKA,IAAI,CAAC,YAAL,CAAkB,IAAlB,CAAuB,GAAvB;MACH,CAtBD,EAVgB,CAmChB;;MACA,kBAAkB,CAAC,gBAAnB,CAAoC,yBAApC,EAA+D,UAAU,CAAV,EAAa;QACxE,IAAI,CAAC,CAAC,MAAF,KAAa,UAAjB,EAA6B;UACzB,IAAI,CAAC,CAAC,OAAN,EAAe;YACX,cAAc,CAAC,eAAf,CAA+B,UAA/B;YACA;UACH;;UAED,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;QACH;;QAED,IAAI,CAAC,CAAC,MAAF,KAAa,aAAjB,EAAgC;UAC5B,IAAI,CAAC,CAAC,YAAF,KAAmB,WAAvB,EAAoC;YAChC,cAAc,CAAC,YAAf,CAA4B,OAA5B,EAAqC,eAArC;YACA,cAAc,CAAC,YAAf,CAA4B,UAA5B,EAAwC,IAAxC;YACA;UACH;;UAED,cAAc,CAAC,YAAf,CAA4B,OAA5B,EAAqC,uBAArC;QACH;MACJ,CAnBD;MAqBA,OAAO,kBAAP;IACH;;;;;;iCAjzBgB,Y,mBACM;EACnB,MAAM,EAAE,QADW;EAEnB,IAAI,EAAE,MAFa;EAGnB,GAAG,EAAE,KAHc;EAInB,eAAe,EAAE,iBAJE;EAKnB,aAAa,EAAE,eALI;EAMnB,MAAM,EAAE,QANW;EAOnB,OAAO,EAAE,SAPU;EAQnB,iBAAiB,EAAE,mBARA;EASnB,kBAAkB,EAAE,oBATD;EAUnB,IAAI,EAAE,MAVa;EAWnB,eAAe,EAAE,mBAXE;EAYnB,MAAM,EAAE,QAZW;EAanB,OAAO,EAAE,SAbU;EAcnB,UAAU,EAAE,YAdO;EAenB,KAAK,EAAE,OAfY;EAgBnB,UAAU,EAAE,YAhBO;EAiBnB,UAAU,EAAE,YAjBO;EAkBnB,gBAAgB,EAAE,kBAlBC;EAmBnB,UAAU,EAAE,YAnBO;EAoBnB,oBAAoB,EAAE,sBApBH;EAqBnB,qBAAqB,EAAE;AArBJ,C;;;;;;;;;;ACH3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAM,WAAW,GAAG,SAAd,WAAc,CAAC,aAAD,EAAgB,GAAhB,EAAqB,KAArB,EAA+B;EAC/C,IAAI,KAAK,GAAG,CAAC,CAAC,aAAD,CAAb;EAEA,GAAG,CAAC,gBAAJ,CAAqB,OAArB,EAA8B,YAAY;IACtC,KAAK,CAAC,OAAN,CAAc,QAAd;EACH,CAFD;EAIA,KAAK,CAAC,EAAN,CAAS,QAAT,EAAmB,UAAU,CAAV,EAAa;IAC5B,IAAI,CAAC,KAAK,CAAC,EAAN,CAAS,UAAT,CAAL,EAA2B;MACvB,CAAC,CAAC,cAAF;MACA,KAAK,CAAC,KAAN,CAAY,MAAZ;MACA,OAAO,KAAP;IACH;;IAED,OAAO,IAAP;EACH,CARD;AASH,CAhBD;;eAkBe,W;;;;;;;;;;;;;;;;;ICzBM,S;EACjB,mBAAY,UAAZ,EAAwB;IAAA;IACpB,KAAK,UAAL,GAAkB,UAAlB;IACA,KAAK,IAAL,GAAY,IAAZ;;IAEA,IAAI,CAAC,MAAM,CAAC,WAAZ,EAAyB;MACrB;IACH;;IAED,KAAK,iBAAL;EACH;;;;WAED,aAAI,OAAJ,EAAwB;MAAA,IAAX,IAAW,uEAAJ,EAAI;;MACpB,IAAI,CAAC,MAAM,CAAC,WAAZ,EAAyB;QACrB;MACH;;MAED,IAAI,CAAC,KAAK,IAAV,EAAgB;QACZ,KAAK,iBAAL;MACH;;MAED,KAAK,IAAL,CAAU,MAAV,CACI,iBAAiB,OAAjB,GAA2B,gBAA3B,GAA8C,IAAI,CAAC,SAAL,CAAe,IAAf,EAAsB,IAAtB,EAA4B,IAA5B,CAA9C,GAAmF,aADvF;IAGH;;;WAED,6BAAoB;MAChB,KAAK,UAAL,CAAgB,MAAhB,CACI,CAAC,CAAC,sFAAD,CADL;MAGA,KAAK,IAAL,GAAY,KAAK,UAAL,CAAgB,IAAhB,CAAqB,iBAArB,CAAZ;IACH;;;;;;;;;;;;;;;;;;;;;IC/BgB,Y;EACjB;AACJ;AACA;AACA;EACI,sBAAY,QAAZ,EAAsB,OAAtB,EAA+B;IAAA;IAC3B,KAAK,QAAL,GAAgB,QAAQ,IAAI,CAAC,CAAC,kBAAD,CAA7B;IACA,KAAK,OAAL,GAAe,OAAO,IAAI,KAAK,QAAL,CAAc,IAAd,CAAmB,QAAnB,CAA1B;EACH;EAED;AACJ;AACA;AACA;;;;;WACI,cAAK,OAAL,EAAc;MACV,KAAK,QAAL,CAAc,IAAd;MACA,KAAK,OAAL,CAAa,IAAb,CAAkB,OAAlB;IACH;IAED;AACJ;AACA;;;;WACI,gBAAO;MACH,KAAK,QAAL,CAAc,IAAd;MACA,KAAK,OAAL,CAAa,IAAb;IACH;;;;;;;;ACzBL;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA", + "file": "unzer.js", + "sourceRoot": "", + "sourcesContent": [ + "(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i Init Payment Type]', {paymentRequest: this.applePayPaymentRequest});\n\n session.onvalidatemerchant = (event) => {\n this.merchantValidationCallback(event, session);\n };\n\n session.onpaymentauthorized = (event) => {\n this.applePayAuthorizedCallback(event, session);\n };\n\n session.oncancel = (event) => {\n this.debugging.log('[> Cancel]', {event});\n this.errorHandler.show(this.snippets.CANCEL_BY_USER);\n };\n\n session.begin();\n }\n\n /**\n * Call the merchant validation in the server-side integration (apple_pay_merchantvalidation)\n * @param {Event} event\n * @param {ApplePaySession} session\n */\n merchantValidationCallback(event, session) {\n var validationUrl = JSON.stringify(event.validationURL);\n\n this.debugging.log('[> Merchant Validation]', {event});\n\n $.ajax({\n 'url': $.evo.io().options.ioUrl,\n 'method': 'POST',\n 'dataType': 'json',\n 'data': 'io={\"name\":\"apple_pay_merchantvalidation\", \"params\":[' + validationUrl + ']}',\n }).done((validationResponse) => {\n this.debugging.log('[> Merchant Validation Response]', validationResponse);\n\n try {\n session.completeMerchantValidation(validationResponse);\n } catch (e) {\n alert(e.message);\n }\n })\n .fail((error) => {\n this.debugging.log('[> Merchant Validation Error]', error);\n this.errorHandler.show(JSON.stringify(error.statusText));\n session.abort();\n });\n }\n\n /**\n * Create Apple Pay resource with unzer and save the resource id to charge it later.\n *\n * We do this here via AJAX instead of the validateAdditional method in the payment method to set the apple pay\n * session state accordingly.\n *\n * @param {Event} event\n * @param {ApplePaySession} session\n */\n applePayAuthorizedCallback(event, session) {\n // Get payment data from event.\n // \"event.payment\" also contains contact information, if they were set via Apple Pay.\n var self = this;\n var unzerApplePayInstance = this.unzerInstance.ApplePay();\n var paymentData = event.payment.token.paymentData;\n\n this.debugging.log('[> Payment Authorization]', {unzerApplePayInstance, event, paymentData});\n\n // Create an Unzer instance with your public key\n unzerApplePayInstance.createResource(paymentData)\n .then(function (createdResource) {\n // Hand over the type ID to your backend.\n var typeId = JSON.stringify(createdResource.id);\n $.ajax({\n 'url': $.evo.io().options.ioUrl,\n 'method': 'POST',\n 'dataType': 'json',\n 'data': 'io={\"name\":\"apple_pay_payment_authorized\", \"params\":[' + typeId + ']}',\n }).done(function (result) {\n // Handle the transaction respone from backend.\n self.debugging.log('[> Payment Authorization Response]', {result, typeId});\n var status = result.transactionStatus;\n if (status === 'success' || status === 'pending') {\n session.completePayment({ status: window.ApplePaySession.STATUS_SUCCESS });\n\n // Append Payment Resource Id\n const hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'paymentData[resourceId]');\n hiddenInput.setAttribute('value', typeId);\n self.form.appendChild(hiddenInput);\n\n // Submitting the form\n self.form.removeEventListener('submit', self.initPaymentType);\n self.form.submit();\n } else {\n self.abortPaymentSession(session);\n }\n }).fail(function (error) {\n self.errorHandler.show(error.statusText);\n self.abortPaymentSession(session);\n });\n })\n .catch(function (error) {\n self.debugging.log('[> Payment Authorization Error]', error);\n self.errorHandler.show(error.message);\n self.abortPaymentSession(session);\n });\n }\n\n /**\n * Handle Unsupported devices\n */\n unsupportedDevice() {\n this.settings.submitButton.disabled = true;\n this.settings.submitButton.ariaDisabled = true;\n this.errorHandler.show(this.snippets.NOT_SUPPORTED);\n }\n\n /**\n * abort current payment session.\n * @param {ApplePaySession} session\n */\n abortPaymentSession(session) {\n this.debugging.log('[> Abort Payment Session]', { status: window.ApplePaySession.STATUS_FAILURE });\n session.completePayment({ status: window.ApplePaySession.STATUS_FAILURE });\n session.abort();\n }\n}\n", + "import ErrorHandler from \"../utils/errors\";\n\nexport default class UnzerPayment {\n static PAYMENT_TYPES = {\n ALIPAY: 'Alipay',\n CARD: 'Card',\n EPS: 'EPS',\n FLEXIPAY_DIRECT: 'FlexiPay Direct',\n HIRE_PURCHASE: 'Hire Purchase',\n PAYPAL: 'Paypal',\n INVOICE: 'Invoice',\n INVOICE_FACTORING: 'Invoice Factoring',\n INVOICE_GUARANTEED: 'Invoice Guaranteed',\n SEPA: 'SEPA',\n SEPA_GUARANTEED: 'SEPA (guaranteed)',\n SOFORT: 'SOFORT',\n GIROPAY: 'Giropay',\n PRZELEWY24: 'Przelewy24',\n IDEAL: 'iDEAL',\n PREPAYMENT: 'Prepayment',\n WECHAT_PAY: 'WeChat Pay',\n PAYLATER_INVOICE: 'Paylater Invoice',\n BANCONTACT: 'Bancontact',\n PAYLATER_INSTALLMENT: 'Paylater Installment',\n PAYLATER_DIRECT_DEBIT: 'Paylater Direct Debit',\n };\n\n /**\n * Heidelpay Payment Class\n *\n * @param {string} pubKey Public Key\n * @param {string} type Payment Type\n * @param {PaymentSettings} settings\n */\n constructor(pubKey, type, settings) {\n /** @type {PaymentSettings} */\n this.settings = settings || {};\n\n var options = {\n locale: this.settings.locale || 'de-DE'\n };\n\n this.unzerInstance = new unzer(pubKey, options);\n this.errorHandler = new ErrorHandler(this.settings.$errorContainer, this.settings.$errorMessage);\n\n /** @type {?string} customerId */\n this.customerId = settings.customerId || null;\n\n /** @type {{createCustomer: Function, updateCustomer: Function}|null} customerResource */\n this.customerResource = null;\n\n /** @type {{createResource: Function}} paymentType */\n this.paymentType = this.initPaymentType(type);\n\n /** @type {HTMLElement} form Form in which the customer enters additional details */\n this.form = this.settings.form || document.getElementById('form_payment_extra');\n\n // Register Events\n this.handleFormSubmit = this.handleFormSubmit.bind(this); // it's a trick! needed in order to overcome the remove event listener\n this.form.addEventListener('submit', this.handleFormSubmit);\n\n if (this.settings.autoSubmit) {\n // this.form.dispatchEvent(new Event('submit')); // Causes endless redirects in some browsers like FF, so we call the callback directly...\n this.handleFormSubmit(new Event('submit'));\n }\n }\n\n /**\n * Init Payment Type\n *\n * @param {string} type\n * @returns {object} payment type\n * @throws Error if there is an unkown payment type\n */\n initPaymentType(type) {\n switch (type) {\n case UnzerPayment.PAYMENT_TYPES.CARD:\n return this.createCard();\n\n case UnzerPayment.PAYMENT_TYPES.INVOICE:\n return this.createInvoice();\n\n case UnzerPayment.PAYMENT_TYPES.INVOICE_GUARANTEED:\n return this.createInvoiceGuaranteed();\n\n case UnzerPayment.PAYMENT_TYPES.INVOICE_FACTORING:\n return this.createInvoiceFactoring();\n\n case UnzerPayment.PAYMENT_TYPES.SEPA:\n return this.createSepa();\n\n case UnzerPayment.PAYMENT_TYPES.SEPA_GUARANTEED:\n return this.createSepaGuaranteed();\n\n case UnzerPayment.PAYMENT_TYPES.PAYPAL:\n return this.createPaypal();\n\n case UnzerPayment.PAYMENT_TYPES.SOFORT:\n return this.createSofort();\n\n case UnzerPayment.PAYMENT_TYPES.GIROPAY:\n return this.createGiropay();\n\n case UnzerPayment.PAYMENT_TYPES.PRZELEWY24:\n return this.createPrzelewy24();\n\n case UnzerPayment.PAYMENT_TYPES.IDEAL:\n return this.createIdeal();\n\n case UnzerPayment.PAYMENT_TYPES.PREPAYMENT:\n return this.createPrepayment();\n\n case UnzerPayment.PAYMENT_TYPES.EPS:\n return this.createEPS();\n\n case UnzerPayment.PAYMENT_TYPES.FLEXIPAY_DIRECT:\n return this.createFlexiPayDirect();\n\n case UnzerPayment.PAYMENT_TYPES.ALIPAY:\n return this.createAlipay();\n\n case UnzerPayment.PAYMENT_TYPES.WECHAT_PAY:\n return this.createWeChatPay();\n\n case UnzerPayment.PAYMENT_TYPES.HIRE_PURCHASE:\n return this.createHirePurchase();\n\n case UnzerPayment.PAYMENT_TYPES.PAYLATER_INVOICE:\n return this.createPaylaterInvoice();\n\n case UnzerPayment.PAYMENT_TYPES.BANCONTACT:\n return this.createBancontact();\n\n case UnzerPayment.PAYMENT_TYPES.PAYLATER_INSTALLMENT:\n return this.createPaylaterInstallment();\n\n case UnzerPayment.PAYMENT_TYPES.PAYLATER_DIRECT_DEBIT:\n return this.createPaylaterDirectDebit();\n\n default:\n throw new Error('Unkown Payment Type: ' + type);\n }\n }\n\n /**\n * Handle the form submit\n *\n * @param {Event} event Submit Event\n */\n handleFormSubmit(event) {\n var self = this;\n event.preventDefault();\n\n // Creating a Payment resource and (optional) Customer Resource\n var resources = [this.paymentType.createResource()];\n\n if (this.customerResource) {\n resources.push(this.customerId ? this.customerResource.updateCustomer() : this.customerResource.createCustomer());\n }\n\n Promise.all(resources).then(function (result) {\n // Append Payment Resource Id\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'paymentData[resourceId]');\n hiddenInput.setAttribute('value', result[0].id);\n self.form.appendChild(hiddenInput);\n\n // Append Customer Id\n if (result.length >= 2) {\n var hiddenCstInput = document.createElement('input');\n hiddenCstInput.setAttribute('type', 'hidden');\n hiddenCstInput.setAttribute('name', 'paymentData[customerId]');\n hiddenCstInput.setAttribute('value', result[1].id);\n self.form.appendChild(hiddenCstInput);\n }\n\n // Submitting the form\n self.form.removeEventListener('submit', self.handleFormSubmit);\n self.form.submit();\n })\n .catch(function (error) {\n self.errorHandler.show(error.message);\n });\n }\n\n /**\n * Handle Paylater Input Validation\n * @param {Event} event\n * @param {boolean} isValid\n * @param {String} paymentMethodName\n * @param {HTMLElement} continueButton\n * @returns\n */\n onPaylaterInputValidation(event, isValid, paymentMethodName, continueButton) {\n // console.log(paymentMethodName, { event, isValid, continueButton, 's360-valid': continueButton.getAttribute('data-s360-valid') });\n\n if (isValid) {\n // everything is still valid\n if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n // Customer is already valid -> everything is valid\n if (continueButton.getAttribute('data-s360-valid') == 'customer') {\n continueButton.setAttribute('data-s360-valid', 'all');\n continueButton.removeAttribute('disabled');\n return;\n }\n\n // mark payment method as valid\n continueButton.setAttribute('data-s360-valid', paymentMethodName);\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n\n // only invalidate if the paymentMethodName was valid before\n if (continueButton.getAttribute('data-s360-valid') == paymentMethodName) {\n continueButton.setAttribute('data-s360-valid', 0);\n } else if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.setAttribute('data-s360-valid', 'customer');\n }\n }\n\n /**\n * Create (or update) customer resource.\n *\n * @param {?String} paymentTypeName\n * @param {?String} multipleValidation\n * @see https://docs.heidelpay.com/docs/customer-ui-integration\n * @returns {{createCustomer: Function, updateCustomer: Function}} Customer Resource\n */\n createCustomer(paymentTypeName = null, multipleValidation = false) {\n var Customer = this.settings.isB2B ? this.unzerInstance.B2BCustomer() : this.unzerInstance.Customer();\n var customerObj = this.settings.customer || {};\n var continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n let options = {\n containerId: 'customer',\n showInfoBox: false,\n showHeader: false,\n fields: ['name', 'birthdate']\n };\n\n if (paymentTypeName) {\n options.paymentTypeName = paymentTypeName;\n }\n\n Customer.initFormFields(customerObj);\n if (multipleValidation) {\n continueButton.setAttribute('data-s360-valid', 0);\n\n Customer.addEventListener('validate', (e) => {\n // console.log('customer validate', e, continueButton, continueButton.getAttribute('data-s360-valid'));\n continueButton.setAttribute('disabled', true);\n\n if (e.success) {\n // everything is still valid\n if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n // payment method is already valid -> everything is valid\n if (continueButton.getAttribute('data-s360-valid') == paymentTypeName) {\n continueButton.setAttribute('data-s360-valid', 'all');\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('data-s360-valid', 'customer');\n return;\n }\n\n // only invalidate if the customer was valid before\n if (continueButton.getAttribute('data-s360-valid') == 'customer') {\n continueButton.setAttribute('data-s360-valid', 0);\n } else if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.setAttribute('data-s360-valid', paymentTypeName);\n }\n });\n } else {\n Customer.addEventListener('validate', (e) => {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n }\n\n if (this.settings.isB2B) {\n options.fields = ['companyInfo'];\n // options = {containerId: 'customer'};\n }\n\n if (this.customerId) {\n Customer.update(this.customerId, options);\n return Customer;\n }\n\n Customer.create(options);\n\n return Customer;\n }\n\n /**\n * Hide form fields from unzer ui component because they are already filled by the shop\n * @param {string} paymentMethodName\n */\n hideFormFields(paymentMethodName) {\n const field = $('#customer');\n\n field.find('.field').filter(\n '.city, .company, :has(.country), .street, .zip, .firstname, .lastname'\n ).hide();\n field.find('.salutation-customer').hide();\n field.find('.firstname, .lastname').parent('.fields').hide();\n field.find('.unzerUI.divider-horizontal:eq(0)').hide();\n field.find('.unzerUI.message.downArrow').hide();\n\n if (paymentMethodName) {\n field.find('.field').filter('.checkbox-billingAddress, .email').hide();\n field.find('.field').filter(\n '.billing-name, .billing-street, .billing-zip, .billing-city, :has(.billing-country)'\n ).hide();\n field.find('.unzerUI.form>.checkboxLabel').hide();\n field.find('.unzerUI.form>.salutation-unzer-' + paymentMethodName + '-customer').hide();\n }\n }\n\n /**\n * Create Paylayter Installment Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/unzer-installment-upl/accept-unzer-installment-ui-component/\n * @returns {{createResource: Function}}\n */\n createPaylaterInstallment() {\n this.customerResource = this.createCustomer('paylater-installment', true);\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n const paylaterInstallment = this.unzerInstance.PaylaterInstallment();\n\n this.hideFormFields('paylater-installment');\n\n paylaterInstallment.create({\n containerId: 'paylater-installment',\n amount: this.settings.amount,\n currency: this.settings.currency,\n country: this.settings.country\n });\n\n paylaterInstallment.addEventListener('paylaterInstallmentEvent', (e) => {\n switch (e.currentStep) {\n case 'plan-list':\n continueButton.setAttribute('disabled', true);\n break;\n\n case 'plan-detail':\n continueButton.setAttribute('disabled', false);\n break;\n\n default:\n break;\n }\n\n const isValid = e.action === 'validate' && e.success;\n this.onPaylaterInputValidation(e, isValid, 'paylater-installment', continueButton);\n });\n\n return paylaterInstallment;\n }\n\n /**\n * Create Paylayter Invoice Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/unzer-invoice-upl/accept-unzer-invoice-upl-ui-component/\n * @returns {{createResource: Function}}\n */\n createPaylaterInvoice() {\n this.customerResource = this.createCustomer('paylater-invoice', true);\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n const paylaterInvoice = this.unzerInstance.PaylaterInvoice();\n\n this.hideFormFields('paylater-invoice');\n\n paylaterInvoice.create({\n containerId: 'paylater-invoice',\n customerType: this.settings.isB2B ? 'B2B' : 'B2C'\n });\n\n paylaterInvoice.addEventListener('change', (e) =>\n this.onPaylaterInputValidation(\n e,\n e.success,\n 'paylater-invoice',\n continueButton\n )\n );\n\n return paylaterInvoice;\n }\n\n /**\n * Create Paylayter Invoice Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/direct-debit-secured/accept-direct-debit-secured-ui-component/\n * @returns {{createResource: Function}}\n */\n createPaylaterDirectDebit() {\n this.customerResource = this.createCustomer('paylater-direct-debit', true);\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n const paylaterDirectDebit = this.unzerInstance.PaylaterDirectDebit();\n\n this.hideFormFields('paylater-direct-debit');\n\n paylaterDirectDebit.create('paylater-direct-debit', {\n containerId: 'paylater-direct-debit',\n customerType: this.settings.isB2B ? 'B2B' : 'B2C'\n });\n\n paylaterDirectDebit.addEventListener('change', (e) =>\n this.onPaylaterInputValidation(\n e,\n e.success,\n 'paylater-direct-debit',\n continueButton\n )\n );\n\n return paylaterDirectDebit;\n }\n\n /**\n * Create Bancontact Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/bancontact/accept-bancontact-ui-component/\n * @returns {{createResource: Function}}\n */\n createBancontact() {\n const bancontact = this.unzerInstance.Bancontact();\n const styling = { fontSize: null, fontColor: null, fontFamily: null };\n\n if (this.settings.styling) {\n styling.fontColor = this.settings.styling.fontColor || null;\n styling.fontSize = this.settings.styling.fontSize || null;\n styling.fontFamily = this.settings.styling.fontFamily || null;\n }\n\n bancontact.create('holder', {\n containerId: 'bancontact-holder',\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n fontFamily: styling.fontFamily\n });\n\n return bancontact;\n }\n\n /**\n * Create a new Card Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/credit-card-ui-integration\n * @returns {{createResource: Function}} Card Payment Type\n */\n createCard() {\n var Card = this.unzerInstance.Card();\n var styling = {fontSize: null, fontColor: null, fontFamily: null};\n\n if (this.settings.styling) {\n styling.fontColor = this.settings.styling.fontColor || null;\n styling.fontSize = this.settings.styling.fontSize || null;\n styling.fontFamily = this.settings.styling.fontFamily || null;\n }\n\n Card.create('number', {\n containerId: 'card-element-id-number',\n onlyIframe: false,\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n fontFamily: styling.fontFamily\n });\n Card.create('expiry', {\n containerId: 'card-element-id-expiry',\n onlyIframe: false,\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n fontFamily: styling.fontFamily\n });\n Card.create('cvc', {\n containerId: 'card-element-id-cvc',\n onlyIframe: false,\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n // fontFamily: styling.fontFamily // messes with hidden font in firefox\n });\n\n // Enable pay button initially\n var self = this;\n var formFieldValid = {};\n\n /** @type {HTMLElement} continueButton */\n var continueButton = self.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n var eventHandlerCardInput = function (e) {\n if (e.success) {\n formFieldValid[e.type] = true;\n self.errorHandler.hide();\n }\n\n if (e.error) {\n formFieldValid[e.type] = false;\n self.errorHandler.show(e.error);\n }\n\n if (formFieldValid.number && formFieldValid.expiry && formFieldValid.cvc) {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n };\n\n Card.addEventListener('change', eventHandlerCardInput);\n\n return Card;\n }\n\n /**\n * Create a new Invoice Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/invoice-ui-integration\n * @returns {{createResource: Function}} Invoice Payment Type\n */\n createInvoice() {\n return this.unzerInstance.Invoice();\n }\n\n /**\n * Create a new Invoice Guaranteed Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/invoice-ui-integration\n * @returns {{createResource: Function}} Invoice Payment Type\n */\n createInvoiceGuaranteed() {\n this.customerResource = this.createCustomer();\n\n return this.unzerInstance.InvoiceSecured();\n }\n\n /**\n * Create a new Invoice Factoring Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/invoice-ui-integration\n * @returns {{createResource: Function}} Invoice Payment Type\n */\n createInvoiceFactoring() {\n this.customerResource = this.createCustomer();\n\n return this.unzerInstance.InvoiceSecured();\n }\n\n /**\n * Create a new SEPA Direct Debit Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration\n * @returns {{createResource: Function}} SEPA Direct Debit Payment Type\n */\n createSepa() {\n var Sepa = this.unzerInstance.SepaDirectDebit();\n Sepa.create('sepa-direct-debit', {\n containerId: 'sepa-IBAN'\n });\n\n /** @type {HTMLElement} continueButton */\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n Sepa.addEventListener('change', (e) => {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n this.errorHandler.hide();\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n\n return Sepa;\n }\n\n /**\n * Create a new SEPA Direct Debit (guaranteed) Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration\n * @returns {{createResource: Function}} SEPA Direct Debit (guaranteed) Payment Type\n */\n createSepaGuaranteed() {\n var SepaGuaranteed = this.unzerInstance.SepaDirectDebitSecured();\n SepaGuaranteed.create('sepa-direct-debit-guaranteed', {\n containerId: 'sepa-guaranteed-IBAN'\n });\n\n /** @type {HTMLElement} continueButton */\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n SepaGuaranteed.addEventListener('change', (e) => {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n this.errorHandler.hide();\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n\n this.customerResource = this.createCustomer();\n\n return SepaGuaranteed;\n }\n\n /**\n * Create a new PayPal Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/paypal-ui-integration\n * @returns {{createResource: Function}} Papal Payment Type\n */\n createPaypal() {\n var Paypal = this.unzerInstance.Paypal();\n Paypal.create('email', {\n containerId: 'paypal-element-email'\n });\n\n return Paypal;\n }\n\n /**\n * Create a new SOFORT Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#sofort\n * @returns {{createResource: Function}} Sofort Payment Type\n */\n createSofort() {\n return this.unzerInstance.Sofort();\n }\n\n /**\n * Create a new Giropay Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#giropay\n * @returns {{createResource: Function}} Giropay Payment Type\n */\n createGiropay () {\n return this.unzerInstance.Giropay();\n }\n\n /**\n * Create a new Przelewy24 Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#przelewy24\n * @returns {{createResource: Function}} Przelewy24 Payment Type\n */\n createPrzelewy24() {\n return this.unzerInstance.Przelewy24();\n }\n\n /**\n * Create a new iDEAL Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/ideal-ui-integration\n * @returns {{createResource: Function}} iDEAL Payment Type\n */\n createIdeal() {\n var Ideal = this.unzerInstance.Ideal();\n\n Ideal.create('ideal', {\n containerId: 'ideal-element'\n });\n\n /** @type {HTMLElement} continueButton */\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n Ideal.addEventListener('change', (e) => {\n if (e.value) {\n continueButton.removeAttribute('disabled');\n this.errorHandler.hide();\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n\n return Ideal;\n }\n\n /**\n * Create a new Prepayment Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/prepayment-ui-integration\n * @returns {{createResource: Function}} Prepayment Payment Type\n */\n createPrepayment() {\n return this.unzerInstance.Prepayment();\n }\n\n /**\n * Create a new EPS Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/eps-ui-integration\n * @returns {{createResource: Function}} EPS Payment Type\n */\n createEPS() {\n var EPS = this.unzerInstance.EPS();\n\n EPS.create('eps', {\n containerId: 'eps-element'\n });\n\n return EPS;\n }\n\n /**\n * Create a new FlexiPay Direct Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#flexipay-direct\n * @returns {{createResource: Function}} Alipay Payment Type\n */\n createFlexiPayDirect() {\n return this.unzerInstance.FlexiPayDirect();\n }\n\n /**\n * Create a new Alipay Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#alipay\n * @returns {{createResource: Function}} Alipay Payment Type\n */\n createAlipay() {\n return this.unzerInstance.Alipay();\n }\n\n /**\n * Create an new WeChat Pay Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#wechat-pay\n * @returns {{createResource: Function}} WeChat Pay Payment Type\n */\n createWeChatPay() {\n return this.unzerInstance.Wechatpay();\n }\n\n /**\n * Create a new Hire Purchase Payment Type.\n *\n * @see https:://docs.heidelpay.com/docs/hire-purchase-ui-integration\n * @returns {{createResource: Function}} Hire Purchase Payment Type\n */\n createHirePurchase() {\n var InstallmentSecured = this.unzerInstance.InstallmentSecured();\n var self = this;\n this.customerResource = this.createCustomer();\n\n /** @type {HTMLElement} continueButton */\n var continueButton = self.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('style', 'display: none');\n continueButton.setAttribute('disabled', true);\n\n InstallmentSecured.create({\n containerId: 'hire-purchase-element',\n amount: this.settings.amount || null,\n currency: this.settings.currency || null,\n effectiveInterest: this.settings.effectiveInterest || null,\n orderDate: this.settings.orderDate || null\n }).then(function (data) {\n // if successful, notify the user that the list of installments was fetched successfully\n // in case you were using a loading element during the fetching process,\n // you can remove it inside this callback function\n })\n .catch(function (response) {\n // sent an error message to the user (fetching installment list failed)\n var msg = '';\n console.error(response.message);\n\n response.error.details.forEach(function(err) {\n console.error('API-Error: ' + err.code);\n msg += err.customerMessage;\n });\n\n self.errorHandler.show(msg);\n });\n\n\n // Listen to UI events\n InstallmentSecured.addEventListener('installmentSecuredEvent', function (e) {\n if (e.action === 'validate') {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n }\n\n if (e.action === 'change-step') {\n if (e.currentSteep === 'plan-list') {\n continueButton.setAttribute('style', 'display: none');\n continueButton.setAttribute('disabled', true);\n return;\n }\n\n continueButton.setAttribute('style', 'display: inline-block');\n }\n });\n\n return InstallmentSecured;\n }\n}\n", + "/**\n * Heidelpay Installment Modal Window Handler\n *\n * @param {string} modalSelector\n * @param {HTMLElement} btn Submit Trigger\n * @param {JQuery} $form\n */\nconst Installment = (modalSelector, btn, $form) => {\n var modal = $(modalSelector);\n\n btn.addEventListener('click', function () {\n $form.trigger('submit');\n });\n\n $form.on('submit', function (e) {\n if (!modal.is(':visible')) {\n e.preventDefault();\n modal.modal('show');\n return false;\n }\n\n return true;\n });\n};\n\nexport default Installment;", + "export default class Debugging {\n constructor($container) {\n this.$container = $container;\n this.$log = null;\n\n if (!window.UNZER_DEBUG) {\n return;\n }\n\n this.createLogTemplate();\n }\n\n log(context, data = {}) {\n if (!window.UNZER_DEBUG) {\n return;\n }\n\n if (!this.$log) {\n this.createLogTemplate();\n }\n\n this.$log.append(\n '
    • ' + context + '
      ' + JSON.stringify(data,  null, '  ') +  '
    • '\n );\n }\n\n createLogTemplate() {\n this.$container.append(\n $('
        ')\n );\n this.$log = this.$container.find('.debug-log > ul');\n }\n}\n", + "export default class ErrorHandler {\n /**\n * @param {JQuery|null} $wrapper Wrapper for Container to display error messages in\n * @param {JQuery|null} $holder Container to display error messages in\n */\n constructor($wrapper, $holder) {\n this.$wrapper = $wrapper || $('#error-container');\n this.$holder = $holder || this.$wrapper.find('.alert');\n }\n\n /**\n * Show Error message\n * @param {String} message\n */\n show(message) {\n this.$wrapper.show();\n this.$holder.html(message);\n }\n\n /**\n * Hide error message\n */\n hide() {\n this.$wrapper.hide();\n this.$holder.html();\n }\n}\n", + "function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", + "function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nmodule.exports = _createClass, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", + "function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", + "function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\n\nmodule.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;" + ] +} \ No newline at end of file diff --git a/frontend/js/unzer.min.js b/frontend/js/unzer.min.js new file mode 100644 index 0000000..466fd07 --- /dev/null +++ b/frontend/js/unzer.min.js @@ -0,0 +1,2 @@ +!function(){function e(t,n,r){function i(s,u){if(!n[s]){if(!t[s]){var o="function"==typeof require&&require;if(!u&&o)return o(s,!0);if(a)return a(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[s]={exports:{}};t[s][0].call(c.exports,function(e){return i(t[s][1][e]||e)},c,c.exports,e,t,n,r)}return n[s].exports}for(var a="function"==typeof require&&require,s=0;s Init Payment Type]",{paymentRequest:this.applePayPaymentRequest}),n.onvalidatemerchant=function(e){t.merchantValidationCallback(e,n)},n.onpaymentauthorized=function(e){t.applePayAuthorizedCallback(e,n)},n.oncancel=function(e){t.debugging.log("[> Cancel]",{event:e}),t.errorHandler.show(t.snippets.CANCEL_BY_USER)},n.begin()}else this.unsupportedDevice()}},{key:"merchantValidationCallback",value:function(e,t){var n=this,r=JSON.stringify(e.validationURL);this.debugging.log("[> Merchant Validation]",{event:e}),$.ajax({url:$.evo.io().options.ioUrl,method:"POST",dataType:"json",data:'io={"name":"apple_pay_merchantvalidation", "params":['+r+"]}"}).done(function(e){n.debugging.log("[> Merchant Validation Response]",e);try{t.completeMerchantValidation(e)}catch(e){alert(e.message)}}).fail(function(e){n.debugging.log("[> Merchant Validation Error]",e),n.errorHandler.show(JSON.stringify(e.statusText)),t.abort()})}},{key:"applePayAuthorizedCallback",value:function(e,t){var n=this,r=this.unzerInstance.ApplePay(),i=e.payment.token.paymentData;this.debugging.log("[> Payment Authorization]",{unzerApplePayInstance:r,event:e,paymentData:i}),r.createResource(i).then(function(e){var r=JSON.stringify(e.id);$.ajax({url:$.evo.io().options.ioUrl,method:"POST",dataType:"json",data:'io={"name":"apple_pay_payment_authorized", "params":['+r+"]}"}).done(function(e){n.debugging.log("[> Payment Authorization Response]",{result:e,typeId:r});var i=e.transactionStatus;if("success"===i||"pending"===i){t.completePayment({status:window.ApplePaySession.STATUS_SUCCESS});var a=document.createElement("input");a.setAttribute("type","hidden"),a.setAttribute("name","paymentData[resourceId]"),a.setAttribute("value",r),n.form.appendChild(a),n.form.removeEventListener("submit",n.initPaymentType),n.form.submit()}else n.abortPaymentSession(t)}).fail(function(e){n.errorHandler.show(e.statusText),n.abortPaymentSession(t)})}).catch(function(e){n.debugging.log("[> Payment Authorization Error]",e),n.errorHandler.show(e.message),n.abortPaymentSession(t)})}},{key:"unsupportedDevice",value:function(){this.settings.submitButton.disabled=!0,this.settings.submitButton.ariaDisabled=!0,this.errorHandler.show(this.snippets.NOT_SUPPORTED)}},{key:"abortPaymentSession",value:function(e){this.debugging.log("[> Abort Payment Session]",{status:window.ApplePaySession.STATUS_FAILURE}),e.completePayment({status:window.ApplePaySession.STATUS_FAILURE}),e.abort()}}]),e}();n.default=l},{"../utils/debugging":5,"../utils/errors":6,"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":10}],3:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=r(e("@babel/runtime/helpers/classCallCheck")),a=r(e("@babel/runtime/helpers/createClass")),s=r(e("@babel/runtime/helpers/defineProperty")),u=r(e("../utils/errors")),o=function(){function e(t,n,r){(0,i.default)(this,e),this.settings=r||{};var a={locale:this.settings.locale||"de-DE"};this.unzerInstance=new unzer(t,a),this.errorHandler=new u.default(this.settings.$errorContainer,this.settings.$errorMessage),this.customerId=r.customerId||null,this.customerResource=null,this.paymentType=this.initPaymentType(n),this.form=this.settings.form||document.getElementById("form_payment_extra"),this.handleFormSubmit=this.handleFormSubmit.bind(this),this.form.addEventListener("submit",this.handleFormSubmit),this.settings.autoSubmit&&this.handleFormSubmit(new Event("submit"))}return(0,a.default)(e,[{key:"initPaymentType",value:function(t){switch(t){case e.PAYMENT_TYPES.CARD:return this.createCard();case e.PAYMENT_TYPES.INVOICE:return this.createInvoice();case e.PAYMENT_TYPES.INVOICE_GUARANTEED:return this.createInvoiceGuaranteed();case e.PAYMENT_TYPES.INVOICE_FACTORING:return this.createInvoiceFactoring();case e.PAYMENT_TYPES.SEPA:return this.createSepa();case e.PAYMENT_TYPES.SEPA_GUARANTEED:return this.createSepaGuaranteed();case e.PAYMENT_TYPES.PAYPAL:return this.createPaypal();case e.PAYMENT_TYPES.SOFORT:return this.createSofort();case e.PAYMENT_TYPES.GIROPAY:return this.createGiropay();case e.PAYMENT_TYPES.PRZELEWY24:return this.createPrzelewy24();case e.PAYMENT_TYPES.IDEAL:return this.createIdeal();case e.PAYMENT_TYPES.PREPAYMENT:return this.createPrepayment();case e.PAYMENT_TYPES.EPS:return this.createEPS();case e.PAYMENT_TYPES.FLEXIPAY_DIRECT:return this.createFlexiPayDirect();case e.PAYMENT_TYPES.ALIPAY:return this.createAlipay();case e.PAYMENT_TYPES.WECHAT_PAY:return this.createWeChatPay();case e.PAYMENT_TYPES.HIRE_PURCHASE:return this.createHirePurchase();case e.PAYMENT_TYPES.PAYLATER_INVOICE:return this.createPaylaterInvoice();case e.PAYMENT_TYPES.BANCONTACT:return this.createBancontact();case e.PAYMENT_TYPES.PAYLATER_INSTALLMENT:return this.createPaylaterInstallment();case e.PAYMENT_TYPES.PAYLATER_DIRECT_DEBIT:return this.createPaylaterDirectDebit();default:throw new Error("Unkown Payment Type: "+t)}}},{key:"handleFormSubmit",value:function(e){var t=this;e.preventDefault();var n=[this.paymentType.createResource()];this.customerResource&&n.push(this.customerId?this.customerResource.updateCustomer():this.customerResource.createCustomer()),Promise.all(n).then(function(e){var n=document.createElement("input");if(n.setAttribute("type","hidden"),n.setAttribute("name","paymentData[resourceId]"),n.setAttribute("value",e[0].id),t.form.appendChild(n),e.length>=2){var r=document.createElement("input");r.setAttribute("type","hidden"),r.setAttribute("name","paymentData[customerId]"),r.setAttribute("value",e[1].id),t.form.appendChild(r)}t.form.removeEventListener("submit",t.handleFormSubmit),t.form.submit()}).catch(function(e){t.errorHandler.show(e.message)})}},{key:"onPaylaterInputValidation",value:function(e,t,n,r){if(t)return"all"==r.getAttribute("data-s360-valid")?void r.removeAttribute("disabled"):"customer"==r.getAttribute("data-s360-valid")?(r.setAttribute("data-s360-valid","all"),void r.removeAttribute("disabled")):void r.setAttribute("data-s360-valid",n);r.setAttribute("disabled",!0),r.getAttribute("data-s360-valid")==n?r.setAttribute("data-s360-valid",0):"all"==r.getAttribute("data-s360-valid")&&r.setAttribute("data-s360-valid","customer")}},{key:"createCustomer",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=this.settings.isB2B?this.unzerInstance.B2BCustomer():this.unzerInstance.Customer(),r=this.settings.customer||{},i=this.settings.submitButton||document.getElementById("submit-button"),a={containerId:"customer",showInfoBox:!1,showHeader:!1,fields:["name","birthdate"]};return e&&(a.paymentTypeName=e),n.initFormFields(r),t?(i.setAttribute("data-s360-valid",0),n.addEventListener("validate",function(t){if(i.setAttribute("disabled",!0),t.success)return"all"==i.getAttribute("data-s360-valid")?void i.removeAttribute("disabled"):i.getAttribute("data-s360-valid")==e?(i.setAttribute("data-s360-valid","all"),void i.removeAttribute("disabled")):void i.setAttribute("data-s360-valid","customer");"customer"==i.getAttribute("data-s360-valid")?i.setAttribute("data-s360-valid",0):"all"==i.getAttribute("data-s360-valid")&&i.setAttribute("data-s360-valid",e)})):n.addEventListener("validate",function(e){e.success?i.removeAttribute("disabled"):i.setAttribute("disabled",!0)}),this.settings.isB2B&&(a.fields=["companyInfo"]),this.customerId?(n.update(this.customerId,a),n):(n.create(a),n)}},{key:"hideFormFields",value:function(e){var t=$("#customer");t.find(".field").filter(".city, .company, :has(.country), .street, .zip, .firstname, .lastname").hide(),t.find(".salutation-customer").hide(),t.find(".firstname, .lastname").parent(".fields").hide(),t.find(".unzerUI.divider-horizontal:eq(0)").hide(),t.find(".unzerUI.message.downArrow").hide(),e&&(t.find(".field").filter(".checkbox-billingAddress, .email").hide(),t.find(".field").filter(".billing-name, .billing-street, .billing-zip, .billing-city, :has(.billing-country)").hide(),t.find(".unzerUI.form>.checkboxLabel").hide(),t.find(".unzerUI.form>.salutation-unzer-"+e+"-customer").hide())}},{key:"createPaylaterInstallment",value:function(){var e=this;this.customerResource=this.createCustomer("paylater-installment",!0);var t=this.settings.submitButton||document.getElementById("submit-button"),n=this.unzerInstance.PaylaterInstallment();return this.hideFormFields("paylater-installment"),n.create({containerId:"paylater-installment",amount:this.settings.amount,currency:this.settings.currency,country:this.settings.country}),n.addEventListener("paylaterInstallmentEvent",function(n){switch(n.currentStep){case"plan-list":t.setAttribute("disabled",!0);break;case"plan-detail":t.setAttribute("disabled",!1)}var r="validate"===n.action&&n.success;e.onPaylaterInputValidation(n,r,"paylater-installment",t)}),n}},{key:"createPaylaterInvoice",value:function(){var e=this;this.customerResource=this.createCustomer("paylater-invoice",!0);var t=this.settings.submitButton||document.getElementById("submit-button"),n=this.unzerInstance.PaylaterInvoice();return this.hideFormFields("paylater-invoice"),n.create({containerId:"paylater-invoice",customerType:this.settings.isB2B?"B2B":"B2C"}),n.addEventListener("change",function(n){return e.onPaylaterInputValidation(n,n.success,"paylater-invoice",t)}),n}},{key:"createPaylaterDirectDebit",value:function(){var e=this;this.customerResource=this.createCustomer("paylater-direct-debit",!0);var t=this.settings.submitButton||document.getElementById("submit-button"),n=this.unzerInstance.PaylaterDirectDebit();return this.hideFormFields("paylater-direct-debit"),n.create("paylater-direct-debit",{containerId:"paylater-direct-debit",customerType:this.settings.isB2B?"B2B":"B2C"}),n.addEventListener("change",function(n){return e.onPaylaterInputValidation(n,n.success,"paylater-direct-debit",t)}),n}},{key:"createBancontact",value:function(){var e=this.unzerInstance.Bancontact(),t={fontSize:null,fontColor:null,fontFamily:null};return this.settings.styling&&(t.fontColor=this.settings.styling.fontColor||null,t.fontSize=this.settings.styling.fontSize||null,t.fontFamily=this.settings.styling.fontFamily||null),e.create("holder",{containerId:"bancontact-holder",fontSize:t.fontSize,fontColor:t.fontColor,fontFamily:t.fontFamily}),e}},{key:"createCard",value:function(){var e=this.unzerInstance.Card(),t={fontSize:null,fontColor:null,fontFamily:null};this.settings.styling&&(t.fontColor=this.settings.styling.fontColor||null,t.fontSize=this.settings.styling.fontSize||null,t.fontFamily=this.settings.styling.fontFamily||null),e.create("number",{containerId:"card-element-id-number",onlyIframe:!1,fontSize:t.fontSize,fontColor:t.fontColor,fontFamily:t.fontFamily}),e.create("expiry",{containerId:"card-element-id-expiry",onlyIframe:!1,fontSize:t.fontSize,fontColor:t.fontColor,fontFamily:t.fontFamily}),e.create("cvc",{containerId:"card-element-id-cvc",onlyIframe:!1,fontSize:t.fontSize,fontColor:t.fontColor});var n=this,r={},i=n.settings.submitButton||document.getElementById("submit-button");i.setAttribute("disabled",!0);return e.addEventListener("change",function(e){e.success&&(r[e.type]=!0,n.errorHandler.hide()),e.error&&(r[e.type]=!1,n.errorHandler.show(e.error)),r.number&&r.expiry&&r.cvc?i.removeAttribute("disabled"):i.setAttribute("disabled",!0)}),e}},{key:"createInvoice",value:function(){return this.unzerInstance.Invoice()}},{key:"createInvoiceGuaranteed",value:function(){return this.customerResource=this.createCustomer(),this.unzerInstance.InvoiceSecured()}},{key:"createInvoiceFactoring",value:function(){return this.customerResource=this.createCustomer(),this.unzerInstance.InvoiceSecured()}},{key:"createSepa",value:function(){var e=this,t=this.unzerInstance.SepaDirectDebit();t.create("sepa-direct-debit",{containerId:"sepa-IBAN"});var n=this.settings.submitButton||document.getElementById("submit-button");return n.setAttribute("disabled",!0),t.addEventListener("change",function(t){if(t.success)return n.removeAttribute("disabled"),void e.errorHandler.hide();n.setAttribute("disabled",!0)}),t}},{key:"createSepaGuaranteed",value:function(){var e=this,t=this.unzerInstance.SepaDirectDebitSecured();t.create("sepa-direct-debit-guaranteed",{containerId:"sepa-guaranteed-IBAN"});var n=this.settings.submitButton||document.getElementById("submit-button");return n.setAttribute("disabled",!0),t.addEventListener("change",function(t){if(t.success)return n.removeAttribute("disabled"),void e.errorHandler.hide();n.setAttribute("disabled",!0)}),this.customerResource=this.createCustomer(),t}},{key:"createPaypal",value:function(){var e=this.unzerInstance.Paypal();return e.create("email",{containerId:"paypal-element-email"}),e}},{key:"createSofort",value:function(){return this.unzerInstance.Sofort()}},{key:"createGiropay",value:function(){return this.unzerInstance.Giropay()}},{key:"createPrzelewy24",value:function(){return this.unzerInstance.Przelewy24()}},{key:"createIdeal",value:function(){var e=this,t=this.unzerInstance.Ideal();t.create("ideal",{containerId:"ideal-element"});var n=this.settings.submitButton||document.getElementById("submit-button");return n.setAttribute("disabled",!0),t.addEventListener("change",function(t){if(t.value)return n.removeAttribute("disabled"),void e.errorHandler.hide();n.setAttribute("disabled",!0)}),t}},{key:"createPrepayment",value:function(){return this.unzerInstance.Prepayment()}},{key:"createEPS",value:function(){var e=this.unzerInstance.EPS();return e.create("eps",{containerId:"eps-element"}),e}},{key:"createFlexiPayDirect",value:function(){return this.unzerInstance.FlexiPayDirect()}},{key:"createAlipay",value:function(){return this.unzerInstance.Alipay()}},{key:"createWeChatPay",value:function(){return this.unzerInstance.Wechatpay()}},{key:"createHirePurchase",value:function(){var e=this.unzerInstance.InstallmentSecured(),t=this;this.customerResource=this.createCustomer();var n=t.settings.submitButton||document.getElementById("submit-button");return n.setAttribute("style","display: none"),n.setAttribute("disabled",!0),e.create({containerId:"hire-purchase-element",amount:this.settings.amount||null,currency:this.settings.currency||null,effectiveInterest:this.settings.effectiveInterest||null,orderDate:this.settings.orderDate||null}).then(function(e){}).catch(function(e){var n="";console.error(e.message),e.error.details.forEach(function(e){console.error("API-Error: "+e.code),n+=e.customerMessage}),t.errorHandler.show(n)}),e.addEventListener("installmentSecuredEvent",function(e){if("validate"===e.action){if(e.success)return void n.removeAttribute("disabled");n.setAttribute("disabled",!0)}if("change-step"===e.action){if("plan-list"===e.currentSteep)return n.setAttribute("style","display: none"),void n.setAttribute("disabled",!0);n.setAttribute("style","display: inline-block")}}),e}}]),e}();n.default=o,(0,s.default)(o,"PAYMENT_TYPES",{ALIPAY:"Alipay",CARD:"Card",EPS:"EPS",FLEXIPAY_DIRECT:"FlexiPay Direct",HIRE_PURCHASE:"Hire Purchase",PAYPAL:"Paypal",INVOICE:"Invoice",INVOICE_FACTORING:"Invoice Factoring",INVOICE_GUARANTEED:"Invoice Guaranteed",SEPA:"SEPA",SEPA_GUARANTEED:"SEPA (guaranteed)",SOFORT:"SOFORT",GIROPAY:"Giropay",PRZELEWY24:"Przelewy24",IDEAL:"iDEAL",PREPAYMENT:"Prepayment",WECHAT_PAY:"WeChat Pay",PAYLATER_INVOICE:"Paylater Invoice",BANCONTACT:"Bancontact",PAYLATER_INSTALLMENT:"Paylater Installment",PAYLATER_DIRECT_DEBIT:"Paylater Direct Debit"})},{"../utils/errors":6,"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":10}],4:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;n.default=function(e,t,n){var r=$(e);t.addEventListener("click",function(){n.trigger("submit")}),n.on("submit",function(e){return!!r.is(":visible")||(e.preventDefault(),r.modal("show"),!1)})}},{}],5:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=r(e("@babel/runtime/helpers/classCallCheck")),a=r(e("@babel/runtime/helpers/createClass")),s=function(){function e(t){(0,i.default)(this,e),this.$container=t,this.$log=null,window.UNZER_DEBUG&&this.createLogTemplate()}return(0,a.default)(e,[{key:"log",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};window.UNZER_DEBUG&&(this.$log||this.createLogTemplate(),this.$log.append("
      • "+e+"
        "+JSON.stringify(t,null,"  ")+"
      • "))}},{key:"createLogTemplate",value:function(){this.$container.append($('
          ')),this.$log=this.$container.find(".debug-log > ul")}}]),e}();n.default=s},{"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":10}],6:[function(e,t,n){"use strict";var r=e("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=r(e("@babel/runtime/helpers/classCallCheck")),a=r(e("@babel/runtime/helpers/createClass")),s=function(){function e(t,n){(0,i.default)(this,e),this.$wrapper=t||$("#error-container"),this.$holder=n||this.$wrapper.find(".alert")}return(0,a.default)(e,[{key:"show",value:function(e){this.$wrapper.show(),this.$holder.html(e)}},{key:"hide",value:function(){this.$wrapper.hide(),this.$holder.html()}}]),e}();n.default=s},{"@babel/runtime/helpers/classCallCheck":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":10}],7:[function(e,t,n){t.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.exports.__esModule=!0,t.exports.default=t.exports},{}],8:[function(e,t,n){function r(e,t){for(var n=0;n Init Payment Type]', {paymentRequest: this.applePayPaymentRequest});\n\n session.onvalidatemerchant = (event) => {\n this.merchantValidationCallback(event, session);\n };\n\n session.onpaymentauthorized = (event) => {\n this.applePayAuthorizedCallback(event, session);\n };\n\n session.oncancel = (event) => {\n this.debugging.log('[> Cancel]', {event});\n this.errorHandler.show(this.snippets.CANCEL_BY_USER);\n };\n\n session.begin();\n }\n\n /**\n * Call the merchant validation in the server-side integration (apple_pay_merchantvalidation)\n * @param {Event} event\n * @param {ApplePaySession} session\n */\n merchantValidationCallback(event, session) {\n var validationUrl = JSON.stringify(event.validationURL);\n\n this.debugging.log('[> Merchant Validation]', {event});\n\n $.ajax({\n 'url': $.evo.io().options.ioUrl,\n 'method': 'POST',\n 'dataType': 'json',\n 'data': 'io={\"name\":\"apple_pay_merchantvalidation\", \"params\":[' + validationUrl + ']}',\n }).done((validationResponse) => {\n this.debugging.log('[> Merchant Validation Response]', validationResponse);\n\n try {\n session.completeMerchantValidation(validationResponse);\n } catch (e) {\n alert(e.message);\n }\n })\n .fail((error) => {\n this.debugging.log('[> Merchant Validation Error]', error);\n this.errorHandler.show(JSON.stringify(error.statusText));\n session.abort();\n });\n }\n\n /**\n * Create Apple Pay resource with unzer and save the resource id to charge it later.\n *\n * We do this here via AJAX instead of the validateAdditional method in the payment method to set the apple pay\n * session state accordingly.\n *\n * @param {Event} event\n * @param {ApplePaySession} session\n */\n applePayAuthorizedCallback(event, session) {\n // Get payment data from event.\n // \"event.payment\" also contains contact information, if they were set via Apple Pay.\n var self = this;\n var unzerApplePayInstance = this.unzerInstance.ApplePay();\n var paymentData = event.payment.token.paymentData;\n\n this.debugging.log('[> Payment Authorization]', {unzerApplePayInstance, event, paymentData});\n\n // Create an Unzer instance with your public key\n unzerApplePayInstance.createResource(paymentData)\n .then(function (createdResource) {\n // Hand over the type ID to your backend.\n var typeId = JSON.stringify(createdResource.id);\n $.ajax({\n 'url': $.evo.io().options.ioUrl,\n 'method': 'POST',\n 'dataType': 'json',\n 'data': 'io={\"name\":\"apple_pay_payment_authorized\", \"params\":[' + typeId + ']}',\n }).done(function (result) {\n // Handle the transaction respone from backend.\n self.debugging.log('[> Payment Authorization Response]', {result, typeId});\n var status = result.transactionStatus;\n if (status === 'success' || status === 'pending') {\n session.completePayment({ status: window.ApplePaySession.STATUS_SUCCESS });\n\n // Append Payment Resource Id\n const hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'paymentData[resourceId]');\n hiddenInput.setAttribute('value', typeId);\n self.form.appendChild(hiddenInput);\n\n // Submitting the form\n self.form.removeEventListener('submit', self.initPaymentType);\n self.form.submit();\n } else {\n self.abortPaymentSession(session);\n }\n }).fail(function (error) {\n self.errorHandler.show(error.statusText);\n self.abortPaymentSession(session);\n });\n })\n .catch(function (error) {\n self.debugging.log('[> Payment Authorization Error]', error);\n self.errorHandler.show(error.message);\n self.abortPaymentSession(session);\n });\n }\n\n /**\n * Handle Unsupported devices\n */\n unsupportedDevice() {\n this.settings.submitButton.disabled = true;\n this.settings.submitButton.ariaDisabled = true;\n this.errorHandler.show(this.snippets.NOT_SUPPORTED);\n }\n\n /**\n * abort current payment session.\n * @param {ApplePaySession} session\n */\n abortPaymentSession(session) {\n this.debugging.log('[> Abort Payment Session]', { status: window.ApplePaySession.STATUS_FAILURE });\n session.completePayment({ status: window.ApplePaySession.STATUS_FAILURE });\n session.abort();\n }\n}\n","import ErrorHandler from \"../utils/errors\";\n\nexport default class UnzerPayment {\n static PAYMENT_TYPES = {\n ALIPAY: 'Alipay',\n CARD: 'Card',\n EPS: 'EPS',\n FLEXIPAY_DIRECT: 'FlexiPay Direct',\n HIRE_PURCHASE: 'Hire Purchase',\n PAYPAL: 'Paypal',\n INVOICE: 'Invoice',\n INVOICE_FACTORING: 'Invoice Factoring',\n INVOICE_GUARANTEED: 'Invoice Guaranteed',\n SEPA: 'SEPA',\n SEPA_GUARANTEED: 'SEPA (guaranteed)',\n SOFORT: 'SOFORT',\n GIROPAY: 'Giropay',\n PRZELEWY24: 'Przelewy24',\n IDEAL: 'iDEAL',\n PREPAYMENT: 'Prepayment',\n WECHAT_PAY: 'WeChat Pay',\n PAYLATER_INVOICE: 'Paylater Invoice',\n BANCONTACT: 'Bancontact',\n PAYLATER_INSTALLMENT: 'Paylater Installment',\n PAYLATER_DIRECT_DEBIT: 'Paylater Direct Debit',\n };\n\n /**\n * Heidelpay Payment Class\n *\n * @param {string} pubKey Public Key\n * @param {string} type Payment Type\n * @param {PaymentSettings} settings\n */\n constructor(pubKey, type, settings) {\n /** @type {PaymentSettings} */\n this.settings = settings || {};\n\n var options = {\n locale: this.settings.locale || 'de-DE'\n };\n\n this.unzerInstance = new unzer(pubKey, options);\n this.errorHandler = new ErrorHandler(this.settings.$errorContainer, this.settings.$errorMessage);\n\n /** @type {?string} customerId */\n this.customerId = settings.customerId || null;\n\n /** @type {{createCustomer: Function, updateCustomer: Function}|null} customerResource */\n this.customerResource = null;\n\n /** @type {{createResource: Function}} paymentType */\n this.paymentType = this.initPaymentType(type);\n\n /** @type {HTMLElement} form Form in which the customer enters additional details */\n this.form = this.settings.form || document.getElementById('form_payment_extra');\n\n // Register Events\n this.handleFormSubmit = this.handleFormSubmit.bind(this); // it's a trick! needed in order to overcome the remove event listener\n this.form.addEventListener('submit', this.handleFormSubmit);\n\n if (this.settings.autoSubmit) {\n // this.form.dispatchEvent(new Event('submit')); // Causes endless redirects in some browsers like FF, so we call the callback directly...\n this.handleFormSubmit(new Event('submit'));\n }\n }\n\n /**\n * Init Payment Type\n *\n * @param {string} type\n * @returns {object} payment type\n * @throws Error if there is an unkown payment type\n */\n initPaymentType(type) {\n switch (type) {\n case UnzerPayment.PAYMENT_TYPES.CARD:\n return this.createCard();\n\n case UnzerPayment.PAYMENT_TYPES.INVOICE:\n return this.createInvoice();\n\n case UnzerPayment.PAYMENT_TYPES.INVOICE_GUARANTEED:\n return this.createInvoiceGuaranteed();\n\n case UnzerPayment.PAYMENT_TYPES.INVOICE_FACTORING:\n return this.createInvoiceFactoring();\n\n case UnzerPayment.PAYMENT_TYPES.SEPA:\n return this.createSepa();\n\n case UnzerPayment.PAYMENT_TYPES.SEPA_GUARANTEED:\n return this.createSepaGuaranteed();\n\n case UnzerPayment.PAYMENT_TYPES.PAYPAL:\n return this.createPaypal();\n\n case UnzerPayment.PAYMENT_TYPES.SOFORT:\n return this.createSofort();\n\n case UnzerPayment.PAYMENT_TYPES.GIROPAY:\n return this.createGiropay();\n\n case UnzerPayment.PAYMENT_TYPES.PRZELEWY24:\n return this.createPrzelewy24();\n\n case UnzerPayment.PAYMENT_TYPES.IDEAL:\n return this.createIdeal();\n\n case UnzerPayment.PAYMENT_TYPES.PREPAYMENT:\n return this.createPrepayment();\n\n case UnzerPayment.PAYMENT_TYPES.EPS:\n return this.createEPS();\n\n case UnzerPayment.PAYMENT_TYPES.FLEXIPAY_DIRECT:\n return this.createFlexiPayDirect();\n\n case UnzerPayment.PAYMENT_TYPES.ALIPAY:\n return this.createAlipay();\n\n case UnzerPayment.PAYMENT_TYPES.WECHAT_PAY:\n return this.createWeChatPay();\n\n case UnzerPayment.PAYMENT_TYPES.HIRE_PURCHASE:\n return this.createHirePurchase();\n\n case UnzerPayment.PAYMENT_TYPES.PAYLATER_INVOICE:\n return this.createPaylaterInvoice();\n\n case UnzerPayment.PAYMENT_TYPES.BANCONTACT:\n return this.createBancontact();\n\n case UnzerPayment.PAYMENT_TYPES.PAYLATER_INSTALLMENT:\n return this.createPaylaterInstallment();\n\n case UnzerPayment.PAYMENT_TYPES.PAYLATER_DIRECT_DEBIT:\n return this.createPaylaterDirectDebit();\n\n default:\n throw new Error('Unkown Payment Type: ' + type);\n }\n }\n\n /**\n * Handle the form submit\n *\n * @param {Event} event Submit Event\n */\n handleFormSubmit(event) {\n var self = this;\n event.preventDefault();\n\n // Creating a Payment resource and (optional) Customer Resource\n var resources = [this.paymentType.createResource()];\n\n if (this.customerResource) {\n resources.push(this.customerId ? this.customerResource.updateCustomer() : this.customerResource.createCustomer());\n }\n\n Promise.all(resources).then(function (result) {\n // Append Payment Resource Id\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'paymentData[resourceId]');\n hiddenInput.setAttribute('value', result[0].id);\n self.form.appendChild(hiddenInput);\n\n // Append Customer Id\n if (result.length >= 2) {\n var hiddenCstInput = document.createElement('input');\n hiddenCstInput.setAttribute('type', 'hidden');\n hiddenCstInput.setAttribute('name', 'paymentData[customerId]');\n hiddenCstInput.setAttribute('value', result[1].id);\n self.form.appendChild(hiddenCstInput);\n }\n\n // Submitting the form\n self.form.removeEventListener('submit', self.handleFormSubmit);\n self.form.submit();\n })\n .catch(function (error) {\n self.errorHandler.show(error.message);\n });\n }\n\n /**\n * Handle Paylater Input Validation\n * @param {Event} event\n * @param {boolean} isValid\n * @param {String} paymentMethodName\n * @param {HTMLElement} continueButton\n * @returns\n */\n onPaylaterInputValidation(event, isValid, paymentMethodName, continueButton) {\n // console.log(paymentMethodName, { event, isValid, continueButton, 's360-valid': continueButton.getAttribute('data-s360-valid') });\n\n if (isValid) {\n // everything is still valid\n if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n // Customer is already valid -> everything is valid\n if (continueButton.getAttribute('data-s360-valid') == 'customer') {\n continueButton.setAttribute('data-s360-valid', 'all');\n continueButton.removeAttribute('disabled');\n return;\n }\n\n // mark payment method as valid\n continueButton.setAttribute('data-s360-valid', paymentMethodName);\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n\n // only invalidate if the paymentMethodName was valid before\n if (continueButton.getAttribute('data-s360-valid') == paymentMethodName) {\n continueButton.setAttribute('data-s360-valid', 0);\n } else if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.setAttribute('data-s360-valid', 'customer');\n }\n }\n\n /**\n * Create (or update) customer resource.\n *\n * @param {?String} paymentTypeName\n * @param {?String} multipleValidation\n * @see https://docs.heidelpay.com/docs/customer-ui-integration\n * @returns {{createCustomer: Function, updateCustomer: Function}} Customer Resource\n */\n createCustomer(paymentTypeName = null, multipleValidation = false) {\n var Customer = this.settings.isB2B ? this.unzerInstance.B2BCustomer() : this.unzerInstance.Customer();\n var customerObj = this.settings.customer || {};\n var continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n let options = {\n containerId: 'customer',\n showInfoBox: false,\n showHeader: false,\n fields: ['name', 'birthdate']\n };\n\n if (paymentTypeName) {\n options.paymentTypeName = paymentTypeName;\n }\n\n Customer.initFormFields(customerObj);\n if (multipleValidation) {\n continueButton.setAttribute('data-s360-valid', 0);\n\n Customer.addEventListener('validate', (e) => {\n // console.log('customer validate', e, continueButton, continueButton.getAttribute('data-s360-valid'));\n continueButton.setAttribute('disabled', true);\n\n if (e.success) {\n // everything is still valid\n if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n // payment method is already valid -> everything is valid\n if (continueButton.getAttribute('data-s360-valid') == paymentTypeName) {\n continueButton.setAttribute('data-s360-valid', 'all');\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('data-s360-valid', 'customer');\n return;\n }\n\n // only invalidate if the customer was valid before\n if (continueButton.getAttribute('data-s360-valid') == 'customer') {\n continueButton.setAttribute('data-s360-valid', 0);\n } else if (continueButton.getAttribute('data-s360-valid') == 'all') {\n continueButton.setAttribute('data-s360-valid', paymentTypeName);\n }\n });\n } else {\n Customer.addEventListener('validate', (e) => {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n }\n\n if (this.settings.isB2B) {\n options.fields = ['companyInfo'];\n // options = {containerId: 'customer'};\n }\n\n if (this.customerId) {\n Customer.update(this.customerId, options);\n return Customer;\n }\n\n Customer.create(options);\n\n return Customer;\n }\n\n /**\n * Hide form fields from unzer ui component because they are already filled by the shop\n * @param {string} paymentMethodName\n */\n hideFormFields(paymentMethodName) {\n const field = $('#customer');\n\n field.find('.field').filter(\n '.city, .company, :has(.country), .street, .zip, .firstname, .lastname'\n ).hide();\n field.find('.salutation-customer').hide();\n field.find('.firstname, .lastname').parent('.fields').hide();\n field.find('.unzerUI.divider-horizontal:eq(0)').hide();\n field.find('.unzerUI.message.downArrow').hide();\n\n if (paymentMethodName) {\n field.find('.field').filter('.checkbox-billingAddress, .email').hide();\n field.find('.field').filter(\n '.billing-name, .billing-street, .billing-zip, .billing-city, :has(.billing-country)'\n ).hide();\n field.find('.unzerUI.form>.checkboxLabel').hide();\n field.find('.unzerUI.form>.salutation-unzer-' + paymentMethodName + '-customer').hide();\n }\n }\n\n /**\n * Create Paylayter Installment Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/unzer-installment-upl/accept-unzer-installment-ui-component/\n * @returns {{createResource: Function}}\n */\n createPaylaterInstallment() {\n this.customerResource = this.createCustomer('paylater-installment', true);\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n const paylaterInstallment = this.unzerInstance.PaylaterInstallment();\n\n this.hideFormFields('paylater-installment');\n\n paylaterInstallment.create({\n containerId: 'paylater-installment',\n amount: this.settings.amount,\n currency: this.settings.currency,\n country: this.settings.country\n });\n\n paylaterInstallment.addEventListener('paylaterInstallmentEvent', (e) => {\n switch (e.currentStep) {\n case 'plan-list':\n continueButton.setAttribute('disabled', true);\n break;\n\n case 'plan-detail':\n continueButton.setAttribute('disabled', false);\n break;\n\n default:\n break;\n }\n\n const isValid = e.action === 'validate' && e.success;\n this.onPaylaterInputValidation(e, isValid, 'paylater-installment', continueButton);\n });\n\n return paylaterInstallment;\n }\n\n /**\n * Create Paylayter Invoice Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/unzer-invoice-upl/accept-unzer-invoice-upl-ui-component/\n * @returns {{createResource: Function}}\n */\n createPaylaterInvoice() {\n this.customerResource = this.createCustomer('paylater-invoice', true);\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n const paylaterInvoice = this.unzerInstance.PaylaterInvoice();\n\n this.hideFormFields('paylater-invoice');\n\n paylaterInvoice.create({\n containerId: 'paylater-invoice',\n customerType: this.settings.isB2B ? 'B2B' : 'B2C'\n });\n\n paylaterInvoice.addEventListener('change', (e) =>\n this.onPaylaterInputValidation(\n e,\n e.success,\n 'paylater-invoice',\n continueButton\n )\n );\n\n return paylaterInvoice;\n }\n\n /**\n * Create Paylayter Invoice Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/direct-debit-secured/accept-direct-debit-secured-ui-component/\n * @returns {{createResource: Function}}\n */\n createPaylaterDirectDebit() {\n this.customerResource = this.createCustomer('paylater-direct-debit', true);\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n const paylaterDirectDebit = this.unzerInstance.PaylaterDirectDebit();\n\n this.hideFormFields('paylater-direct-debit');\n\n paylaterDirectDebit.create('paylater-direct-debit', {\n containerId: 'paylater-direct-debit',\n customerType: this.settings.isB2B ? 'B2B' : 'B2C'\n });\n\n paylaterDirectDebit.addEventListener('change', (e) =>\n this.onPaylaterInputValidation(\n e,\n e.success,\n 'paylater-direct-debit',\n continueButton\n )\n );\n\n return paylaterDirectDebit;\n }\n\n /**\n * Create Bancontact Payment Type\n *\n * @see https://docs.unzer.com/payment-methods/bancontact/accept-bancontact-ui-component/\n * @returns {{createResource: Function}}\n */\n createBancontact() {\n const bancontact = this.unzerInstance.Bancontact();\n const styling = { fontSize: null, fontColor: null, fontFamily: null };\n\n if (this.settings.styling) {\n styling.fontColor = this.settings.styling.fontColor || null;\n styling.fontSize = this.settings.styling.fontSize || null;\n styling.fontFamily = this.settings.styling.fontFamily || null;\n }\n\n bancontact.create('holder', {\n containerId: 'bancontact-holder',\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n fontFamily: styling.fontFamily\n });\n\n return bancontact;\n }\n\n /**\n * Create a new Card Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/credit-card-ui-integration\n * @returns {{createResource: Function}} Card Payment Type\n */\n createCard() {\n var Card = this.unzerInstance.Card();\n var styling = {fontSize: null, fontColor: null, fontFamily: null};\n\n if (this.settings.styling) {\n styling.fontColor = this.settings.styling.fontColor || null;\n styling.fontSize = this.settings.styling.fontSize || null;\n styling.fontFamily = this.settings.styling.fontFamily || null;\n }\n\n Card.create('number', {\n containerId: 'card-element-id-number',\n onlyIframe: false,\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n fontFamily: styling.fontFamily\n });\n Card.create('expiry', {\n containerId: 'card-element-id-expiry',\n onlyIframe: false,\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n fontFamily: styling.fontFamily\n });\n Card.create('cvc', {\n containerId: 'card-element-id-cvc',\n onlyIframe: false,\n fontSize: styling.fontSize,\n fontColor: styling.fontColor,\n // fontFamily: styling.fontFamily // messes with hidden font in firefox\n });\n\n // Enable pay button initially\n var self = this;\n var formFieldValid = {};\n\n /** @type {HTMLElement} continueButton */\n var continueButton = self.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n var eventHandlerCardInput = function (e) {\n if (e.success) {\n formFieldValid[e.type] = true;\n self.errorHandler.hide();\n }\n\n if (e.error) {\n formFieldValid[e.type] = false;\n self.errorHandler.show(e.error);\n }\n\n if (formFieldValid.number && formFieldValid.expiry && formFieldValid.cvc) {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n };\n\n Card.addEventListener('change', eventHandlerCardInput);\n\n return Card;\n }\n\n /**\n * Create a new Invoice Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/invoice-ui-integration\n * @returns {{createResource: Function}} Invoice Payment Type\n */\n createInvoice() {\n return this.unzerInstance.Invoice();\n }\n\n /**\n * Create a new Invoice Guaranteed Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/invoice-ui-integration\n * @returns {{createResource: Function}} Invoice Payment Type\n */\n createInvoiceGuaranteed() {\n this.customerResource = this.createCustomer();\n\n return this.unzerInstance.InvoiceSecured();\n }\n\n /**\n * Create a new Invoice Factoring Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/invoice-ui-integration\n * @returns {{createResource: Function}} Invoice Payment Type\n */\n createInvoiceFactoring() {\n this.customerResource = this.createCustomer();\n\n return this.unzerInstance.InvoiceSecured();\n }\n\n /**\n * Create a new SEPA Direct Debit Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration\n * @returns {{createResource: Function}} SEPA Direct Debit Payment Type\n */\n createSepa() {\n var Sepa = this.unzerInstance.SepaDirectDebit();\n Sepa.create('sepa-direct-debit', {\n containerId: 'sepa-IBAN'\n });\n\n /** @type {HTMLElement} continueButton */\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n Sepa.addEventListener('change', (e) => {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n this.errorHandler.hide();\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n\n return Sepa;\n }\n\n /**\n * Create a new SEPA Direct Debit (guaranteed) Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration\n * @returns {{createResource: Function}} SEPA Direct Debit (guaranteed) Payment Type\n */\n createSepaGuaranteed() {\n var SepaGuaranteed = this.unzerInstance.SepaDirectDebitSecured();\n SepaGuaranteed.create('sepa-direct-debit-guaranteed', {\n containerId: 'sepa-guaranteed-IBAN'\n });\n\n /** @type {HTMLElement} continueButton */\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n SepaGuaranteed.addEventListener('change', (e) => {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n this.errorHandler.hide();\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n\n this.customerResource = this.createCustomer();\n\n return SepaGuaranteed;\n }\n\n /**\n * Create a new PayPal Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/paypal-ui-integration\n * @returns {{createResource: Function}} Papal Payment Type\n */\n createPaypal() {\n var Paypal = this.unzerInstance.Paypal();\n Paypal.create('email', {\n containerId: 'paypal-element-email'\n });\n\n return Paypal;\n }\n\n /**\n * Create a new SOFORT Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#sofort\n * @returns {{createResource: Function}} Sofort Payment Type\n */\n createSofort() {\n return this.unzerInstance.Sofort();\n }\n\n /**\n * Create a new Giropay Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#giropay\n * @returns {{createResource: Function}} Giropay Payment Type\n */\n createGiropay () {\n return this.unzerInstance.Giropay();\n }\n\n /**\n * Create a new Przelewy24 Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#przelewy24\n * @returns {{createResource: Function}} Przelewy24 Payment Type\n */\n createPrzelewy24() {\n return this.unzerInstance.Przelewy24();\n }\n\n /**\n * Create a new iDEAL Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/ideal-ui-integration\n * @returns {{createResource: Function}} iDEAL Payment Type\n */\n createIdeal() {\n var Ideal = this.unzerInstance.Ideal();\n\n Ideal.create('ideal', {\n containerId: 'ideal-element'\n });\n\n /** @type {HTMLElement} continueButton */\n const continueButton = this.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('disabled', true);\n\n Ideal.addEventListener('change', (e) => {\n if (e.value) {\n continueButton.removeAttribute('disabled');\n this.errorHandler.hide();\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n });\n\n return Ideal;\n }\n\n /**\n * Create a new Prepayment Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/prepayment-ui-integration\n * @returns {{createResource: Function}} Prepayment Payment Type\n */\n createPrepayment() {\n return this.unzerInstance.Prepayment();\n }\n\n /**\n * Create a new EPS Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/eps-ui-integration\n * @returns {{createResource: Function}} EPS Payment Type\n */\n createEPS() {\n var EPS = this.unzerInstance.EPS();\n\n EPS.create('eps', {\n containerId: 'eps-element'\n });\n\n return EPS;\n }\n\n /**\n * Create a new FlexiPay Direct Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#flexipay-direct\n * @returns {{createResource: Function}} Alipay Payment Type\n */\n createFlexiPayDirect() {\n return this.unzerInstance.FlexiPayDirect();\n }\n\n /**\n * Create a new Alipay Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#alipay\n * @returns {{createResource: Function}} Alipay Payment Type\n */\n createAlipay() {\n return this.unzerInstance.Alipay();\n }\n\n /**\n * Create an new WeChat Pay Payment Type.\n *\n * @see https://docs.heidelpay.com/docs/redirect-ui-integration#wechat-pay\n * @returns {{createResource: Function}} WeChat Pay Payment Type\n */\n createWeChatPay() {\n return this.unzerInstance.Wechatpay();\n }\n\n /**\n * Create a new Hire Purchase Payment Type.\n *\n * @see https:://docs.heidelpay.com/docs/hire-purchase-ui-integration\n * @returns {{createResource: Function}} Hire Purchase Payment Type\n */\n createHirePurchase() {\n var InstallmentSecured = this.unzerInstance.InstallmentSecured();\n var self = this;\n this.customerResource = this.createCustomer();\n\n /** @type {HTMLElement} continueButton */\n var continueButton = self.settings.submitButton || document.getElementById(\"submit-button\");\n continueButton.setAttribute('style', 'display: none');\n continueButton.setAttribute('disabled', true);\n\n InstallmentSecured.create({\n containerId: 'hire-purchase-element',\n amount: this.settings.amount || null,\n currency: this.settings.currency || null,\n effectiveInterest: this.settings.effectiveInterest || null,\n orderDate: this.settings.orderDate || null\n }).then(function (data) {\n // if successful, notify the user that the list of installments was fetched successfully\n // in case you were using a loading element during the fetching process,\n // you can remove it inside this callback function\n })\n .catch(function (response) {\n // sent an error message to the user (fetching installment list failed)\n var msg = '';\n console.error(response.message);\n\n response.error.details.forEach(function(err) {\n console.error('API-Error: ' + err.code);\n msg += err.customerMessage;\n });\n\n self.errorHandler.show(msg);\n });\n\n\n // Listen to UI events\n InstallmentSecured.addEventListener('installmentSecuredEvent', function (e) {\n if (e.action === 'validate') {\n if (e.success) {\n continueButton.removeAttribute('disabled');\n return;\n }\n\n continueButton.setAttribute('disabled', true);\n }\n\n if (e.action === 'change-step') {\n if (e.currentSteep === 'plan-list') {\n continueButton.setAttribute('style', 'display: none');\n continueButton.setAttribute('disabled', true);\n return;\n }\n\n continueButton.setAttribute('style', 'display: inline-block');\n }\n });\n\n return InstallmentSecured;\n }\n}\n","/**\n * Heidelpay Installment Modal Window Handler\n *\n * @param {string} modalSelector\n * @param {HTMLElement} btn Submit Trigger\n * @param {JQuery} $form\n */\nconst Installment = (modalSelector, btn, $form) => {\n var modal = $(modalSelector);\n\n btn.addEventListener('click', function () {\n $form.trigger('submit');\n });\n\n $form.on('submit', function (e) {\n if (!modal.is(':visible')) {\n e.preventDefault();\n modal.modal('show');\n return false;\n }\n\n return true;\n });\n};\n\nexport default Installment;","export default class Debugging {\n constructor($container) {\n this.$container = $container;\n this.$log = null;\n\n if (!window.UNZER_DEBUG) {\n return;\n }\n\n this.createLogTemplate();\n }\n\n log(context, data = {}) {\n if (!window.UNZER_DEBUG) {\n return;\n }\n\n if (!this.$log) {\n this.createLogTemplate();\n }\n\n this.$log.append(\n '
        • ' + context + '
          ' + JSON.stringify(data,  null, '  ') +  '
        • '\n );\n }\n\n createLogTemplate() {\n this.$container.append(\n $('
            ')\n );\n this.$log = this.$container.find('.debug-log > ul');\n }\n}\n","export default class ErrorHandler {\n /**\n * @param {JQuery|null} $wrapper Wrapper for Container to display error messages in\n * @param {JQuery|null} $holder Container to display error messages in\n */\n constructor($wrapper, $holder) {\n this.$wrapper = $wrapper || $('#error-container');\n this.$holder = $holder || this.$wrapper.find('.alert');\n }\n\n /**\n * Show Error message\n * @param {String} message\n */\n show(message) {\n this.$wrapper.show();\n this.$holder.html(message);\n }\n\n /**\n * Hide error message\n */\n hide() {\n this.$wrapper.hide();\n this.$holder.html();\n }\n}\n","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nmodule.exports = _createClass, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\n\nmodule.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;"]} \ No newline at end of file diff --git a/frontend/src/js/app.js b/frontend/src/js/app.js new file mode 100644 index 0000000..e8638d6 --- /dev/null +++ b/frontend/src/js/app.js @@ -0,0 +1,7 @@ +import ApplePay from './payments/applepay'; +import UnzerPayment from "./payments/general"; +import Installment from "./payments/instalment"; + +window.HpPayment = UnzerPayment; +window.HpInstalment = Installment; +window.UnzerApplePay = ApplePay; diff --git a/frontend/src/js/payments/applepay.js b/frontend/src/js/payments/applepay.js new file mode 100644 index 0000000..c9f7dbe --- /dev/null +++ b/frontend/src/js/payments/applepay.js @@ -0,0 +1,194 @@ +import ErrorHandler from "../utils/errors"; +import Debugging from "../utils/debugging"; + +/** @type {ApplePaySnippets} */ +const ApplePaySnippetsDefaults = { + NOT_SUPPORTED: "This device does not support Apple Pay!", + CANCEL_BY_USER: "Canceled payment process by user!" +}; + +export default class ApplePay { + /** + * Similiar to the HeidelpayPayment class but slightly differently + * (apple pay works differently, so yeah, custom class it is :D) + * + * @class + * @param {String} pubKey + * @param {ApplePayPaymentRequest} applePayPaymentRequest + * @param {ApplePaySnippets} snippets + * @param {ApplePaySettings} settings + */ + constructor(pubKey, applePayPaymentRequest, snippets, settings) { + /** @type {ApplePaySettings} */ + this.settings = settings || {}; + + /** @type {ApplePaySnippets} */ + this.snippets = Object.assign(ApplePaySnippetsDefaults, snippets); + + var options = { + locale: this.settings.locale || 'de-DE' + }; + + /** @type {ApplePayPaymentRequest} */ + this.applePayPaymentRequest = applePayPaymentRequest; + this.unzerInstance = new unzer(pubKey, options); + this.errorHandler = new ErrorHandler(this.settings.$errorContainer, this.settings.$errorMessage); + this.debugging = new Debugging($('.unzerUI')); + window.UNZER_DEBUG = !!this.unzerInstance._isSandbox || this.unzerInstance.config.hasSandboxKey; // Enable Debugging in sandbox mode + + if (!window.ApplePaySession|| !window.ApplePaySession.canMakePayments()) { + this.unsupportedDevice(); + return; + } + + /** @type {HTMLElement} form Form in which the customer enters additional details */ + this.form = this.settings.form || document.getElementById('form_payment_extra'); + + // Register Events + this.initPaymentType = this.initPaymentType.bind(this); // it's a trick! needed in order to overcome the remove event listener + this.form.addEventListener('submit', this.initPaymentType); + $('.apple-pay-button').on('click', this.initPaymentType.bind(this)); + } + + /** + * Init the payment type in this case means starting the apple pay session + * @param {Event} event + */ + initPaymentType(event) { + event.preventDefault(); + + if (!window.ApplePaySession || !window.ApplePaySession.canMakePayments()) { + this.unsupportedDevice(); + return; + } + + // We adhere to Apple Pay version 6 to handle the payment request. + const session = new ApplePaySession(3, this.applePayPaymentRequest); + this.debugging.log('[> Init Payment Type]', {paymentRequest: this.applePayPaymentRequest}); + + session.onvalidatemerchant = (event) => { + this.merchantValidationCallback(event, session); + }; + + session.onpaymentauthorized = (event) => { + this.applePayAuthorizedCallback(event, session); + }; + + session.oncancel = (event) => { + this.debugging.log('[> Cancel]', {event}); + this.errorHandler.show(this.snippets.CANCEL_BY_USER); + }; + + session.begin(); + } + + /** + * Call the merchant validation in the server-side integration (apple_pay_merchantvalidation) + * @param {Event} event + * @param {ApplePaySession} session + */ + merchantValidationCallback(event, session) { + var validationUrl = JSON.stringify(event.validationURL); + + this.debugging.log('[> Merchant Validation]', {event}); + + $.ajax({ + 'url': $.evo.io().options.ioUrl, + 'method': 'POST', + 'dataType': 'json', + 'data': 'io={"name":"apple_pay_merchantvalidation", "params":[' + validationUrl + ']}', + }).done((validationResponse) => { + this.debugging.log('[> Merchant Validation Response]', validationResponse); + + try { + session.completeMerchantValidation(validationResponse); + } catch (e) { + alert(e.message); + } + }) + .fail((error) => { + this.debugging.log('[> Merchant Validation Error]', error); + this.errorHandler.show(JSON.stringify(error.statusText)); + session.abort(); + }); + } + + /** + * Create Apple Pay resource with unzer and save the resource id to charge it later. + * + * We do this here via AJAX instead of the validateAdditional method in the payment method to set the apple pay + * session state accordingly. + * + * @param {Event} event + * @param {ApplePaySession} session + */ + applePayAuthorizedCallback(event, session) { + // Get payment data from event. + // "event.payment" also contains contact information, if they were set via Apple Pay. + var self = this; + var unzerApplePayInstance = this.unzerInstance.ApplePay(); + var paymentData = event.payment.token.paymentData; + + this.debugging.log('[> Payment Authorization]', {unzerApplePayInstance, event, paymentData}); + + // Create an Unzer instance with your public key + unzerApplePayInstance.createResource(paymentData) + .then(function (createdResource) { + // Hand over the type ID to your backend. + var typeId = JSON.stringify(createdResource.id); + $.ajax({ + 'url': $.evo.io().options.ioUrl, + 'method': 'POST', + 'dataType': 'json', + 'data': 'io={"name":"apple_pay_payment_authorized", "params":[' + typeId + ']}', + }).done(function (result) { + // Handle the transaction respone from backend. + self.debugging.log('[> Payment Authorization Response]', {result, typeId}); + var status = result.transactionStatus; + if (status === 'success' || status === 'pending') { + session.completePayment({ status: window.ApplePaySession.STATUS_SUCCESS }); + + // Append Payment Resource Id + const hiddenInput = document.createElement('input'); + hiddenInput.setAttribute('type', 'hidden'); + hiddenInput.setAttribute('name', 'paymentData[resourceId]'); + hiddenInput.setAttribute('value', typeId); + self.form.appendChild(hiddenInput); + + // Submitting the form + self.form.removeEventListener('submit', self.initPaymentType); + self.form.submit(); + } else { + self.abortPaymentSession(session); + } + }).fail(function (error) { + self.errorHandler.show(error.statusText); + self.abortPaymentSession(session); + }); + }) + .catch(function (error) { + self.debugging.log('[> Payment Authorization Error]', error); + self.errorHandler.show(error.message); + self.abortPaymentSession(session); + }); + } + + /** + * Handle Unsupported devices + */ + unsupportedDevice() { + this.settings.submitButton.disabled = true; + this.settings.submitButton.ariaDisabled = true; + this.errorHandler.show(this.snippets.NOT_SUPPORTED); + } + + /** + * abort current payment session. + * @param {ApplePaySession} session + */ + abortPaymentSession(session) { + this.debugging.log('[> Abort Payment Session]', { status: window.ApplePaySession.STATUS_FAILURE }); + session.completePayment({ status: window.ApplePaySession.STATUS_FAILURE }); + session.abort(); + } +} diff --git a/frontend/src/js/payments/general.js b/frontend/src/js/payments/general.js new file mode 100644 index 0000000..7f6b920 --- /dev/null +++ b/frontend/src/js/payments/general.js @@ -0,0 +1,821 @@ +import ErrorHandler from "../utils/errors"; + +export default class UnzerPayment { + static PAYMENT_TYPES = { + ALIPAY: 'Alipay', + CARD: 'Card', + EPS: 'EPS', + FLEXIPAY_DIRECT: 'FlexiPay Direct', + HIRE_PURCHASE: 'Hire Purchase', + PAYPAL: 'Paypal', + INVOICE: 'Invoice', + INVOICE_FACTORING: 'Invoice Factoring', + INVOICE_GUARANTEED: 'Invoice Guaranteed', + SEPA: 'SEPA', + SEPA_GUARANTEED: 'SEPA (guaranteed)', + SOFORT: 'SOFORT', + GIROPAY: 'Giropay', + PRZELEWY24: 'Przelewy24', + IDEAL: 'iDEAL', + PREPAYMENT: 'Prepayment', + WECHAT_PAY: 'WeChat Pay', + PAYLATER_INVOICE: 'Paylater Invoice', + BANCONTACT: 'Bancontact', + PAYLATER_INSTALLMENT: 'Paylater Installment', + PAYLATER_DIRECT_DEBIT: 'Paylater Direct Debit', + }; + + /** + * Heidelpay Payment Class + * + * @param {string} pubKey Public Key + * @param {string} type Payment Type + * @param {PaymentSettings} settings + */ + constructor(pubKey, type, settings) { + /** @type {PaymentSettings} */ + this.settings = settings || {}; + + var options = { + locale: this.settings.locale || 'de-DE' + }; + + this.unzerInstance = new unzer(pubKey, options); + this.errorHandler = new ErrorHandler(this.settings.$errorContainer, this.settings.$errorMessage); + + /** @type {?string} customerId */ + this.customerId = settings.customerId || null; + + /** @type {{createCustomer: Function, updateCustomer: Function}|null} customerResource */ + this.customerResource = null; + + /** @type {{createResource: Function}} paymentType */ + this.paymentType = this.initPaymentType(type); + + /** @type {HTMLElement} form Form in which the customer enters additional details */ + this.form = this.settings.form || document.getElementById('form_payment_extra'); + + // Register Events + this.handleFormSubmit = this.handleFormSubmit.bind(this); // it's a trick! needed in order to overcome the remove event listener + this.form.addEventListener('submit', this.handleFormSubmit); + + if (this.settings.autoSubmit) { + // this.form.dispatchEvent(new Event('submit')); // Causes endless redirects in some browsers like FF, so we call the callback directly... + this.handleFormSubmit(new Event('submit')); + } + } + + /** + * Init Payment Type + * + * @param {string} type + * @returns {object} payment type + * @throws Error if there is an unkown payment type + */ + initPaymentType(type) { + switch (type) { + case UnzerPayment.PAYMENT_TYPES.CARD: + return this.createCard(); + + case UnzerPayment.PAYMENT_TYPES.INVOICE: + return this.createInvoice(); + + case UnzerPayment.PAYMENT_TYPES.INVOICE_GUARANTEED: + return this.createInvoiceGuaranteed(); + + case UnzerPayment.PAYMENT_TYPES.INVOICE_FACTORING: + return this.createInvoiceFactoring(); + + case UnzerPayment.PAYMENT_TYPES.SEPA: + return this.createSepa(); + + case UnzerPayment.PAYMENT_TYPES.SEPA_GUARANTEED: + return this.createSepaGuaranteed(); + + case UnzerPayment.PAYMENT_TYPES.PAYPAL: + return this.createPaypal(); + + case UnzerPayment.PAYMENT_TYPES.SOFORT: + return this.createSofort(); + + case UnzerPayment.PAYMENT_TYPES.GIROPAY: + return this.createGiropay(); + + case UnzerPayment.PAYMENT_TYPES.PRZELEWY24: + return this.createPrzelewy24(); + + case UnzerPayment.PAYMENT_TYPES.IDEAL: + return this.createIdeal(); + + case UnzerPayment.PAYMENT_TYPES.PREPAYMENT: + return this.createPrepayment(); + + case UnzerPayment.PAYMENT_TYPES.EPS: + return this.createEPS(); + + case UnzerPayment.PAYMENT_TYPES.FLEXIPAY_DIRECT: + return this.createFlexiPayDirect(); + + case UnzerPayment.PAYMENT_TYPES.ALIPAY: + return this.createAlipay(); + + case UnzerPayment.PAYMENT_TYPES.WECHAT_PAY: + return this.createWeChatPay(); + + case UnzerPayment.PAYMENT_TYPES.HIRE_PURCHASE: + return this.createHirePurchase(); + + case UnzerPayment.PAYMENT_TYPES.PAYLATER_INVOICE: + return this.createPaylaterInvoice(); + + case UnzerPayment.PAYMENT_TYPES.BANCONTACT: + return this.createBancontact(); + + case UnzerPayment.PAYMENT_TYPES.PAYLATER_INSTALLMENT: + return this.createPaylaterInstallment(); + + case UnzerPayment.PAYMENT_TYPES.PAYLATER_DIRECT_DEBIT: + return this.createPaylaterDirectDebit(); + + default: + throw new Error('Unkown Payment Type: ' + type); + } + } + + /** + * Handle the form submit + * + * @param {Event} event Submit Event + */ + handleFormSubmit(event) { + var self = this; + event.preventDefault(); + + // Creating a Payment resource and (optional) Customer Resource + var resources = [this.paymentType.createResource()]; + + if (this.customerResource) { + resources.push(this.customerId ? this.customerResource.updateCustomer() : this.customerResource.createCustomer()); + } + + Promise.all(resources).then(function (result) { + // Append Payment Resource Id + var hiddenInput = document.createElement('input'); + hiddenInput.setAttribute('type', 'hidden'); + hiddenInput.setAttribute('name', 'paymentData[resourceId]'); + hiddenInput.setAttribute('value', result[0].id); + self.form.appendChild(hiddenInput); + + // Append Customer Id + if (result.length >= 2) { + var hiddenCstInput = document.createElement('input'); + hiddenCstInput.setAttribute('type', 'hidden'); + hiddenCstInput.setAttribute('name', 'paymentData[customerId]'); + hiddenCstInput.setAttribute('value', result[1].id); + self.form.appendChild(hiddenCstInput); + } + + // Submitting the form + self.form.removeEventListener('submit', self.handleFormSubmit); + self.form.submit(); + }) + .catch(function (error) { + self.errorHandler.show(error.message); + }); + } + + /** + * Handle Paylater Input Validation + * @param {Event} event + * @param {boolean} isValid + * @param {String} paymentMethodName + * @param {HTMLElement} continueButton + * @returns + */ + onPaylaterInputValidation(event, isValid, paymentMethodName, continueButton) { + // console.log(paymentMethodName, { event, isValid, continueButton, 's360-valid': continueButton.getAttribute('data-s360-valid') }); + + if (isValid) { + // everything is still valid + if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.removeAttribute('disabled'); + return; + } + + // Customer is already valid -> everything is valid + if (continueButton.getAttribute('data-s360-valid') == 'customer') { + continueButton.setAttribute('data-s360-valid', 'all'); + continueButton.removeAttribute('disabled'); + return; + } + + // mark payment method as valid + continueButton.setAttribute('data-s360-valid', paymentMethodName); + return; + } + + continueButton.setAttribute('disabled', true); + + // only invalidate if the paymentMethodName was valid before + if (continueButton.getAttribute('data-s360-valid') == paymentMethodName) { + continueButton.setAttribute('data-s360-valid', 0); + } else if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.setAttribute('data-s360-valid', 'customer'); + } + } + + /** + * Create (or update) customer resource. + * + * @param {?String} paymentTypeName + * @param {?String} multipleValidation + * @see https://docs.heidelpay.com/docs/customer-ui-integration + * @returns {{createCustomer: Function, updateCustomer: Function}} Customer Resource + */ + createCustomer(paymentTypeName = null, multipleValidation = false) { + var Customer = this.settings.isB2B ? this.unzerInstance.B2BCustomer() : this.unzerInstance.Customer(); + var customerObj = this.settings.customer || {}; + var continueButton = this.settings.submitButton || document.getElementById("submit-button"); + let options = { + containerId: 'customer', + showInfoBox: false, + showHeader: false, + fields: ['name', 'birthdate'] + }; + + if (paymentTypeName) { + options.paymentTypeName = paymentTypeName; + } + + Customer.initFormFields(customerObj); + if (multipleValidation) { + continueButton.setAttribute('data-s360-valid', 0); + + Customer.addEventListener('validate', (e) => { + // console.log('customer validate', e, continueButton, continueButton.getAttribute('data-s360-valid')); + continueButton.setAttribute('disabled', true); + + if (e.success) { + // everything is still valid + if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.removeAttribute('disabled'); + return; + } + + // payment method is already valid -> everything is valid + if (continueButton.getAttribute('data-s360-valid') == paymentTypeName) { + continueButton.setAttribute('data-s360-valid', 'all'); + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('data-s360-valid', 'customer'); + return; + } + + // only invalidate if the customer was valid before + if (continueButton.getAttribute('data-s360-valid') == 'customer') { + continueButton.setAttribute('data-s360-valid', 0); + } else if (continueButton.getAttribute('data-s360-valid') == 'all') { + continueButton.setAttribute('data-s360-valid', paymentTypeName); + } + }); + } else { + Customer.addEventListener('validate', (e) => { + if (e.success) { + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('disabled', true); + }); + } + + if (this.settings.isB2B) { + options.fields = ['companyInfo']; + // options = {containerId: 'customer'}; + } + + if (this.customerId) { + Customer.update(this.customerId, options); + return Customer; + } + + Customer.create(options); + + return Customer; + } + + /** + * Hide form fields from unzer ui component because they are already filled by the shop + * @param {string} paymentMethodName + */ + hideFormFields(paymentMethodName) { + const field = $('#customer'); + + field.find('.field').filter( + '.city, .company, :has(.country), .street, .zip, .firstname, .lastname' + ).hide(); + field.find('.salutation-customer').hide(); + field.find('.firstname, .lastname').parent('.fields').hide(); + field.find('.unzerUI.divider-horizontal:eq(0)').hide(); + field.find('.unzerUI.message.downArrow').hide(); + + if (paymentMethodName) { + field.find('.field').filter('.checkbox-billingAddress, .email').hide(); + field.find('.field').filter( + '.billing-name, .billing-street, .billing-zip, .billing-city, :has(.billing-country)' + ).hide(); + field.find('.unzerUI.form>.checkboxLabel').hide(); + field.find('.unzerUI.form>.salutation-unzer-' + paymentMethodName + '-customer').hide(); + } + } + + /** + * Create Paylayter Installment Payment Type + * + * @see https://docs.unzer.com/payment-methods/unzer-installment-upl/accept-unzer-installment-ui-component/ + * @returns {{createResource: Function}} + */ + createPaylaterInstallment() { + this.customerResource = this.createCustomer('paylater-installment', true); + const continueButton = this.settings.submitButton || document.getElementById("submit-button"); + const paylaterInstallment = this.unzerInstance.PaylaterInstallment(); + + this.hideFormFields('paylater-installment'); + + paylaterInstallment.create({ + containerId: 'paylater-installment', + amount: this.settings.amount, + currency: this.settings.currency, + country: this.settings.country + }); + + paylaterInstallment.addEventListener('paylaterInstallmentEvent', (e) => { + switch (e.currentStep) { + case 'plan-list': + continueButton.setAttribute('disabled', true); + break; + + case 'plan-detail': + continueButton.setAttribute('disabled', false); + break; + + default: + break; + } + + const isValid = e.action === 'validate' && e.success; + this.onPaylaterInputValidation(e, isValid, 'paylater-installment', continueButton); + }); + + return paylaterInstallment; + } + + /** + * Create Paylayter Invoice Payment Type + * + * @see https://docs.unzer.com/payment-methods/unzer-invoice-upl/accept-unzer-invoice-upl-ui-component/ + * @returns {{createResource: Function}} + */ + createPaylaterInvoice() { + this.customerResource = this.createCustomer('paylater-invoice', true); + const continueButton = this.settings.submitButton || document.getElementById("submit-button"); + const paylaterInvoice = this.unzerInstance.PaylaterInvoice(); + + this.hideFormFields('paylater-invoice'); + + paylaterInvoice.create({ + containerId: 'paylater-invoice', + customerType: this.settings.isB2B ? 'B2B' : 'B2C' + }); + + paylaterInvoice.addEventListener('change', (e) => + this.onPaylaterInputValidation( + e, + e.success, + 'paylater-invoice', + continueButton + ) + ); + + return paylaterInvoice; + } + + /** + * Create Paylayter Invoice Payment Type + * + * @see https://docs.unzer.com/payment-methods/direct-debit-secured/accept-direct-debit-secured-ui-component/ + * @returns {{createResource: Function}} + */ + createPaylaterDirectDebit() { + this.customerResource = this.createCustomer('paylater-direct-debit', true); + const continueButton = this.settings.submitButton || document.getElementById("submit-button"); + const paylaterDirectDebit = this.unzerInstance.PaylaterDirectDebit(); + + this.hideFormFields('paylater-direct-debit'); + + paylaterDirectDebit.create('paylater-direct-debit', { + containerId: 'paylater-direct-debit', + customerType: this.settings.isB2B ? 'B2B' : 'B2C' + }); + + paylaterDirectDebit.addEventListener('change', (e) => + this.onPaylaterInputValidation( + e, + e.success, + 'paylater-direct-debit', + continueButton + ) + ); + + return paylaterDirectDebit; + } + + /** + * Create Bancontact Payment Type + * + * @see https://docs.unzer.com/payment-methods/bancontact/accept-bancontact-ui-component/ + * @returns {{createResource: Function}} + */ + createBancontact() { + const bancontact = this.unzerInstance.Bancontact(); + const styling = { fontSize: null, fontColor: null, fontFamily: null }; + + if (this.settings.styling) { + styling.fontColor = this.settings.styling.fontColor || null; + styling.fontSize = this.settings.styling.fontSize || null; + styling.fontFamily = this.settings.styling.fontFamily || null; + } + + bancontact.create('holder', { + containerId: 'bancontact-holder', + fontSize: styling.fontSize, + fontColor: styling.fontColor, + fontFamily: styling.fontFamily + }); + + return bancontact; + } + + /** + * Create a new Card Payment Type. + * + * @see https://docs.heidelpay.com/docs/credit-card-ui-integration + * @returns {{createResource: Function}} Card Payment Type + */ + createCard() { + var Card = this.unzerInstance.Card(); + var styling = {fontSize: null, fontColor: null, fontFamily: null}; + + if (this.settings.styling) { + styling.fontColor = this.settings.styling.fontColor || null; + styling.fontSize = this.settings.styling.fontSize || null; + styling.fontFamily = this.settings.styling.fontFamily || null; + } + + Card.create('number', { + containerId: 'card-element-id-number', + onlyIframe: false, + fontSize: styling.fontSize, + fontColor: styling.fontColor, + fontFamily: styling.fontFamily + }); + Card.create('expiry', { + containerId: 'card-element-id-expiry', + onlyIframe: false, + fontSize: styling.fontSize, + fontColor: styling.fontColor, + fontFamily: styling.fontFamily + }); + Card.create('cvc', { + containerId: 'card-element-id-cvc', + onlyIframe: false, + fontSize: styling.fontSize, + fontColor: styling.fontColor, + // fontFamily: styling.fontFamily // messes with hidden font in firefox + }); + + // Enable pay button initially + var self = this; + var formFieldValid = {}; + + /** @type {HTMLElement} continueButton */ + var continueButton = self.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + + var eventHandlerCardInput = function (e) { + if (e.success) { + formFieldValid[e.type] = true; + self.errorHandler.hide(); + } + + if (e.error) { + formFieldValid[e.type] = false; + self.errorHandler.show(e.error); + } + + if (formFieldValid.number && formFieldValid.expiry && formFieldValid.cvc) { + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('disabled', true); + }; + + Card.addEventListener('change', eventHandlerCardInput); + + return Card; + } + + /** + * Create a new Invoice Payment Type. + * + * @see https://docs.heidelpay.com/docs/invoice-ui-integration + * @returns {{createResource: Function}} Invoice Payment Type + */ + createInvoice() { + return this.unzerInstance.Invoice(); + } + + /** + * Create a new Invoice Guaranteed Payment Type. + * + * @see https://docs.heidelpay.com/docs/invoice-ui-integration + * @returns {{createResource: Function}} Invoice Payment Type + */ + createInvoiceGuaranteed() { + this.customerResource = this.createCustomer(); + + return this.unzerInstance.InvoiceSecured(); + } + + /** + * Create a new Invoice Factoring Payment Type. + * + * @see https://docs.heidelpay.com/docs/invoice-ui-integration + * @returns {{createResource: Function}} Invoice Payment Type + */ + createInvoiceFactoring() { + this.customerResource = this.createCustomer(); + + return this.unzerInstance.InvoiceSecured(); + } + + /** + * Create a new SEPA Direct Debit Payment Type. + * + * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration + * @returns {{createResource: Function}} SEPA Direct Debit Payment Type + */ + createSepa() { + var Sepa = this.unzerInstance.SepaDirectDebit(); + Sepa.create('sepa-direct-debit', { + containerId: 'sepa-IBAN' + }); + + /** @type {HTMLElement} continueButton */ + const continueButton = this.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + + Sepa.addEventListener('change', (e) => { + if (e.success) { + continueButton.removeAttribute('disabled'); + this.errorHandler.hide(); + return; + } + + continueButton.setAttribute('disabled', true); + }); + + return Sepa; + } + + /** + * Create a new SEPA Direct Debit (guaranteed) Payment Type. + * + * @see https://docs.heidelpay.com/docs/sepa-direct-debit-ui-integration + * @returns {{createResource: Function}} SEPA Direct Debit (guaranteed) Payment Type + */ + createSepaGuaranteed() { + var SepaGuaranteed = this.unzerInstance.SepaDirectDebitSecured(); + SepaGuaranteed.create('sepa-direct-debit-guaranteed', { + containerId: 'sepa-guaranteed-IBAN' + }); + + /** @type {HTMLElement} continueButton */ + const continueButton = this.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + + SepaGuaranteed.addEventListener('change', (e) => { + if (e.success) { + continueButton.removeAttribute('disabled'); + this.errorHandler.hide(); + return; + } + + continueButton.setAttribute('disabled', true); + }); + + this.customerResource = this.createCustomer(); + + return SepaGuaranteed; + } + + /** + * Create a new PayPal Payment Type. + * + * @see https://docs.heidelpay.com/docs/paypal-ui-integration + * @returns {{createResource: Function}} Papal Payment Type + */ + createPaypal() { + var Paypal = this.unzerInstance.Paypal(); + Paypal.create('email', { + containerId: 'paypal-element-email' + }); + + return Paypal; + } + + /** + * Create a new SOFORT Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#sofort + * @returns {{createResource: Function}} Sofort Payment Type + */ + createSofort() { + return this.unzerInstance.Sofort(); + } + + /** + * Create a new Giropay Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#giropay + * @returns {{createResource: Function}} Giropay Payment Type + */ + createGiropay () { + return this.unzerInstance.Giropay(); + } + + /** + * Create a new Przelewy24 Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#przelewy24 + * @returns {{createResource: Function}} Przelewy24 Payment Type + */ + createPrzelewy24() { + return this.unzerInstance.Przelewy24(); + } + + /** + * Create a new iDEAL Payment Type. + * + * @see https://docs.heidelpay.com/docs/ideal-ui-integration + * @returns {{createResource: Function}} iDEAL Payment Type + */ + createIdeal() { + var Ideal = this.unzerInstance.Ideal(); + + Ideal.create('ideal', { + containerId: 'ideal-element' + }); + + /** @type {HTMLElement} continueButton */ + const continueButton = this.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('disabled', true); + + Ideal.addEventListener('change', (e) => { + if (e.value) { + continueButton.removeAttribute('disabled'); + this.errorHandler.hide(); + return; + } + + continueButton.setAttribute('disabled', true); + }); + + return Ideal; + } + + /** + * Create a new Prepayment Payment Type. + * + * @see https://docs.heidelpay.com/docs/prepayment-ui-integration + * @returns {{createResource: Function}} Prepayment Payment Type + */ + createPrepayment() { + return this.unzerInstance.Prepayment(); + } + + /** + * Create a new EPS Payment Type. + * + * @see https://docs.heidelpay.com/docs/eps-ui-integration + * @returns {{createResource: Function}} EPS Payment Type + */ + createEPS() { + var EPS = this.unzerInstance.EPS(); + + EPS.create('eps', { + containerId: 'eps-element' + }); + + return EPS; + } + + /** + * Create a new FlexiPay Direct Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#flexipay-direct + * @returns {{createResource: Function}} Alipay Payment Type + */ + createFlexiPayDirect() { + return this.unzerInstance.FlexiPayDirect(); + } + + /** + * Create a new Alipay Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#alipay + * @returns {{createResource: Function}} Alipay Payment Type + */ + createAlipay() { + return this.unzerInstance.Alipay(); + } + + /** + * Create an new WeChat Pay Payment Type. + * + * @see https://docs.heidelpay.com/docs/redirect-ui-integration#wechat-pay + * @returns {{createResource: Function}} WeChat Pay Payment Type + */ + createWeChatPay() { + return this.unzerInstance.Wechatpay(); + } + + /** + * Create a new Hire Purchase Payment Type. + * + * @see https:://docs.heidelpay.com/docs/hire-purchase-ui-integration + * @returns {{createResource: Function}} Hire Purchase Payment Type + */ + createHirePurchase() { + var InstallmentSecured = this.unzerInstance.InstallmentSecured(); + var self = this; + this.customerResource = this.createCustomer(); + + /** @type {HTMLElement} continueButton */ + var continueButton = self.settings.submitButton || document.getElementById("submit-button"); + continueButton.setAttribute('style', 'display: none'); + continueButton.setAttribute('disabled', true); + + InstallmentSecured.create({ + containerId: 'hire-purchase-element', + amount: this.settings.amount || null, + currency: this.settings.currency || null, + effectiveInterest: this.settings.effectiveInterest || null, + orderDate: this.settings.orderDate || null + }).then(function (data) { + // if successful, notify the user that the list of installments was fetched successfully + // in case you were using a loading element during the fetching process, + // you can remove it inside this callback function + }) + .catch(function (response) { + // sent an error message to the user (fetching installment list failed) + var msg = ''; + console.error(response.message); + + response.error.details.forEach(function(err) { + console.error('API-Error: ' + err.code); + msg += err.customerMessage; + }); + + self.errorHandler.show(msg); + }); + + + // Listen to UI events + InstallmentSecured.addEventListener('installmentSecuredEvent', function (e) { + if (e.action === 'validate') { + if (e.success) { + continueButton.removeAttribute('disabled'); + return; + } + + continueButton.setAttribute('disabled', true); + } + + if (e.action === 'change-step') { + if (e.currentSteep === 'plan-list') { + continueButton.setAttribute('style', 'display: none'); + continueButton.setAttribute('disabled', true); + return; + } + + continueButton.setAttribute('style', 'display: inline-block'); + } + }); + + return InstallmentSecured; + } +} diff --git a/frontend/src/js/payments/instalment.js b/frontend/src/js/payments/instalment.js new file mode 100644 index 0000000..7b11abb --- /dev/null +++ b/frontend/src/js/payments/instalment.js @@ -0,0 +1,26 @@ +/** + * Heidelpay Installment Modal Window Handler + * + * @param {string} modalSelector + * @param {HTMLElement} btn Submit Trigger + * @param {JQuery} $form + */ +const Installment = (modalSelector, btn, $form) => { + var modal = $(modalSelector); + + btn.addEventListener('click', function () { + $form.trigger('submit'); + }); + + $form.on('submit', function (e) { + if (!modal.is(':visible')) { + e.preventDefault(); + modal.modal('show'); + return false; + } + + return true; + }); +}; + +export default Installment; \ No newline at end of file diff --git a/frontend/src/js/utils/debugging.js b/frontend/src/js/utils/debugging.js new file mode 100644 index 0000000..26765a4 --- /dev/null +++ b/frontend/src/js/utils/debugging.js @@ -0,0 +1,33 @@ +export default class Debugging { + constructor($container) { + this.$container = $container; + this.$log = null; + + if (!window.UNZER_DEBUG) { + return; + } + + this.createLogTemplate(); + } + + log(context, data = {}) { + if (!window.UNZER_DEBUG) { + return; + } + + if (!this.$log) { + this.createLogTemplate(); + } + + this.$log.append( + '
          • ' + context + '
            ' + JSON.stringify(data,  null, '  ') +  '
          • ' + ); + } + + createLogTemplate() { + this.$container.append( + $('
              ') + ); + this.$log = this.$container.find('.debug-log > ul'); + } +} diff --git a/frontend/src/js/utils/errors.js b/frontend/src/js/utils/errors.js new file mode 100644 index 0000000..1ce06cd --- /dev/null +++ b/frontend/src/js/utils/errors.js @@ -0,0 +1,27 @@ +export default class ErrorHandler { + /** + * @param {JQuery|null} $wrapper Wrapper for Container to display error messages in + * @param {JQuery|null} $holder Container to display error messages in + */ + constructor($wrapper, $holder) { + this.$wrapper = $wrapper || $('#error-container'); + this.$holder = $holder || this.$wrapper.find('.alert'); + } + + /** + * Show Error message + * @param {String} message + */ + show(message) { + this.$wrapper.show(); + this.$holder.html(message); + } + + /** + * Hide error message + */ + hide() { + this.$wrapper.hide(); + this.$holder.html(); + } +} diff --git a/frontend/src/js/utils/types.js b/frontend/src/js/utils/types.js new file mode 100644 index 0000000..c7b7374 --- /dev/null +++ b/frontend/src/js/utils/types.js @@ -0,0 +1,46 @@ +// @ts-check + +/** + * @typedef {{ + * submitButton: HTMLElement|HTMLButtonElement|null, + * form: ?HTMLElement, + * locale: string + * }} ApplePaySettings + */ + +/** + * @typedef {{ + * NOT_SUPPORTED: string + * CANCEL_BY_USER: string + * }} ApplePaySnippets + */ + +/** + * @typedef {{ + * $errorHolder: ?jQuery, + * $form: ?jQuery, + * submitButton: HTMLElement|HTMLButtonElement|null, + * locale: ?string, + * customerId: ?string, + * customer: ?object, + * autoSubmit: ?boolean, + * amount: null|string|number, + * currency: ?string, + * effectiveInterest: null|string|number, + * orderDate: ?string, + * styling: {fontSize: string, fontFamily: string, fontColor: string}, + * isB2B: ?boolean, + * county: ?string + * }} PaymentSettings + */ + +/** + * @typedef {{ + * countryCode: string, + * currencyCode: string, + * supportedNetworks: string[], + * merchantCapabilities: string[], + * total: { label: string, amount: number }, + * lineItems: Array<{label: string, amount: number, type: string}> + * }} ApplePayPaymentRequest + */ \ No newline at end of file diff --git a/frontend/src/scss/unzer.scss b/frontend/src/scss/unzer.scss new file mode 100644 index 0000000..1281783 --- /dev/null +++ b/frontend/src/scss/unzer.scss @@ -0,0 +1,34 @@ +// Heidelpay UI Fixes +.unzerUI { + .field { + position: relative; + } +} + +// NOVA Fixes +.label-slide .form-group:not(.exclude-from-label-slide):not(.checkbox) .unzerUI { + &.form { + label { + position: relative; + top: initial; + left: initial; + font-size: 1rem; + margin: 0 0 .28571429rem; + padding: 0; + transform: none; + line-height: 30px; + pointer-events: all; + text-overflow: initial; + white-space: normal; + overflow: initial; + max-width: none; + } + } + + &.checkbox { + .box, label { + cursor: pointer; + padding-left: 2.5em; + } + } +} diff --git a/frontend/template/hire_purchase_direct_debit.tpl b/frontend/template/hire_purchase_direct_debit.tpl index 972058d..12d2276 100644 --- a/frontend/template/hire_purchase_direct_debit.tpl +++ b/frontend/template/hire_purchase_direct_debit.tpl @@ -21,17 +21,17 @@ $(document).ready(function() {
              {$hpInstalment.lang.totalPurchaseAmount}
              -
              {$hpInstalment.totalPurchaseAmount|number_format:2} {$hpInstalment.currency}
              +
              {number_format($hpInstalment.totalPurchaseAmount|default:0, 2)} {$hpInstalment.currency}
              {$hpInstalment.lang.totalInterestAmount}
              -
              {$hpInstalment.totalInterestAmount|number_format:2} {$hpInstalment.currency}
              +
              {number_format($hpInstalment.totalInterestAmount|default:0, 2)} {$hpInstalment.currency}
              {$hpInstalment.lang.totalAmount}
              -
              {$hpInstalment.totalAmount|number_format:2} {$hpInstalment.currency}
              +
              {number_format($hpInstalment.totalAmount|default:0, 2)} {$hpInstalment.currency}

              diff --git a/frontend/template/instalment_info.tpl b/frontend/template/instalment_info.tpl new file mode 100644 index 0000000..1b144ad --- /dev/null +++ b/frontend/template/instalment_info.tpl @@ -0,0 +1 @@ +{$info} \ No newline at end of file diff --git a/frontend/template/partials/_threatMetrix.tpl b/frontend/template/partials/_threatMetrix.tpl new file mode 100644 index 0000000..360849e --- /dev/null +++ b/frontend/template/partials/_threatMetrix.tpl @@ -0,0 +1,12 @@ +{if $hpPayment.threatMetrixId} + + + +{/if} \ No newline at end of file diff --git a/info.xml b/info.xml index 670da30..e1da24a 100644 --- a/info.xml +++ b/info.xml @@ -6,7 +6,7 @@ http://www.solution360.de 100 5.0.0 - 1.0.1 + 1.4.1 s360_unzer_shop5 2020-10-27 eef84f33-97ff-4519-8e0f-6760ae06c51f @@ -16,6 +16,12 @@ + + + + + + @@ -75,6 +81,55 @@ + + s360_hp_cancel_payment_reference + + + + + + + + + + + + s360_hp_apple_pay_not_supported + + + + + + + + + + + + s360_hp_apple_pay_cancel_by_user + + + + + + + + + + + + + s360_hp_error_validating_merchant + + + + + + + + + + s360_hp_invalid_form_token @@ -237,6 +292,18 @@ + + s360_hp_instalment_info + + + + + Hinweis: Die angegebene Gesamtsumme unterscheidet sich von dem zu zahlenden Betrag. Den zu zahlenden Betrag entnehmen Sie bitte ihrem Ratenzahlungsplan.]]> + + + Note: The total amount shown differs from the amount to be paid. Please refer to your instalment plan for the amount to be paid.]]> + + @@ -280,13 +347,13 @@ template/dummy.tpl template/sepa_form.tpl - - + + - - + + @@ -305,13 +372,13 @@ template/dummy.tpl template/sepa_guaranteed_form.tpl - - + + - - + + @@ -330,13 +397,13 @@ template/dummy.tpl template/invoice_form.tpl - - + + - - + + @@ -355,13 +422,38 @@ template/dummy.tpl template/invoice_guaranteed_form.tpl - - + + - - + + + + + + + + 0 + 1 + + INVOICE + 1 + 0 + 1 + 0 + UnzerPaylaterInvoice.php + UnzerPaylaterInvoice + template/dummy.tpl + template/paylater_invoice_form.tpl + + + + + + + + @@ -672,6 +764,106 @@ effectiveInterest + + + 10 + 1 + + OTHER + 0 + 0 + 1 + 0 + UnzerApplePay.php + UnzerApplePay + template/dummy.tpl + template/applepay.tpl + + + + + + + + + + + + + + 20 + 1 + + OTHER + 0 + 0 + 1 + 0 + UnzerBancontact.php + UnzerBancontact + template/dummy.tpl + template/bancontact_form.tpl + + + + + + + + + + + + + + 30 + 1 + + OTHER + 1 + 0 + 1 + 0 + UnzerPaylaterInstallment.php + UnzerPaylaterInstallment + template/dummy.tpl + template/paylater_installment_form.tpl + + + + + + + + + + + + + + 40 + 1 + + OTHER + 1 + 0 + 1 + 0 + UnzerPaylaterDirectDebit.php + UnzerPaylaterDirectDebit + template/dummy.tpl + template/paylater_direct_debit_form.tpl + + + + + + + + + + + \ No newline at end of file diff --git a/locale/de-DE/base.mo b/locale/de-DE/base.mo index 9d94f5a..9b13204 100644 Binary files a/locale/de-DE/base.mo and b/locale/de-DE/base.mo differ diff --git a/locale/de-DE/base.po b/locale/de-DE/base.po index a39be70..8229ece 100644 --- a/locale/de-DE/base.po +++ b/locale/de-DE/base.po @@ -8,22 +8,28 @@ msgid "Unzer Kreditkarte" msgstr "Unzer Kreditkarte" msgid "Unzer SEPA-Lastschrift" -msgstr "Unzer Lastschrift" +msgstr "Unzer SEPA Lastschrift" msgid "Unzer Lastschrift" -msgstr "Unzer Lastschrift" +msgstr "Unzer SEPA Lastschrift" msgid "Unzer SEPA-Lastschrift (guaranteed)" -msgstr "Unzer Lastschrift (secured)" +msgstr "(Veraltet) Unzer Direct Debit (Gesichert)" msgid "Unzer Lastschrift (secured)" -msgstr "Unzer Lastschrift (secured)" +msgstr "(Veraltet) Unzer Direct Debit (Gesichert)" + +msgid "Unzer Lastschrift (Paylater)" +msgstr "Unzer Lastschrift" msgid "Unzer Rechnung" -msgstr "Unzer Rechnung" +msgstr "(Veraltet) Unzer Rechnungskauf" msgid "Unzer Rechnung (guaranteed)" -msgstr "Unzer Rechnung (secured)" +msgstr "(Veraltet) Unzer Rechnungskauf Gesichert" + +msgid "Unzer Rechnung (secured)" +msgstr "(Veraltet) Unzer Rechnungskauf Gesichert" msgid "Unzer Fakturierung von Rechnungen" msgstr "Unzer Fakturierung von Rechnungen" @@ -68,6 +74,15 @@ msgid "Unzer FlexiPay Installment (Hire Purchase)" msgstr "Unzer FlexiPay Instalment (Hire Purchase)" msgid "Unzer Instalment" +msgstr "(Veraltet) Unzer Ratenkauf" + +msgid "Unzer Ratenkauf" +msgstr "(Veraltet) Unzer Ratenkauf" + +msgid "Unzer Rechnung (Jetzt kaufen, Später bezahlen)" +msgstr "Unzer Rechnungskauf" + +msgid "Unzer Ratenzahlung (Paylater)" msgstr "Unzer Ratenkauf" msgid "hpError" @@ -167,19 +182,19 @@ msgid "hpPaymentmethodCard" msgstr "Kreditkarte" msgid "hpPaymentmethodSEPA" -msgstr "Lastschrift" +msgstr "SEPA Lastschrift" msgid "hpPaymentmethodSEPAGuaranteed" -msgstr "Lastschrift (secured)" +msgstr "(Veraltet) Unzer Direct Debit (Gesichert)" msgid "hpPaymentmethodInvoice" -msgstr "Rechnung" +msgstr "(Veraltet) Rechnung" msgid "hpPaymentmethodInvoiceGuaranteed" -msgstr "Rechnung (secured)" +msgstr "(Veraltet) Rechnung (secured)" msgid "hpPaymentmethodInvoiceFactoring" -msgstr "Rechnungskauf" +msgstr "(Veraltet) Rechnungskauf" msgid "hpPaymentmethodPayPal" msgstr "PayPal" @@ -209,11 +224,14 @@ msgid "hpPaymentmethodiDEAL" msgstr "iDEAL" msgid "hpPaymentmethodHirePurchaseDirectDebit" -msgstr "Ratenkauf" +msgstr "(Veraltet) Ratenkauf" msgid "hpOpenInPortal" msgstr "Bestellung im Insight-Portal anzeigen" +msgid "hpOpenInPaylaterPortal" +msgstr "Im Unzer Pay Later - Merchant Portal anzeigen" + msgid "hpDelivieryAddress" msgstr "Lieferadresse" @@ -398,4 +416,141 @@ msgid "hpPaymentMethodDuringCheckoutNotification" msgstr "Die Zahlungsart \"%s\" ist vor Abschluss der Bestellung nicht verwendbar." msgid "hpPaymentMethodNotConfiguredNotification" -msgstr "Die Zahlungsart \"%s\" ist nicht konfiguriert!" \ No newline at end of file +msgstr "Die Zahlungsart \"%s\" ist nicht konfiguriert!" + +msgid "hpWarningWebhookUrlChanged" +msgstr "Die URL der Unzer Webhook-Verarbeitung hat sich geändert, dadurch kann das Plugin die Zahlungseingänge nicht mehr richtig verarbeiten. Schaue in die Dokumentation, um zu erfahren wie der Fehler behoben werden kann." + +msgid "hpWarningSyncWorkflowUrlChanged" +msgstr "Die URL der Unzer WaWi Workflow-Verarbeitung hat sich geändert, dadurch kann das Plugin Rechnungen nicht mehr richtig aktivieren. Schaue in die Dokumentation, um zu erfahren wie der Fehler behoben werden kann." + +msgid "hpApplePayRefreshCert" +msgstr "Erneuern" + +msgid "hpApplePayDownloadCert" +msgstr "CSR herunterladen" + +msgid "hpApplePayUploadCert" +msgstr "Zertifikat hochladen" + +msgid "hpApplePayUpload" +msgstr "Auswählen" + +msgid "hpApplePayPaymentGeneral" +msgstr "Allgemein" + +msgid "hpApplePayPaymentGeneralMerchantId" +msgstr "Händlerkennung" + +msgid "hpApplePayPaymentGeneralMerchantIdHelp" +msgstr "Die Händlerkennung (Merchant Identifier) welche im Apple Developer Account erstellt wurde." + +msgid "hpApplePayPaymentGeneralMerchantDomain" +msgstr "Händler/Shop-URL" + +msgid "hpApplePayPaymentGeneralMerchantDomainHelp" +msgstr "Die Händler/Shop-URL welche im Apple Developer Account für die Händlerkennung hinterlegt wurde." + +msgid "hpApplePayPaymentProcessingCertificate" +msgstr "Payment Processing Zertifikat" + +msgid "hpApplePayPaymentProcessingCertificateCSR" +msgstr "Certificate Signing Request (CSR)" + +msgid "hpApplePayPaymentProcessingCertificateCSRHelp" +msgstr "Die Certificate Signing Request (CSR) Datei zum erstellte des Apple Pay Payment Processing Zertifikat." + +msgid "hpApplePayPaymentProcessingCertificateApple" +msgstr "Apple Pay Zertifikat" + +msgid "hpApplePayPaymentProcessingCertificateAppleHelp" +msgstr "Das von Apple erstellte Payment Processing Zertifikat." + +msgid "hpApplePayMerchantIdentityCertificate" +msgstr "Merchant Identity Zertifikat" + +msgid "hpApplePayMerchantIdentityCertificateCSR" +msgstr "Certificate Signing Request (CSR)" + +msgid "hpApplePayMerchantIdentityCertificateCSRHelp" +msgstr "Die Certificate Signing Request (CSR) Datei zum erstellte des Apple Pay Merchant Identity Zertifikat." + +msgid "hpApplePayMerchantIdentityCertificateApple" +msgstr "Apple Pay Zertifikat" + +msgid "hpApplePayMerchantIdentityCertificateAppleHelp" +msgstr "Das von Apple erstellte Merchant Identity Zertifikat." + +msgid "hpApplePayUnzerIDs" +msgstr "Unzer Payment Processing Zertifikat IDs" + +msgid "hpApplePayUpdateCert" +msgstr "Zertifikat aktivieren" + +msgid "CERTIFICATE_TRANSFORMATION_ERROR" +msgstr "Zertifikat konnte nicht in Text konvertiert werden" + +msgid "ERROR_ID_LOAD_ERROR" +msgstr "Zertifikat konnte nicht geladen werden. Bitte überprüfen Sie, ob das Zertifikat gültig ist." + +msgid "hpSettingsActive" +msgstr "aktiv" + +msgid "hpSettingsAddIncomingPayments" +msgstr "Zahlungseingänge automatisch setzen" + +msgid "hpSettingsAddIncomingPaymentsHelp" +msgstr "Steuert, ob das Plugin automatisch Zahlungseingänge für die JTL-Wawi setzt.
              Deaktivieren Sie diese Option nur, wenn Sie die Zahlungseingänge auf andere Art in der JTL-Wawi setzen. (Zum Beispiel per Zahlungsabgleich oder manuell.)" + +msgid "hpDeprecationPaymentMethodTitle" +msgstr "ABSCHAFFUNG: %s" + +msgid "hpDeprecationInvoiceNotice" +msgstr "" +"Sie verwenden die Zahlungsmethode `%s`. Beachten Sie, dass diese Methode von Unzer abgeschafft wird. Sie wird derzeit noch unterstützt, aber es sind keine weiteren Entwicklungen dafür geplant.\n" +"\n" +"Der Ersatz für diese Zahlart ist die neue Zahlart `Unzer Rechnung (Jetzt kaufen, später bezahlen)`.\n" +"\n" +"Wenn Sie migrieren möchten, wenden Sie sich bitte an Ihren Ansprechpartner bei Unzer!" + +msgid "Key Pairs" +msgstr "Schlüsselpaare" + +msgid "hpKeyPairEdit" +msgstr "Schlüsselpaar bearbeiten" + +msgid "hpKeypairIsB2B" +msgstr "B2B" + +msgid "hpKeypairIsB2BHelp" +msgstr "Gibt an, ob das Schlüsselpaar nur für B2B Kunden benutzt werden soll." + +msgid "hpKeypairCurrencyHelp" +msgstr "Gibt an für welche Währung das Schlüsselpaar verwendet werden soll." + +msgid "hpKeypairPaymentMethodsHelp" +msgstr "Gibt an für welche Zahlungsart das Schlüsselpaar verwendet werden soll." + +msgid "hpSettingsPqSelectorInstalmentInfo" +msgstr "PQ-Selector für den Ratenzahlungshinweis auf Bestellbestätigungsseite" + +msgid "hpSettingsPqSelectorInstalmentInfoHelp" +msgstr "Der PHP-Query-Selektor für das Einhängen des Ratenzahlungshinweis auf der Bestellbestätigungsseite" + +msgid "hpSettingsPqMethodInstalmentInfo" +msgstr "PQ-Einfügemethode für den Ratenzahlungshinweis auf Bestellbestätigungsseite" + +msgid "hpSettingsPqMethodInstalmentInfoHelp" +msgstr "Die PHP-Query-Einfügemethode für das Einhängen des Ratenzahlungshinweis auf der Bestellbestätigungsseite" + +msgid "hpPaymentReference" +msgstr "Zahlungsreferenz" + +msgid "paylater-installment" +msgstr "Ratenkauf" + +msgid "paylater-invoice" +msgstr "Rechnungskauf" + +msgid "paylater-direct-debit" +msgstr "Lastschrift" \ No newline at end of file diff --git a/locale/en-GB/base.mo b/locale/en-GB/base.mo index 3838d9e..d26514f 100644 Binary files a/locale/en-GB/base.mo and b/locale/en-GB/base.mo differ diff --git a/locale/en-GB/base.po b/locale/en-GB/base.po index 0059bfe..93799b2 100644 --- a/locale/en-GB/base.po +++ b/locale/en-GB/base.po @@ -11,22 +11,25 @@ msgid "Unzer SEPA-Lastschrift" msgstr "Unzer SEPA Direct Debit" msgid "Unzer Lastschrift" -msgstr "Unzer Direct Debit" +msgstr "Unzer SEPA Direct Debit" msgid "Unzer SEPA-Lastschrift (guaranteed)" -msgstr "Unzer SEPA Direct Debit (secured)" +msgstr "(Deprecated) Unzer SEPA Direct Debit (secured)" msgid "Unzer Lastschrift (secured)" -msgstr "Unzer Direct Debit (secured)" +msgstr "(Deprecated) Unzer Direct Debit (secured)" + +msgid "Unzer Lastschrift (Paylater)" +msgstr "Unzer Direct Debit" msgid "Unzer Rechnung" -msgstr "Unzer Invoice" +msgstr "(Deprecated) Unzer Invoice" msgid "Unzer Rechnung (guaranteed)" -msgstr "Unzer Ivoice (secured)" +msgstr "(Deprecated) Unzer Invoice Secured" msgid "Unzer Rechnung (secured)" -msgstr "Unzer Ivoice (secured)" +msgstr "(Deprecated) Unzer Invoice Secured" msgid "Unzer Fakturierung von Rechnungen" msgstr "Unzer Invoice Factoring" @@ -74,10 +77,16 @@ msgid "Unzer FlexiPay Installment (Hire Purchase)" msgstr "Unzer FlexiPay Instalment (Hire Purchase)" msgid "Unzer Instalment" -msgstr "Unzer Instalment" +msgstr "(Deprecated) Unzer Installment" msgid "Unzer Ratenkauf" -msgstr "Unzer Instalment" +msgstr "(Deprecated) Unzer Instalment" + +msgid "Unzer Rechnung (Jetzt kaufen, Später bezahlen)" +msgstr "Unzer Invoice" + +msgid "Unzer Ratenzahlung (Paylater)" +msgstr "Unzer Installment" msgid "hpError" msgstr "Error" @@ -176,19 +185,19 @@ msgid "hpPaymentmethodCard" msgstr "Credit Card" msgid "hpPaymentmethodSEPA" -msgstr "Direct Debit" +msgstr "SEPA Direct Debit" msgid "hpPaymentmethodSEPAGuaranteed" -msgstr "Direct Debit (secured)" +msgstr "(Deprecated) Direct Debit (secured)" msgid "hpPaymentmethodInvoice" -msgstr "Invoice" +msgstr "(Deprecated) Invoice" msgid "hpPaymentmethodInvoiceGuaranteed" -msgstr "Invoice (secured)" +msgstr "(Deprecated) Invoice (secured)" msgid "hpPaymentmethodInvoiceFactoring" -msgstr "Invoice (factoring)" +msgstr "(Deprecated) Invoice (factoring)" msgid "hpPaymentmethodPayPal" msgstr "PayPal" @@ -218,11 +227,20 @@ msgid "hpPaymentmethodiDEAL" msgstr "iDEAL" msgid "hpPaymentmethodHirePurchaseDirectDebit" -msgstr "Instalment" +msgstr "(Deprecated) Instalment" + +msgid "paylater-invoice" +msgstr "Invoice" + +msgid "paylater-installment" +msgstr "Installment" msgid "hpOpenInPortal" msgstr "Open Order in Insight Portal" +msgid "hpOpenInPaylaterPortal" +msgstr "Open in Unzer Pay Later - Merchant Portal" + msgid "hpDelivieryAddress" msgstr "Deliviery Address" @@ -407,4 +425,153 @@ msgid "hpPaymentMethodDuringCheckoutNotification" msgstr "The payment method \"%s\" is not usable before order completion." msgid "hpPaymentMethodNotConfiguredNotification" -msgstr "The payment method \"%s\" is not configured!" \ No newline at end of file +msgstr "The payment method \"%s\" is not configured!" + +msgid "hpWarningWebhookUrlChanged" +msgstr "The URL of the Unzer Webhook Handling page has changed, so the plugin can no longer process incoming payments correctly. See the documentation to find out how to fix the error" + +msgid "hpWarningSyncWorkflowUrlChanged" +msgstr "The URL of the Unzer WaWi Workflow Handling page has changed, so the plugin can no longer activate invoices correctly. See the documentation to find out how to fix the error" + +msgid "hpApplePayRefreshCert" +msgstr "Refresh" + +msgid "hpApplePayDownloadCert" +msgstr "Download CSR" + +msgid "hpApplePayUploadCert" +msgstr "Upload Certificate" + +msgid "hpApplePayUpload" +msgstr "Browse" + +msgid "hpApplePayPaymentGeneral" +msgstr "Allgemein" + +msgid "hpApplePayPaymentGeneralMerchantId" +msgstr "Merchant Identifier" + +msgid "hpApplePayPaymentGeneralMerchantIdHelp" +msgstr "The merchant identifier created in the Apple Developer Account." + +msgid "hpApplePayPaymentGeneralMerchantDomain" +msgstr "Merchant Domain" + +msgid "hpApplePayPaymentGeneralMerchantDomainHelp" +msgstr "The merchant/shop URL that was saved in the Apple Developer Account to use with the merchant ID." + +msgid "hpApplePayPaymentProcessingCertificate" +msgstr "Payment Processing Certificate" + +msgid "hpApplePayPaymentProcessingCertificateCSR" +msgstr "Certificate Signing Request (CSR)" + +msgid "hpApplePayPaymentProcessingCertificateCSRHelp" +msgstr "The Certificate Signing Request (CSR) file to create the Apple Pay Payment Processing certificate." + +msgid "hpApplePayPaymentProcessingCertificateApple" +msgstr "Apple Pay Certificate" + +msgid "hpApplePayPaymentProcessingCertificateAppleHelp" +msgstr "The Payment Processing Certificate created by Apple." + +msgid "hpApplePayMerchantIdentityCertificate" +msgstr "Merchant Identity Certificate" + +msgid "hpApplePayMerchantIdentityCertificateCSR" +msgstr "Certificate Signing Request (CSR)" + +msgid "hpApplePayMerchantIdentityCertificateCSRHelp" +msgstr "The Certificate Signing Request (CSR) file to create the Apple Pay Merchant Identity certificate." + +msgid "hpApplePayMerchantIdentityCertificateApple" +msgstr "Apple Pay Certificate" + +msgid "hpApplePayMerchantIdentityCertificateAppleHelp" +msgstr "The Merchant Indentity Certificate created by Apple." + +msgid "hpApplePayUnzerIDs" +msgstr "Unzer Payment Processing Certificate IDs" + +msgid "hpApplePayUpdateCert" +msgstr "Activate Certificate" + +msgid "CERTIFICATE_TRANSFORMATION_ERROR" +msgstr "Certificate could not be converted to text" + +msgid "ERROR_ID_LOAD_ERROR" +msgstr "Certificate could not be loaded. Please check if the certificate is valid." + +msgid "hpSettingsActive" +msgstr "active" + +msgid "hpSettingsAddIncomingPayments" +msgstr "Add Incoming Payments" + +msgid "hpSettingsAddIncomingPaymentsHelp" +msgstr "Controls whether the plugin sets incoming payments automatically for JTL-Wawi.
              You should only ever deactivate this option if you set your incoming payments in JTL-Wawi in a different way (e.g. manually or via the payment synchronisation module.)" + +msgid "hpDeprecationPaymentMethodTitle" +msgstr "DEPRECATION: %s" + +msgid "hpDeprecationInvoiceNotice" +msgstr "" +"You are using the payment method `%s`, note that this method is now deprecated by Unzer. It is currently supported, but there are no further developments planned for it.\n" +"\n" +"The replacement for this payment method is the new `Unzer Invoice (Buy Now Pay Later)` payment method..\n" +"\n" +"If you want to migrate, please get in touch with your contact person at Unzer!" + +msgid "Ungültiger Private Key." +msgstr "Invalid private key." + +msgid "Ungültiger Public Key. Bitte stellen Sie sicher, dass sie hier Ihren Public Key und nicht Ihren Private Key angeben!" +msgstr "Invalid public key. Please make sure that you enter your public key here and not your private key!" + +msgid "Die Webhooks wurden erfolgreich gespeichert." +msgstr "The webhooks have been saved successfully." + +msgid "Key Pairs" +msgstr "Key Pairs" + +msgid "hpKeyPairEdit" +msgstr "Edit Key Pair" + +msgid "hpKeypairIsB2B" +msgstr "B2B" + +msgid "hpKeypairIsB2BHelp" +msgstr "Specifies whether the key pair is to be used only for B2B clients." + +msgid "hpKeypairCurrencyHelp" +msgstr "Specifies for which currency the key pair is to be used." + +msgid "hpKeypairPaymentMethodsHelp" +msgstr "Specifies for which payment type the key pair is to be used." + +msgid "hpSettingsPqSelectorInstallmentInfo" +msgstr "PQ-Selector for instalment information on the order confirm page" + +msgid "hpSettingsPqSelectorInstallmentInfoHelp" +msgstr "The PHP Query Selector for the injection of the instalment information on the order confirm page" + +msgid "hpSettingsPqMethodInstallmentInfo" +msgstr "PQ-Method for instalment information on the order confirm page" + +msgid "hpSettingsPqMethodInstallmentInfoHelp" +msgstr "The PHP Query Method for the injection of the instalment information on the order confirm page" + +msgid "hpPaymentReference" +msgstr "Payment Reference" + +msgid "paylater-direct-debit" +msgstr "Direct Debit" + +msgid "Hinzufügen" +msgstr "Add" + +msgid "Die Einstellungen wurden erfolgreich gespeichert." +msgstr "The settings have been saved successfully." + +msgid "Dokumentation" +msgstr "Documentation" diff --git a/paymentmethod/HeidelpayAlipay.php b/paymentmethod/HeidelpayAlipay.php index e95d739..188de20 100644 --- a/paymentmethod/HeidelpayAlipay.php +++ b/paymentmethod/HeidelpayAlipay.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayCreditCard.php b/paymentmethod/HeidelpayCreditCard.php index 7fafcb7..48d726f 100644 --- a/paymentmethod/HeidelpayCreditCard.php +++ b/paymentmethod/HeidelpayCreditCard.php @@ -1,4 +1,5 @@ cGueltigkeit = Text::convertUTF8($type->getExpiryDate() ?? ''); $oPaymentInfo->cCVV = Text::convertUTF8($type->getCvc() ?? ''); $oPaymentInfo->cKartenTyp = Text::convertUTF8($type->getBrand() ?? ''); + $oPaymentInfo->cBankName = ''; + $oPaymentInfo->cKartenNr = ''; + $oPaymentInfo->cCVV = ''; + isset($oPaymentInfo->kZahlungsInfo) ? $oPaymentInfo->updateInDB() : $oPaymentInfo->insertInDB(); @@ -82,7 +91,7 @@ public function getOrderAttributes(Bestellung $order, AbstractTransactionType $t } catch (Exception $exc) { $this->errorLog( 'An exception was thrown while trying to get the order attributes ' - . Text::convertUTF8($exc->getMessage()), + . Text::convertUTF8($exc->getMessage()), static::class ); } @@ -115,15 +124,26 @@ public function handleStepAdditional(JTLSmarty $view): void * @inheritDoc * @return AbstractTransactionType|Charge */ - protected function performTransaction(BasePaymentType $payment, $order): AbstractTransactionType + protected function performTransaction(BasePaymentType $payment, Bestellung $order): AbstractTransactionType { - return $this->adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayEPS.php b/paymentmethod/HeidelpayEPS.php index 53a6e4d..400e7df 100644 --- a/paymentmethod/HeidelpayEPS.php +++ b/paymentmethod/HeidelpayEPS.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayFlexiPayDirect.php b/paymentmethod/HeidelpayFlexiPayDirect.php index 31c4521..35937c0 100644 --- a/paymentmethod/HeidelpayFlexiPayDirect.php +++ b/paymentmethod/HeidelpayFlexiPayDirect.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getApi()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getApi()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } + + /** + * @inheritDoc + */ + public function isValid(object $customer, Cart $cart): bool + { + //! Note: Payment Method is deprecated -> should not be used anymore + return false; + } + + /** + * @inheritDoc + */ + public function isSelectable(): bool + { + //! Note: Payment Method is deprecated -> should not be used anymore + return false; + } } diff --git a/paymentmethod/HeidelpayGiropay.php b/paymentmethod/HeidelpayGiropay.php index f60cdb8..bb95268 100644 --- a/paymentmethod/HeidelpayGiropay.php +++ b/paymentmethod/HeidelpayGiropay.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayHirePurchaseDirectDebit.php b/paymentmethod/HeidelpayHirePurchaseDirectDebit.php index 3a97b34..acacace 100644 --- a/paymentmethod/HeidelpayHirePurchaseDirectDebit.php +++ b/paymentmethod/HeidelpayHirePurchaseDirectDebit.php @@ -1,4 +1,5 @@ cBIC = Text::convertUTF8($type->getBic() ?? ''); $oPaymentInfo->cKontoNr = $oPaymentInfo->cIBAN; $oPaymentInfo->cBLZ = $oPaymentInfo->cBIC; + $oPaymentInfo->cBankName = ''; + $oPaymentInfo->cKartenNr = ''; + $oPaymentInfo->cCVV = ''; isset($oPaymentInfo->kZahlungsInfo) ? $oPaymentInfo->updateInDB() : $oPaymentInfo->insertInDB(); @@ -148,12 +156,30 @@ public function handleStepAdditional(JTLSmarty $view): void $this->sessionHelper->getFrontendSession()->getCart()->gibGesamtsummeWaren(true), 2 ); - $data['currency'] = $this->sessionHelper->getFrontendSession()->getCurrency()->cISO; + $data['currency'] = $this->sessionHelper->getFrontendSession()->getCurrency()->getCode(); $data['orderDate'] = date('Y-m-d'); $view->assign('hpPayment', $data); } + /** + * @inheritDoc + */ + public function isValid(object $customer, Cart $cart): bool + { + //! Note: Payment Method is deprecated -> should not be used anymore + return false; + } + + /** + * @inheritDoc + */ + public function isSelectable(): bool + { + //! Note: Payment Method is deprecated -> should not be used anymore + return false; + } + /** * Check if payment settings are correct. * @inheritDoc @@ -205,8 +231,8 @@ public function handleStepReviewOrder(JTLSmarty $view): ?string $this->handler->prepareView(); try { - $paymentId = $this->sessionHelper->get(SessionHelper::KEY_PAYMENT_ID, ''); - $payment = $this->adapter->getApi()->fetchPayment($paymentId); + $paymentId = $this->sessionHelper->get(SessionHelper::KEY_PAYMENT_ID); + $payment = $this->adapter->getCurrentConnection()->fetchPayment($paymentId); // If currency or basket change, redirect to select payment screen to reauthorize new amounts! if ($this->handler->currencyChanged($payment) || $this->handler->basketChanged($payment)) { @@ -312,7 +338,13 @@ private function authorizeInstalmentTransaction(): bool { // We need to register an order id here otherwise the auth call will fail! // @see: BillPay for similiar behavior - $orderId = \baueBestellnummer(); + if (Compatibility::isShopAtLeast52()) { + $orderId = $this->sessionHelper->get(SessionHelper::KEY_ORDER_ID) ?? getOrderHandler()->createOrderNo(); + } else { + $orderId = $this->sessionHelper->get(SessionHelper::KEY_ORDER_ID) ?? \baueBestellnummer(); + } + + $this->sessionHelper->set(SessionHelper::KEY_ORDER_ID, $orderId); // Create or fetch customer resource $session = $this->sessionHelper->getFrontendSession(); @@ -329,7 +361,7 @@ private function authorizeInstalmentTransaction(): bool // Update existing customer resource if needed if ($customer->getId()) { - $customer = $this->adapter->getApi()->updateCustomer($customer); + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); $this->debugLog('Updated Customer Resource: ' . $customer->jsonSerialize(), static::class); } @@ -343,13 +375,16 @@ private function authorizeInstalmentTransaction(): bool $paymentType = $this->adapter->fetchPaymentType(); // Authorize Transaction - $authorization = $this->adapter->getApi()->authorize( + $auth = (new Authorization( $paymentType->getTotalPurchaseAmount(), - $session->getCurrency()->cISO, + $session->getCurrency()->getCode(), + Shop::Container()->getLinkService()->getStaticRoute('bestellvorgang.php') + ))->setOrderId($orderId); + + $authorization = $this->adapter->getCurrentConnection()->performAuthorization( + $auth, $paymentType, - Shop::Container()->getLinkService()->getStaticRoute('bestellvorgang.php'), $customer, - $orderId, $this->createMetadata(), $basket ); @@ -372,7 +407,7 @@ private function authorizeInstalmentTransaction(): bool $this->sessionHelper->redirectError( Text::convertUTF8($authorization->getMessage()->getCustomer()), 'heidelpayTransactionError', - PaymentHandler::REDIRECT_ON_FAILURE_URL + PaymentHandler::REDIRECT_TO_PAYMENT_SELECTION_URL ); } catch (UnzerApiException $exc) { $msg = $exc->getMerchantMessage() . ' | Id: ' . $exc->getErrorId() . ' | Code: ' . $exc->getCode(); @@ -380,7 +415,7 @@ private function authorizeInstalmentTransaction(): bool $this->sessionHelper->redirectError( Text::convertUTF8($exc->getClientMessage()), 'UnzerApiException', - PaymentHandler::REDIRECT_ON_FAILURE_URL + PaymentHandler::REDIRECT_TO_PAYMENT_SELECTION_URL ); } catch (RuntimeException $exc) { $this->errorLog( @@ -390,14 +425,14 @@ private function authorizeInstalmentTransaction(): bool $this->sessionHelper->redirectError( $this->trans(Config::LANG_PAYMENT_PROCESS_RUNTIME_EXCEPTION), 'paymentRuntimeException', - PaymentHandler::REDIRECT_ON_FAILURE_URL + PaymentHandler::REDIRECT_TO_PAYMENT_SELECTION_URL ); } catch (Exception $exc) { $this->errorLog('An error occured in the payment process: ' . $exc->getMessage(), static::class); $this->sessionHelper->redirectError( $this->trans(Config::LANG_PAYMENT_PROCESS_EXCEPTION), 'paymentRuntimeException', - PaymentHandler::REDIRECT_ON_FAILURE_URL + PaymentHandler::REDIRECT_TO_PAYMENT_SELECTION_URL ); } } diff --git a/paymentmethod/HeidelpayInvoice.php b/paymentmethod/HeidelpayInvoice.php index db3d475..3bb2549 100644 --- a/paymentmethod/HeidelpayInvoice.php +++ b/paymentmethod/HeidelpayInvoice.php @@ -1,15 +1,20 @@ plugin->getPaymentMethods()->getMethodByID($this->moduleID); + + if ($payMethod !== null && $payMethod->getActive()) { + $this->kZahlungsart = $payMethod->getMethodID(); + $result = Shop::Container()->getDB()->select('tversandartzahlungsart', 'kZahlungsart', $this->kZahlungsart); + + if ($result) { + $notification = new NotificationEntry( + NotificationEntry::TYPE_INFO, + sprintf(__('hpDeprecationPaymentMethodTitle'), $payMethod->getName()), + sprintf(nl2br(__('hpDeprecationInvoiceNotice')), $payMethod->getName()) + ); + + $notification->setPluginId((string) $this->plugin->getID()); + Notification::getInstance()->addNotify($notification); + } + } + } + + /** + * @inheritDoc + */ + public function isSelectable(): bool + { + // Add deprecation notice log IF payment method is selectable (ie being actively used) + $isSelectable = parent::isSelectable(); + $payMethod = $this->plugin->getPaymentMethods()->getMethodByID($this->moduleID); + + if ($isSelectable && $payMethod !== null && $payMethod->getActive()) { + $this->noticeLog( + sprintf(nl2br(__('hpDeprecationInvoiceNotice')), $payMethod->getName()) + ); + } + + return $isSelectable; + } /** * Data the merchant needs to put on the Invoice. @@ -53,6 +103,9 @@ public function getOrderAttributes(Bestellung $order, AbstractTransactionType $t $oPaymentInfo->cKontoNr = $oPaymentInfo->cIBAN; $oPaymentInfo->cBLZ = $oPaymentInfo->cBIC; $oPaymentInfo->cVerwendungszweck = Text::convertUTF8($transaction->getDescriptor() ?? ''); + $oPaymentInfo->cBankName = ''; + $oPaymentInfo->cKartenNr = ''; + $oPaymentInfo->cCVV = ''; isset($oPaymentInfo->kZahlungsInfo) ? $oPaymentInfo->updateInDB() : $oPaymentInfo->insertInDB(); @@ -68,15 +121,26 @@ public function getOrderAttributes(Bestellung $order, AbstractTransactionType $t * @inheritDoc * @return AbstractTransactionType|Charge */ - protected function performTransaction(BasePaymentType $payment, $order): AbstractTransactionType + protected function performTransaction(BasePaymentType $payment, Bestellung $order): AbstractTransactionType { - return $this->adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayInvoiceFactoring.php b/paymentmethod/HeidelpayInvoiceFactoring.php index 8553cc7..37d6376 100644 --- a/paymentmethod/HeidelpayInvoiceFactoring.php +++ b/paymentmethod/HeidelpayInvoiceFactoring.php @@ -1,4 +1,5 @@ debugLog('Basket Resource: ' . $basket->jsonSerialize(), static::class); - return $this->adapter->getApi()->charge( + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getApi()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), $customer, - $order->cBestellNr ?? null, $this->createMetadata(), $basket ); diff --git a/paymentmethod/HeidelpayInvoiceGuaranteed.php b/paymentmethod/HeidelpayInvoiceGuaranteed.php index 7a7b61c..14a205c 100644 --- a/paymentmethod/HeidelpayInvoiceGuaranteed.php +++ b/paymentmethod/HeidelpayInvoiceGuaranteed.php @@ -1,9 +1,11 @@ cancel(null, CancelReasonCodes::REASON_CODE_CANCEL); + $reference = str_replace( + ['%ORDER_ID%', '%SHOPNAME%'], + [$order->cBestellNr, Shop::getSettingValue(CONF_GLOBAL, 'global_shopname')], + $this->trans(Config::LANG_CANCEL_PAYMENT_REFERENCE) + ); + + return $transaction->cancel(null, CancelReasonCodes::REASON_CODE_CANCEL, $reference); } /** @@ -63,12 +73,14 @@ public function cancelPaymentTransaction( */ public function handleStepAdditional(JTLSmarty $view): void { + $this->adapter->getConnectionForSession(); $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); $customer = $this->createOrFetchHeidelpayCustomer( $this->adapter, $this->sessionHelper, $this->isB2BCustomer($shopCustomer) ); + $customer->setShippingAddress( $this->createHeidelpayAddress( $this->sessionHelper->getFrontendSession()->get('Lieferadresse') @@ -110,7 +122,7 @@ public function validateAdditional(): bool * @inheritDoc * @return AbstractTransactionType|Charge */ - protected function performTransaction(BasePaymentType $payment, $order): AbstractTransactionType + protected function performTransaction(BasePaymentType $payment, Bestellung $order): AbstractTransactionType { // Create or fetch customer resource $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); @@ -125,7 +137,7 @@ protected function performTransaction(BasePaymentType $payment, $order): Abstrac // Update existing customer resource if needed if ($customer->getId()) { - $customer = $this->adapter->getApi()->updateCustomer($customer); + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); $this->debugLog('Updated Customer Resource: ' . $customer->jsonSerialize(), static::class); } @@ -139,13 +151,17 @@ protected function performTransaction(BasePaymentType $payment, $order): Abstrac ); $this->debugLog('Basket Resource: ' . $basket->jsonSerialize(), static::class); - return $this->adapter->getApi()->charge( + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), $customer, - $order->cBestellNr ?? null, $this->createMetadata(), $basket ); diff --git a/paymentmethod/HeidelpayPayPal.php b/paymentmethod/HeidelpayPayPal.php index 7299e8a..80b7c76 100644 --- a/paymentmethod/HeidelpayPayPal.php +++ b/paymentmethod/HeidelpayPayPal.php @@ -1,8 +1,10 @@ createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); @@ -47,16 +49,20 @@ protected function performTransaction(BasePaymentType $payment, $order): Abstrac // Update existing customer resource if needed if ($customer->getId()) { - $customer = $this->adapter->getApi()->updateCustomer($customer); + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); } - return $this->adapter->getApi()->charge( + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), $customer, - $order->cBestellNr ?? null, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayPrepayment.php b/paymentmethod/HeidelpayPrepayment.php index 4ded596..578d665 100644 --- a/paymentmethod/HeidelpayPrepayment.php +++ b/paymentmethod/HeidelpayPrepayment.php @@ -1,4 +1,5 @@ cKontoNr = $oPaymentInfo->cIBAN; $oPaymentInfo->cBLZ = $oPaymentInfo->cBIC; $oPaymentInfo->cVerwendungszweck = Text::convertUTF8($transaction->getDescriptor() ?? ''); + $oPaymentInfo->cBankName = ''; + $oPaymentInfo->cKartenNr = ''; + $oPaymentInfo->cCVV = ''; isset($oPaymentInfo->kZahlungsInfo) ? $oPaymentInfo->updateInDB() : $oPaymentInfo->insertInDB(); @@ -70,15 +76,26 @@ public function getOrderAttributes(Bestellung $order, AbstractTransactionType $t * @inheritDoc * @return AbstractTransactionType|Charge */ - protected function performTransaction(BasePaymentType $payment, $order): AbstractTransactionType + protected function performTransaction(BasePaymentType $payment, Bestellung $order): AbstractTransactionType { - return $this->adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayPrzelewy24.php b/paymentmethod/HeidelpayPrzelewy24.php index dcc570c..3ffc6dd 100644 --- a/paymentmethod/HeidelpayPrzelewy24.php +++ b/paymentmethod/HeidelpayPrzelewy24.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpaySEPADirectDebit.php b/paymentmethod/HeidelpaySEPADirectDebit.php index de4da70..eae63f6 100644 --- a/paymentmethod/HeidelpaySEPADirectDebit.php +++ b/paymentmethod/HeidelpaySEPADirectDebit.php @@ -1,8 +1,10 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpaySEPADirectDebitGuaranteed.php b/paymentmethod/HeidelpaySEPADirectDebitGuaranteed.php index db4c691..a1e648b 100644 --- a/paymentmethod/HeidelpaySEPADirectDebitGuaranteed.php +++ b/paymentmethod/HeidelpaySEPADirectDebitGuaranteed.php @@ -1,4 +1,5 @@ cancel(null, CancelReasonCodes::REASON_CODE_CANCEL); + $reference = str_replace( + ['%ORDER_ID%', '%SHOPNAME%'], + [$order->cBestellNr, Shop::getSettingValue(CONF_GLOBAL, 'global_shopname')], + $this->trans(Config::LANG_CANCEL_PAYMENT_REFERENCE) + ); + + return $transaction->cancel(null, CancelReasonCodes::REASON_CODE_CANCEL, $reference); } /** @@ -72,6 +82,7 @@ public function cancelPaymentTransaction( */ public function handleStepAdditional(JTLSmarty $view): void { + $this->adapter->getConnectionForSession(); $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); $customer = $this->createOrFetchHeidelpayCustomer( $this->adapter, @@ -148,7 +159,7 @@ protected function performTransaction(BasePaymentType $payment, $order): Abstrac // Update existing customer resource if needed if ($customer->getId()) { - $customer = $this->adapter->getApi()->updateCustomer($customer); + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); $this->debugLog('Updated Customer Resource: ' . $customer->jsonSerialize(), static::class); } @@ -158,17 +169,21 @@ protected function performTransaction(BasePaymentType $payment, $order): Abstrac $session->getCart(), $order->Waehrung, $session->getLanguage(), - $payment->getId() + $order->cBestellNr ?? $payment->getId() ); $this->debugLog('Basket Resource: ' . $basket->jsonSerialize(), static::class); - return $this->adapter->getApi()->charge( + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), $customer, - $order->cBestellNr ?? null, $this->createMetadata(), $basket ); diff --git a/paymentmethod/HeidelpaySofort.php b/paymentmethod/HeidelpaySofort.php index de3fca9..4add54e 100644 --- a/paymentmethod/HeidelpaySofort.php +++ b/paymentmethod/HeidelpaySofort.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayWeChatPay.php b/paymentmethod/HeidelpayWeChatPay.php index 4f304e5..e3178d0 100644 --- a/paymentmethod/HeidelpayWeChatPay.php +++ b/paymentmethod/HeidelpayWeChatPay.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/HeidelpayiDEAL.php b/paymentmethod/HeidelpayiDEAL.php index dc4adf9..4983cba 100644 --- a/paymentmethod/HeidelpayiDEAL.php +++ b/paymentmethod/HeidelpayiDEAL.php @@ -1,13 +1,16 @@ adapter->getApi()->charge( + // Create / Update existing customer resource if needed + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( $this->getTotalPriceCustomerCurrency($order), - $order->Waehrung->cISO, + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, $payment->getId(), - $this->getReturnURL($order), - null, - $order->cBestellNr ?? null, + $customer, $this->createMetadata() ); } diff --git a/paymentmethod/UnzerApplePay.php b/paymentmethod/UnzerApplePay.php new file mode 100644 index 0000000..f54613d --- /dev/null +++ b/paymentmethod/UnzerApplePay.php @@ -0,0 +1,142 @@ +getTemplateVars('hpPayment') ?: []; + $session = $this->sessionHelper->getFrontendSession(); + $countryCode = end(explode('-', $data['locale'])); + + $data['snippets'] = [ + 'NOT_SUPPORTED' => $this->plugin->getLocalization()->getTranslation(Config::LANG_APPLE_PAY_NOT_SUPPORTED) + ?? Config::LANG_APPLE_PAY_NOT_SUPPORTED, + 'CANCEL_BY_USER' => $this->plugin->getLocalization()->getTranslation(Config::LANG_APPLE_PAY_CANCEL_BY_USER) + ?? Config::LANG_APPLE_PAY_CANCEL_BY_USER + ]; + + $data['paymentRequest'] = [ + 'countryCode' => $countryCode, + 'currencyCode' => $session->getCurrency()->getCode(), + 'supportedNetworks' => ['visa', 'masterCard'], + 'merchantCapabilities' => ['supports3DS'], + 'total' => [ + 'label' => Shop::getSettingValue(\CONF_GLOBAL, 'global_shopname'), + 'amount' => round($session->getCart()->gibGesamtsummeWaren(true), 2), + ], + 'lineItems' => $this->createApplePayLineItems( + $session->getCart(), + $session->getCurrency(), + $session->getLanguage() + ), + ]; + + $view->assign('hpPayment', $data); + } + + /** + * Checks if apple pay method is fully configured + * + * @param array $args + * @return boolean + */ + public function isValidIntern($args = []): bool + { + try { + /** @var CertificationService $certService */ + $certService = Shop::Container()->get(CertificationService::class); + + /** @var Config $config */ + $config = Shop::Container()->get(Config::class); + + $merchantId = $config->get(Config::APPLEPAY_MERCHANT_IDENTIFIER); + $merchantDomain = $config->get(Config::APPLEPAY_MERCHANT_DOMAIN); + $merchantCert = $certService->get(Config::APPLEPAY_MERCHANT_SIGNED_PEM); + $merchantPrivateKey = $certService->get(Config::APPLEPAY_MERCHANT_PRIVATE_KEY); + $paymentCert = $certService->get(Config::APPLEPAY_PAYMENT_SIGNED_PEM); + $paymentPrivateKey = $certService->get(Config::APPLEPAY_PAYMENT_PRIVATE_KEY); + + if ( + empty($merchantId) || empty($merchantDomain) || + empty($merchantCert) || empty($merchantPrivateKey) || + empty($paymentCert) || empty($paymentPrivateKey) + ) { + $this->debugLog('ApplePay Payment Method not fully configured', self::class); + return false; + } + } catch (Exception $exc) { + $this->errorLog( + 'An error occured while validating apple pay payment method: ' . $exc->getMessage(), + self::class + ); + + return false; + } + + return parent::isValidIntern($args); + } + + /** + * @inheritDoc + * @return AbstractTransactionType|Charge + */ + protected function performTransaction(BasePaymentType $payment, $order): AbstractTransactionType + { + // Create a customer with shipping address for Paypal's Buyer Protection + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + $customer->setShippingAddress($this->createHeidelpayAddress($order->Lieferadresse)); + $customer->setBillingAddress($this->createHeidelpayAddress($order->oRechnungsadresse)); + + // Update existing customer resource if needed + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( + $this->getTotalPriceCustomerCurrency($order), + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, + $payment->getId(), + $customer, + $this->createMetadata() + ); + } +} diff --git a/paymentmethod/UnzerBancontact.php b/paymentmethod/UnzerBancontact.php new file mode 100644 index 0000000..2a3a582 --- /dev/null +++ b/paymentmethod/UnzerBancontact.php @@ -0,0 +1,80 @@ +get(Config::class); + $data = $view->getTemplateVars('hpPayment') ?: []; + + $data['styling'] = [ + Config::FONT_COLOR => $config->get(Config::FONT_COLOR), + Config::FONT_FAMILY => $config->get(Config::FONT_FAMILY), + Config::FONT_SIZE => $config->get(Config::FONT_SIZE), + ]; + + $view->assign('hpPayment', $data); + } + + /** + * @inheritDoc + * @return AbstractTransactionType|Charge + */ + protected function performTransaction(BasePaymentType $payment, $order): AbstractTransactionType + { + // Create a customer with shipping address for Paypal's Buyer Protection + $customer = $this->createOrFetchHeidelpayCustomer($this->adapter, $this->sessionHelper, false); + $customer->setShippingAddress($this->createHeidelpayAddress($order->Lieferadresse)); + $customer->setBillingAddress($this->createHeidelpayAddress($order->oRechnungsadresse)); + + // Update existing customer resource if needed + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + } + + $charge = new Charge( + $this->getTotalPriceCustomerCurrency($order), + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $charge->setOrderId($order->cBestellNr ?? null); + + return $this->adapter->getCurrentConnection()->performCharge( + $charge, + $payment->getId(), + $customer, + $this->createMetadata() + ); + } +} diff --git a/paymentmethod/UnzerPaylaterDirectDebit.php b/paymentmethod/UnzerPaylaterDirectDebit.php new file mode 100644 index 0000000..e885b41 --- /dev/null +++ b/paymentmethod/UnzerPaylaterDirectDebit.php @@ -0,0 +1,216 @@ +adapter->getConnectionForOrder($order); + + $reference = str_replace( + ['%ORDER_ID%', '%SHOPNAME%'], + [$order->cBestellNr, Shop::getSettingValue(CONF_GLOBAL, 'global_shopname')], + $this->trans(Config::LANG_CANCEL_PAYMENT_REFERENCE) + ); + + $cancel = (new Cancellation($transaction->getAmount()))->setPaymentReference($reference); + + // Cancel before charge (reversal) + if ($transaction instanceof Authorization) { + return $api->cancelAuthorizedPayment($payment, $cancel); + } + + // Cancel after charge (refund) + return $api->cancelChargedPayment($payment, $cancel); + } + + /** + * Save the payment reference and some other bank data. + * + * @param Bestellung $order + * @param Authorization $transaction + * @return array + */ + public function getOrderAttributes(Bestellung $order, AbstractTransactionType $transaction): array + { + return [ + self::ATTR_IBAN => $transaction->getIban(), + self::ATTR_BIC => $transaction->getBic(), + self::ATTR_TRANSACTION_DESCRIPTOR => $transaction->getDescriptor(), + self::ATTR_ACCOUNT_HOLDER => $transaction->getHolder() + ]; + } + + /** + * Different billing and shipping address is allowed, BUT first and last name should be the same. + * + * @return bool + */ + public function isSelectable(): bool + { + // @see: https://unz.atlassian.net/browse/S360-21?focusedCommentId=322832 + // if (isset($_SESSION['Bestellung']->kLieferadresse) && $_SESSION['Bestellung']->kLieferadresse == -1) { + // /** @var Lieferadresse $shipping */ + // $shipping = $this->sessionHelper->getFrontendSession()->get('Lieferadresse'); + // $billing = $this->sessionHelper->getFrontendSession()->getCustomer(); + + // if ($shipping->cVorname !== $billing->cVorname || $shipping->cNachname !== $billing->cNachname) { + // $this->debugLog( + // 'Hide Unzer Paylater Direct Debit as the names for shipping and billing address are different.', + // static::class + // ); + // return false; + // } + // } + if ( + $this->isB2BCustomer($this->sessionHelper->getFrontendSession()->getCustomer()) || + $this->sessionHelper->getFrontendSession()->getCurrency()->getCode() !== 'EUR' + ) { + return false; + } + + return parent::isSelectable(); + } + + /** + * Add Customer Resource to view. + * + * @param JTLSmarty $view + * @return void + */ + public function handleStepAdditional(JTLSmarty $view): void + { + $this->adapter->getConnectionForSession(); + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + $customer = $this->createOrFetchHeidelpayCustomer( + $this->adapter, + $this->sessionHelper, + $this->isB2BCustomer($shopCustomer) + ); + $customer->setShippingAddress( + $this->createHeidelpayAddress( + $this->sessionHelper->getFrontendSession()->get('Lieferadresse') + ) + ); + + $data = $view->getTemplateVars('hpPayment') ?: []; + $data['customer'] = $customer; + $data['isB2B'] = $this->isB2BCustomer($shopCustomer); + + $view->assign('hpPayment', $data); + } + + /** + * Generate and add threat metrix id (fraud prevention). + * + * @param JTLSmarty $view + * @return null|string + */ + public function handleStepReviewOrder(JTLSmarty $view): ?string + { + $data = $view->getTemplateVars('hpPayment') ?: []; + $data['threatMetrixId'] = $this->sessionHelper->generateThreatMetrixId(); + $view->assign('hpPayment', $data); + + return 'template/partials/_threatMetrix'; + } + + protected function performTransaction(BasePaymentType $payment, Bestellung $order): AbstractTransactionType + { + // Create or fetch customer resource + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + $customer = $this->createOrFetchHeidelpayCustomer( + $this->adapter, + $this->sessionHelper, + $this->isB2BCustomer($shopCustomer) + ); + $customer->setShippingAddress($this->createHeidelpayAddress($order->Lieferadresse)); + $customer->setBillingAddress($this->createHeidelpayAddress($order->oRechnungsadresse)); + $this->debugLog('Customer Resource: ' . $customer->jsonSerialize(), static::class); + + // Update existing customer resource if needed + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + $this->debugLog('Updated Customer Resource: ' . $customer->jsonSerialize(), static::class); + } + + // Create Basket + $session = $this->sessionHelper->getFrontendSession(); + $basket = $this->createHeidelpayBasket( + $session->getCart(), + $order->Waehrung, + $session->getLanguage(), + $order->cBestellNr ?? $payment->getId() + ); + $this->debugLog('Basket Resource: ' . $basket->jsonSerialize(), static::class); + + // Authorize Transaction + $riskData = (new RiskData()) + ->setThreatMetrixId($this->sessionHelper->get(SessionHelper::KEY_THREAT_METRIX_ID)) + ->setRegistrationLevel($shopCustomer->nRegistriert == '1' ? '1' : '0') + ->setRegistrationDate( + DateTime::createFromFormat('Y-m-d', $shopCustomer->dErstellt ?? date('Y-m-d'))->format('Ymd') + ); + + $authorization = new Authorization( + $this->getTotalPriceCustomerCurrency($order), + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $authorization->setOrderId($order->cBestellNr ?? null); + $authorization->setRiskData($riskData); + + return $this->adapter->getCurrentConnection()->performAuthorization( + $authorization, + $payment->getId(), + $customer, + $this->createMetadata(), + $basket + ); + } +} diff --git a/paymentmethod/UnzerPaylaterInstallment.php b/paymentmethod/UnzerPaylaterInstallment.php new file mode 100644 index 0000000..49bd088 --- /dev/null +++ b/paymentmethod/UnzerPaylaterInstallment.php @@ -0,0 +1,293 @@ +adapter->getConnectionForOrder($order); + + $reference = str_replace( + ['%ORDER_ID%', '%SHOPNAME%'], + [$order->cBestellNr, Shop::getSettingValue(CONF_GLOBAL, 'global_shopname')], + $this->trans(Config::LANG_CANCEL_PAYMENT_REFERENCE) + ); + + $cancel = (new Cancellation($transaction->getAmount()))->setPaymentReference($reference); + + // Cancel before charge (reversal) + if ($transaction instanceof Authorization) { + return $api->cancelAuthorizedPayment($payment, $cancel); + } + + // Cancel after charge (refund) + return $api->cancelChargedPayment($payment, $cancel); + } + + /** + * Data the merchant needs to put on the Invoice. + * + * The information iban, bic, descriptor and holder data must be be stated on the invoice + * so that the customer can make the bank transfer. + * + * The customer should be informed that he should use the descriptor during online banking transfer. + * This is the identifier that links the payment to the customer. + * + * We also save this data as payment info (tzahlungsinfo) to it is easily accessible. + * + * @param Bestellung $order + * @param Authorization $transaction + * @return array + */ + public function getOrderAttributes(Bestellung $order, AbstractTransactionType $transaction): array + { + // save payment information + $oPaymentInfo = new ZahlungsInfo(0, $order->kBestellung); + $oPaymentInfo->kKunde = $order->kKunde; + $oPaymentInfo->kBestellung = $order->kBestellung; + $oPaymentInfo->cInhaber = Text::convertUTF8($transaction->getHolder() ?? ''); + $oPaymentInfo->cIBAN = Text::convertUTF8($transaction->getIban() ?? ''); + $oPaymentInfo->cBIC = Text::convertUTF8($transaction->getBic() ?? ''); + $oPaymentInfo->cKontoNr = $oPaymentInfo->cIBAN; + $oPaymentInfo->cBLZ = $oPaymentInfo->cBIC; + $oPaymentInfo->cVerwendungszweck = Text::convertUTF8($transaction->getDescriptor() ?? ''); + $oPaymentInfo->cBankName = ''; + $oPaymentInfo->cKartenNr = ''; + $oPaymentInfo->cCVV = ''; + + isset($oPaymentInfo->kZahlungsInfo) ? $oPaymentInfo->updateInDB() : $oPaymentInfo->insertInDB(); + + return [ + self::ATTR_IBAN => $oPaymentInfo->cIBAN, + self::ATTR_BIC => $oPaymentInfo->cBIC, + self::ATTR_TRANSACTION_DESCRIPTOR => $oPaymentInfo->cVerwendungszweck, + self::ATTR_ACCOUNT_HOLDER => $oPaymentInfo->cInhaber, + ]; + } + + /** + * Only allow B2C Customers + */ + public function isSelectable(): bool + { + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + return !$this->isB2BCustomer($shopCustomer) && parent::isSelectable(); + } + + /** + * Load data for installment + * + * @inheritDoc + */ + public function handleStepAdditional(JTLSmarty $view): void + { + $this->adapter->getConnectionForSession(); + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + $customer = $this->createOrFetchHeidelpayCustomer( + $this->adapter, + $this->sessionHelper, + $this->isB2BCustomer($shopCustomer) + ); + $customer->setShippingAddress( + $this->createHeidelpayAddress( + $this->sessionHelper->getFrontendSession()->get('Lieferadresse') + ) + ); + $customer->setBillingAddress( + $this->createHeidelpayAddress($this->sessionHelper->getFrontendSession()->getCustomer()) + ); + + $data = $view->getTemplateVars('hpPayment') ?: []; + $data['customer'] = $customer; + $data['amount'] = round( + $this->sessionHelper->getFrontendSession()->getCart()->gibGesamtsummeWaren(true) + * Frontend::getCurrency()->getConversionFactor(), + 2 + ); + $data['currency'] = $this->sessionHelper->getFrontendSession()->getCurrency()->getCode(); + $data['country'] = $customer->getBillingAddress()->getCountry() ?? 'DE'; + + $view->assign('hpPayment', $data); + } + + /** + * Save customer resource id in the session. + * + * @SuppressWarnings(PHPMD.Superglobals) + * @return bool + */ + public function validateAdditional(): bool + { + $postPaymentData = $_POST['paymentData'] ?? []; + + // Save Customer ID if it exists + if (isset($postPaymentData['customerId'])) { + $this->sessionHelper->set(SessionHelper::KEY_CUSTOMER_ID, $postPaymentData['customerId']); + + // Save Basket Checksum + currency + $this->sessionHelper->set( + SessionHelper::KEY_CART_CHECKSUM, + Cart::getChecksum($this->sessionHelper->getFrontendSession()->getCart()) + ); + $this->sessionHelper->set( + SessionHelper::KEY_CART_CURRENCY, + $this->sessionHelper->getFrontendSession()->getCurrency()->getCode() + ); + + return true && parent::validateAdditional(); + } + + return parent::validateAdditional(); + } + + /** + * Generate and add threat metrix id (fraud prevention). + * + * @param JTLSmarty $view + * @return null|string + */ + public function handleStepReviewOrder(JTLSmarty $view): ?string + { + $data = $view->getTemplateVars('hpPayment') ?: []; + $data['threatMetrixId'] = $this->sessionHelper->generateThreatMetrixId(); + $view->assign('hpPayment', $data); + + // Check if basket changed + $currency = $this->sessionHelper->getFrontendSession()->getCurrency(); + $basket = $this->sessionHelper->getFrontendSession()->getCart(); + + if ( + Cart::getChecksum($basket) !== $this->sessionHelper->get(SessionHelper::KEY_CART_CHECKSUM) || + $currency->getCode() !== $this->sessionHelper->get(SessionHelper::KEY_CART_CURRENCY) + ) { + $this->sessionHelper->clearCheckoutSession(); + $this->sessionHelper->clear(SessionHelper::KEY_CART_CHECKSUM); + $this->sessionHelper->clear(SessionHelper::KEY_CART_CURRENCY); + $this->sessionHelper->addErrorAlert( + 'Aborting Checkout. Currency or Basket mismatch. Reauthorization needed!', + $this->trans(Config::LANG_CONFIRMATION_CHECKSUM), + 'basketMismatch', + PaymentHandler::REDIRECT_TO_PAYMENT_SELECTION_URL, + static::class + ); + + return null; + } + + return 'template/partials/_threatMetrix'; + } + + /** + * Authorizes the order on unzer side. + * + * With a successful authorize transaction, the amount is authorized and a payment resource is created. + * At this point no money has been transferred. + * + * The charge transaction calls are made when the order is shipped. + * With a successful charge transaction, the amount has been prepared to be insured. + * + * @inheritDoc + * @return AbstractTransactionType|Authorization + */ + protected function performTransaction(BasePaymentType $payment, Bestellung $order): AbstractTransactionType + { + // Create or fetch customer resource + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + $customer = $this->createOrFetchHeidelpayCustomer( + $this->adapter, + $this->sessionHelper, + $this->isB2BCustomer($shopCustomer) + ); + $customer->setShippingAddress($this->createHeidelpayAddress($order->Lieferadresse)); + $customer->setBillingAddress($this->createHeidelpayAddress($order->oRechnungsadresse)); + $this->debugLog('Customer Resource: ' . $customer->jsonSerialize(), static::class); + + // Update existing customer resource if needed + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + $this->debugLog('Updated Customer Resource: ' . $customer->jsonSerialize(), static::class); + } + + // Create Basket + $session = $this->sessionHelper->getFrontendSession(); + $basket = $this->createHeidelpayBasket( + $session->getCart(), + $order->Waehrung, + $session->getLanguage(), + $order->cBestellNr ?? $payment->getId() + ); + $this->debugLog('Basket Resource: ' . $basket->jsonSerialize(), static::class); + + // Authorize Transaction + $riskData = (new RiskData()) + ->setThreatMetrixId($this->sessionHelper->get(SessionHelper::KEY_THREAT_METRIX_ID)) + ->setRegistrationLevel($shopCustomer->nRegistriert == '1' ? '1' : '0') + ->setRegistrationDate( + DateTime::createFromFormat('Y-m-d', $shopCustomer->dErstellt ?? date('Y-m-d'))->format('Ymd') + ); + + $authorization = new Authorization( + $this->getTotalPriceCustomerCurrency($order), + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $authorization->setOrderId($order->cBestellNr ?? null); + $authorization->setRiskData($riskData); + + return $this->adapter->getCurrentConnection()->performAuthorization( + $authorization, + $payment->getId(), + $customer, + $this->createMetadata(), + $basket + ); + } +} diff --git a/paymentmethod/UnzerPaylaterInvoice.php b/paymentmethod/UnzerPaylaterInvoice.php new file mode 100644 index 0000000..4bc28d4 --- /dev/null +++ b/paymentmethod/UnzerPaylaterInvoice.php @@ -0,0 +1,309 @@ +adapter->getConnectionForOrder($order); + + $reference = str_replace( + ['%ORDER_ID%', '%SHOPNAME%'], + [$order->cBestellNr, Shop::getSettingValue(CONF_GLOBAL, 'global_shopname')], + $this->trans(Config::LANG_CANCEL_PAYMENT_REFERENCE) + ); + + $cancel = (new Cancellation($transaction->getAmount()))->setPaymentReference($reference); + + // Cancel before charge (reversal) + if ($transaction instanceof Authorization) { + return $api->cancelAuthorizedPayment($payment, $cancel); + } + + // Cancel after charge (refund) + return $api->cancelChargedPayment($payment, $cancel); + } + + + /** + * Data the merchant needs to put on the Invoice. + * + * The information iban, bic, descriptor and holder data must be be stated on the invoice + * so that the customer can make the bank transfer. + * + * The customer should be informed that he should use the descriptor during online banking transfer. + * This is the identifier that links the payment to the customer. + * + * We also save this data as payment info (tzahlungsinfo) to it is easily accessible. + * + * @param Bestellung $order + * @param Authorization $transaction + * @return array + */ + public function getOrderAttributes(Bestellung $order, AbstractTransactionType $transaction): array + { + // save payment information + $oPaymentInfo = new ZahlungsInfo(0, $order->kBestellung); + $oPaymentInfo->kKunde = $order->kKunde; + $oPaymentInfo->kBestellung = $order->kBestellung; + $oPaymentInfo->cInhaber = Text::convertUTF8($transaction->getHolder() ?? ''); + $oPaymentInfo->cIBAN = Text::convertUTF8($transaction->getIban() ?? ''); + $oPaymentInfo->cBIC = Text::convertUTF8($transaction->getBic() ?? ''); + $oPaymentInfo->cKontoNr = $oPaymentInfo->cIBAN; + $oPaymentInfo->cBLZ = $oPaymentInfo->cBIC; + $oPaymentInfo->cVerwendungszweck = Text::convertUTF8($transaction->getDescriptor() ?? ''); + $oPaymentInfo->cBankName = ''; + $oPaymentInfo->cKartenNr = ''; + $oPaymentInfo->cCVV = ''; + + isset($oPaymentInfo->kZahlungsInfo) ? $oPaymentInfo->updateInDB() : $oPaymentInfo->insertInDB(); + + return [ + self::ATTR_IBAN => $oPaymentInfo->cIBAN, + self::ATTR_BIC => $oPaymentInfo->cBIC, + self::ATTR_TRANSACTION_DESCRIPTOR => $oPaymentInfo->cVerwendungszweck, + self::ATTR_ACCOUNT_HOLDER => $oPaymentInfo->cInhaber, + ]; + } + + /** + * Add Customer Resource to view. + * + * @param JTLSmarty $view + * @return void + */ + public function handleStepAdditional(JTLSmarty $view): void + { + $this->adapter->getConnectionForSession(); + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + $customer = $this->createOrFetchHeidelpayCustomer( + $this->adapter, + $this->sessionHelper, + $this->isB2BCustomer($shopCustomer) + ); + $customer->setShippingAddress( + $this->createHeidelpayAddress( + $this->sessionHelper->getFrontendSession()->get('Lieferadresse') + ) + ); + + $data = $view->getTemplateVars('hpPayment') ?: []; + $data['customer'] = $customer; + $data['isB2B'] = $this->isB2BCustomer($shopCustomer); + + $view->assign('hpPayment', $data); + } + + /** + * Generate and add threat metrix id (fraud prevention). + * + * @param JTLSmarty $view + * @return null|string + */ + public function handleStepReviewOrder(JTLSmarty $view): ?string + { + $data = $view->getTemplateVars('hpPayment') ?: []; + $data['threatMetrixId'] = $this->sessionHelper->generateThreatMetrixId(); + $view->assign('hpPayment', $data); + + return 'template/partials/_threatMetrix'; + } + + /** + * Save customer resource id in the session. + * + * Save different billing address in session AND in the DB! + * + * @SuppressWarnings(PHPMD.Superglobals) + * @return bool + */ + public function validateAdditional(): bool + { + $postPaymentData = $_POST['paymentData'] ?? []; + + // Save Customer ID if it exists + if (isset($postPaymentData['customerId'])) { + $this->sessionHelper->set(SessionHelper::KEY_CUSTOMER_ID, $postPaymentData['customerId']); + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + $customer = $this->adapter->getConnectionForSession()->fetchCustomer($postPaymentData['customerId']); + + if (!isset($_SESSION['Bestellung'])) { + $_SESSION['Bestellung'] = new stdClass(); + } + + /** @var Lieferadresse $shipping */ + $shipping = $this->sessionHelper->getFrontendSession()->get('Lieferadresse'); + + if ($this->isB2BCustomer($shopCustomer)) { + // Split name into first and lastname + $names = $this->getNamesFromAddress($customer->getShippingAddress()); + $shipping->cVorname = $names['firstname'] ?: $shipping->cVorname; + $shipping->cNachname = $names['lastname'] ?: $shipping->cNachname; + $shipping->cBundesland = $customer->getShippingAddress()->getState(); + $shipping->cPLZ = $customer->getShippingAddress()->getZip(); + $shipping->cOrt = $customer->getShippingAddress()->getCity(); + $shipping->cLand = $customer->getShippingAddress()->getCountry(); + + // split street into street and street number + $street = $this->getStreetFromAddress($customer->getShippingAddress()); + $shipping->cHausnummer = $street['number'] ?: $shipping->cHausnummer; + $shipping->cStrasse = $street['street'] ?: $shipping->cStrasse; + } + + // Update Billing Address + // Split name into first and lastname + $names = $this->getNamesFromAddress($customer->getBillingAddress()); + $shopCustomer->cVorname = $names['firstname'] ?: $shopCustomer->cVorname; + $shopCustomer->cNachname = $names['lastname'] ?: $shopCustomer->cNachname; + + if ($this->isB2BCustomer($shopCustomer)) { + $shopCustomer->cBundesland = $customer->getBillingAddress()->getState(); + $shopCustomer->cPLZ = $customer->getBillingAddress()->getZip(); + $shopCustomer->cOrt = $customer->getBillingAddress()->getCity(); + $shopCustomer->cLand = $customer->getBillingAddress()->getCountry(); + + // split street into street and street number + $street = $this->getStreetFromAddress($customer->getBillingAddress()); + $shopCustomer->cHausnummer = $street['number'] ?: $shopCustomer->cHausnummer; + $shopCustomer->cStrasse = $street['street'] ?: $shopCustomer->cStrasse; + } + + if ($customer->getShippingAddress()->getShippingType() === ShippingTypes::DIFFERENT_ADDRESS) { + // Set kLieferadresse to -1 in the order so that JTL knows to use the delivery address from the session + // and not use the billing adress as the delivery address + $_SESSION['Bestellung']->kLieferadresse = -1; + // $this->sessionHelper->getFrontendSession()->setCustomer($shopCustomer); + } + + return true && parent::validateAdditional(); + } + + return parent::validateAdditional(); + } + + /** + * Authorizes the order on unzer side. + * + * With a successful authorize transaction, the amount is authorized and a payment resource is created. + * At this point no money has been transferred. + * + * The charge transaction calls are made when the order is shipped. + * With a successful charge transaction, the amount has been prepared to be insured. + * + * @inheritDoc + * @return AbstractTransactionType|Authorization + */ + protected function performTransaction(BasePaymentType $payment, $order): AbstractTransactionType + { + // Create or fetch customer resource + $shopCustomer = $this->sessionHelper->getFrontendSession()->getCustomer(); + $customer = $this->createOrFetchHeidelpayCustomer( + $this->adapter, + $this->sessionHelper, + $this->isB2BCustomer($shopCustomer) + ); + + if ($customer->getShippingAddress()->getStreet() === null) { + $customer->setShippingAddress($this->createHeidelpayAddress($order->Lieferadresse)); + } + + $customer->getBillingAddress()->setShippingType( + $order->kLieferadresse == -1 ? ShippingTypes::DIFFERENT_ADDRESS : ShippingTypes::EQUALS_BILLING + ); + + if ($customer->getBillingAddress()->getStreet() === null) { + $customer->setBillingAddress($this->createHeidelpayAddress($order->oRechnungsadresse)); + } + + $this->debugLog('Customer Resource: ' . $customer->jsonSerialize(), static::class); + + // Update existing customer resource if needed + if ($customer->getId()) { + $customer = $this->adapter->getCurrentConnection()->updateCustomer($customer); + $this->debugLog('Updated Customer Resource: ' . $customer->jsonSerialize(), static::class); + } + + // Create Basket + $session = $this->sessionHelper->getFrontendSession(); + $basket = $this->createHeidelpayBasket( + $session->getCart(), + $order->Waehrung, + $session->getLanguage(), + $order->cBestellNr ?? $payment->getId() + ); + $this->debugLog('Basket Resource: ' . $basket->jsonSerialize(), static::class); + + // Authorize Transaction + $riskData = (new RiskData()) + ->setThreatMetrixId($this->sessionHelper->get(SessionHelper::KEY_THREAT_METRIX_ID)) + ->setRegistrationLevel($shopCustomer->nRegistriert == '1' ? '1' : '0') + ->setRegistrationDate( + DateTime::createFromFormat('Y-m-d', $shopCustomer->dErstellt ?? date('Y-m-d'))->format('Ymd') + ); + + $authorization = new Authorization( + $this->getTotalPriceCustomerCurrency($order), + $order->Waehrung->getCode(), + $this->getReturnURL($order) + ); + $authorization->setOrderId($order->cBestellNr ?? null); + $authorization->setRiskData($riskData); + + return $this->adapter->getCurrentConnection()->performAuthorization( + $authorization, + $payment->getId(), + $customer, + $this->createMetadata(), + $basket + ); + } +} diff --git a/paymentmethod/template/_includes.tpl b/paymentmethod/template/_includes.tpl index c0d059b..a02cdd6 100644 --- a/paymentmethod/template/_includes.tpl +++ b/paymentmethod/template/_includes.tpl @@ -1,7 +1,7 @@ - + - +

              -
              - +
              +
              + +
              + @@ -116,7 +100,9 @@
              - +
              + +
              + @@ -102,7 +86,9 @@
              - +
              + +
              + @@ -50,7 +34,9 @@
              - +
              + +
              - + + @@ -71,7 +54,9 @@ - +
              + +
              + + + + +
              +

              Failure

              +

              + There has been an error completing the payment. + Merchant message (don\'t show this to the customer): ' . $_SESSION['merchantMessage'] . '

              '; + } + if (isset($_SESSION['clientMessage']) && !empty($_SESSION['clientMessage'])) { + echo '

              Client message (this is the error message for the customer): ' . $_SESSION['clientMessage'] . '

              '; + } + if (isset($_SESSION['ShortId']) && !empty($_SESSION['ShortId'])) { + echo '

              Please look for ShortId ' . $_SESSION['ShortId'] . ' in Unzer Insights to see the transaction.

              '; + } + if (isset($_SESSION['PaymentId']) && !empty($_SESSION['PaymentId'])) { + echo '

              The PaymentId of your transaction is \'' . $_SESSION['PaymentId'] . '\'.

              '; + } + ?> +

              + start again +
              + diff --git a/vendor/unzerdev/php-sdk/examples/Giropay/Constants.php b/vendor/unzerdev/php-sdk/examples/Giropay/Constants.php index a48246a..0bbb5fc 100644 --- a/vendor/unzerdev/php-sdk/examples/Giropay/Constants.php +++ b/vendor/unzerdev/php-sdk/examples/Giropay/Constants.php @@ -2,25 +2,8 @@ /** * This file defines the constants needed for the Giropay example. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ require_once __DIR__ . '/../Constants.php'; diff --git a/vendor/unzerdev/php-sdk/examples/Giropay/Controller.php b/vendor/unzerdev/php-sdk/examples/Giropay/Controller.php index 0cc02bf..29c02d2 100644 --- a/vendor/unzerdev/php-sdk/examples/Giropay/Controller.php +++ b/vendor/unzerdev/php-sdk/examples/Giropay/Controller.php @@ -3,25 +3,8 @@ * This is the controller for the Giropay example. * It is called when the pay button on the index page is clicked. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ diff --git a/vendor/unzerdev/php-sdk/examples/Giropay/index.php b/vendor/unzerdev/php-sdk/examples/Giropay/index.php index 8287dd7..3b9fb05 100644 --- a/vendor/unzerdev/php-sdk/examples/Giropay/index.php +++ b/vendor/unzerdev/php-sdk/examples/Giropay/index.php @@ -2,25 +2,8 @@ /** * This file provides an example implementation of the Giropay payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -36,8 +19,9 @@ Unzer UI Examples - + @@ -49,7 +33,9 @@
              - +
              + +
              + + + + + + + + + +

              Click here to open our test data in new tab.
              +

              + +
              + +
              + +
              +
              + + +
              +
              +
              +
              + + +
              +
              +
              + + +
              +
              +
              +
              +
              +
              +
              +
              +
              +
              + + + +
              +
              + + + + + diff --git a/vendor/unzerdev/php-sdk/examples/HostedPayPage/Constants.php b/vendor/unzerdev/php-sdk/examples/HostedPayPage/Constants.php index ea10350..22a8644 100644 --- a/vendor/unzerdev/php-sdk/examples/HostedPayPage/Constants.php +++ b/vendor/unzerdev/php-sdk/examples/HostedPayPage/Constants.php @@ -2,25 +2,8 @@ /** * This file defines the constants needed for the Hosted Payment Page example. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ require_once __DIR__ . '/../Constants.php'; diff --git a/vendor/unzerdev/php-sdk/examples/HostedPayPage/Controller.php b/vendor/unzerdev/php-sdk/examples/HostedPayPage/Controller.php index d60ab50..f74392c 100644 --- a/vendor/unzerdev/php-sdk/examples/HostedPayPage/Controller.php +++ b/vendor/unzerdev/php-sdk/examples/HostedPayPage/Controller.php @@ -3,25 +3,8 @@ * This is the controller for the Hosted Payment Page example. * It is called when the pay button on the index page is clicked. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -31,15 +14,17 @@ /** Require the composer autoloader file */ require_once __DIR__ . '/../../../../autoload.php'; +use UnzerSDK\Constants\CustomerGroups; +use UnzerSDK\Constants\CustomerRegistrationLevel; use UnzerSDK\Constants\Salutations; use UnzerSDK\examples\ExampleDebugHandler; use UnzerSDK\Exceptions\UnzerApiException; -use UnzerSDK\Resources\EmbeddedResources\Address; -use UnzerSDK\Unzer; use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\CustomerFactory; +use UnzerSDK\Resources\EmbeddedResources\Address; use UnzerSDK\Resources\EmbeddedResources\BasketItem; use UnzerSDK\Resources\PaymentTypes\Paypage; +use UnzerSDK\Unzer; session_start(); session_unset(); @@ -50,7 +35,7 @@ function redirect($url, $merchantMessage = '', $clientMessage = '') { $_SESSION['merchantMessage'] = $merchantMessage; - $_SESSION['clientMessage'] = $clientMessage; + $_SESSION['clientMessage'] = $clientMessage; header('Location: ' . $url); die(); } @@ -65,7 +50,7 @@ function redirect($url, $merchantMessage = '', $clientMessage = '') $unzer->setDebugMode(true)->setDebugHandler(new ExampleDebugHandler()); // A customer with matching addresses is mandatory for Installment payment type - $address = (new Address()) + $address = (new Address()) ->setName('Max Mustermann') ->setStreet('Vangerowstr. 18') ->setCity('Heidelberg') @@ -76,6 +61,7 @@ function redirect($url, $merchantMessage = '', $clientMessage = '') $customer = CustomerFactory::createCustomer('Max', 'Mustermann') ->setSalutation(Salutations::MR) ->setBirthDate('2000-02-12') + ->setLanguage('de') ->setEmail('test@test.com'); // These are the mandatory parameters for the payment page ... @@ -83,28 +69,45 @@ function redirect($url, $merchantMessage = '', $clientMessage = '') $orderId = 'o' . str_replace(['0.', ' '], '', microtime(false)); + // Just for example purpose. Make sure to generate a unique ID. + $threatMetrixId = 'php-sdk-example_' . $orderId; + + // ... however you can customize the Payment Page using additional parameters. - $paypage->setLogoImage('https://dev.unzer.com/wp-content/uploads/2020/09/Unzer__PrimaryLogo_Raspberry_RGB.png') - ->setFullPageImage('https://dev.unzer.com/wp-content/uploads/2020/09/01_Unzer_Ambitious_RGB_LoRes.jpg') - ->setShopName('My Test Shop') - ->setShopDescription('Best shop in the whole world!') - ->setTagline('Try and stop us from being awesome!') - ->setOrderId('OrderNr' . $orderId) - ->setTermsAndConditionUrl('https://www.unzer.com/en/') - ->setPrivacyPolicyUrl('https://www.unzer.com/de/datenschutz/') - ->setImprintUrl('https://www.unzer.com/de/impressum') - ->setHelpUrl('https://www.unzer.com/de/support') - ->setContactUrl('https://www.unzer.com/en/ueber-unzer') - ->setInvoiceId('i' . microtime(true)); + $paypage->setShopName('My Test Shop') + ->setShopDescription('Best shop in the whole world!') + ->setTagline('Try and stop us from being awesome!') + ->setOrderId('OrderNr' . $orderId) + ->setTermsAndConditionUrl('https://www.unzer.com/en/') + ->setPrivacyPolicyUrl('https://www.unzer.com/de/datenschutz/') + ->setImprintUrl('https://www.unzer.com/de/impressum') + ->setHelpUrl('https://www.unzer.com/de/support') + ->setContactUrl('https://www.unzer.com/en/ueber-unzer') + ->setFullPageImage(UNZER_PP_FULL_PAGE_IMAGE_URL) + ->setLogoImage(UNZER_PP_LOGO_URL) + ->setAdditionalAttribute('riskData.threatMetrixId', $threatMetrixId) + ->setAdditionalAttribute('riskData.customerGroup', CustomerGroups::GOOD) + ->setAdditionalAttribute('riskData.confirmedAmount', 99.99) + ->setAdditionalAttribute('riskData.confirmedOrders', 2) + ->setAdditionalAttribute('riskData.registrationLevel', CustomerRegistrationLevel::REGISTERED) + ->setAdditionalAttribute('riskData.registrationDate ', '20160412') + ->setInvoiceId('i' . microtime(true)); // ... in order to enable Unzer Instalment you will need to set the effectiveInterestRate as well. $paypage->setEffectiveInterestRate(4.99); // ... a Basket is mandatory for InstallmentSecured - $basketItem = (new BasketItem('Hat', 100.00, 119.00, 1)) - ->setAmountGross(119.0) - ->setAmountVat(19.0); - $basket = new Basket($orderId, 119.0, 'EUR', [$basketItem]); + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross(119.00) + ->setVat(19.00) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('Hat'); + + $basket = new Basket($orderId); + $basket->setTotalValueGross(119.00) + ->addBasketItem($basketItem) + ->setCurrencyCode('EUR'); if ($transactionType === 'charge') { $unzer->initPayPageCharge($paypage, $customer, $basket); diff --git a/vendor/unzerdev/php-sdk/examples/HostedPayPage/index.php b/vendor/unzerdev/php-sdk/examples/HostedPayPage/index.php index 75096f2..d69db61 100644 --- a/vendor/unzerdev/php-sdk/examples/HostedPayPage/index.php +++ b/vendor/unzerdev/php-sdk/examples/HostedPayPage/index.php @@ -2,25 +2,8 @@ /** * This file provides an example implementation of the Hosted Payment Page. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -37,8 +20,9 @@ Unzer UI Examples - + @@ -68,7 +52,9 @@ - +
              + +
              + @@ -50,7 +34,9 @@
              - +
              + +
              + - - + + diff --git a/vendor/unzerdev/php-sdk/examples/InstallmentSecured/index.php b/vendor/unzerdev/php-sdk/examples/InstallmentSecured/index.php index 67e15bc..d147a5a 100644 --- a/vendor/unzerdev/php-sdk/examples/InstallmentSecured/index.php +++ b/vendor/unzerdev/php-sdk/examples/InstallmentSecured/index.php @@ -2,25 +2,8 @@ /** * This file provides an example implementation of the Installment Secured direct debit payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -36,8 +19,9 @@ Unzer UI Examples - + @@ -52,9 +36,11 @@
              - +
              + +
              + @@ -48,13 +32,15 @@

              Click here to open our test data in new tab.

              -
              +
              - +
              + +
              + + + + + + +

              Click here to open our test data in new tab.

              + +
              + +
              +
              +
              + +
              +
              + + + + diff --git a/vendor/unzerdev/php-sdk/examples/PayPal/Constants.php b/vendor/unzerdev/php-sdk/examples/PayPal/Constants.php index c30b852..17a496a 100644 --- a/vendor/unzerdev/php-sdk/examples/PayPal/Constants.php +++ b/vendor/unzerdev/php-sdk/examples/PayPal/Constants.php @@ -2,25 +2,8 @@ /** * This file defines the constants needed for the PayPal example. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ require_once __DIR__ . '/../Constants.php'; diff --git a/vendor/unzerdev/php-sdk/examples/PayPal/Controller.php b/vendor/unzerdev/php-sdk/examples/PayPal/Controller.php index 6e3ae35..a71cfb4 100644 --- a/vendor/unzerdev/php-sdk/examples/PayPal/Controller.php +++ b/vendor/unzerdev/php-sdk/examples/PayPal/Controller.php @@ -3,25 +3,8 @@ * This is the controller for the PayPal example. * It is called when the pay button on the index page is clicked. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -33,6 +16,10 @@ use UnzerSDK\examples\ExampleDebugHandler; use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\Resources\Basket; +use UnzerSDK\Resources\EmbeddedResources\BasketItem; +use UnzerSDK\Resources\TransactionTypes\Authorization; +use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\Unzer; session_start(); @@ -53,6 +40,9 @@ function redirect($url, $merchantMessage = '', $clientMessage = '') if (!isset($_POST['resourceId'])) { redirect(FAILURE_URL, 'Resource id is missing!', $clientMessage); } + +$useExpressCheckout = isset($_POST['express-checkout']) && ($_POST['express-checkout'] === '1'); + $paymentTypeId = $_POST['resourceId']; $transactionType = $_POST['transaction_type'] ?? 'authorize'; @@ -62,12 +52,34 @@ function redirect($url, $merchantMessage = '', $clientMessage = '') // Create an Unzer object using your private key and register a debug handler if you want to. $unzer = new Unzer(UNZER_PAPI_PRIVATE_KEY); $unzer->setDebugMode(true)->setDebugHandler(new ExampleDebugHandler()); + $paymentType = $unzer->fetchPaymentType($paymentTypeId); + $orderId = 'o' . str_replace(['0.', ' '], '', microtime(false)); + + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross(12.32) + ->setVat(19.00) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('Hat'); + + $basket = new Basket($orderId); + $basket->setTotalValueGross(12.32) + ->addBasketItem($basketItem) + ->setCurrencyCode('EUR'); // Create a charge/authorize transaction to get the redirectUrl. if ($transactionType === 'charge') { - $transaction = $unzer->charge(12.32, 'EUR', $paymentTypeId, RETURN_CONTROLLER_URL); + $charge = new Charge(12.32, 'EUR', RETURN_CONTROLLER_URL); + if ($useExpressCheckout) { + $charge->setCheckoutType('express', $paymentType); + } + $transaction = $unzer->performCharge($charge, $paymentType, null, null, $basket); } else { - $transaction = $unzer->authorize(12.32, 'EUR', $paymentTypeId, RETURN_CONTROLLER_URL); + $authorize = new Authorization(12.32, 'EUR', RETURN_CONTROLLER_URL); + if ($useExpressCheckout) { + $authorize->setCheckoutType('express', $paymentType); + } + $transaction = $unzer->performAuthorization($authorize, $paymentType, null, null, $basket); } // You'll need to remember the paymentId for later in the ReturnController diff --git a/vendor/unzerdev/php-sdk/examples/PayPal/index.php b/vendor/unzerdev/php-sdk/examples/PayPal/index.php index 0432b52..0fb4842 100644 --- a/vendor/unzerdev/php-sdk/examples/PayPal/index.php +++ b/vendor/unzerdev/php-sdk/examples/PayPal/index.php @@ -2,25 +2,8 @@ /** * This file provides an example implementation of the PayPal payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -36,8 +19,9 @@ Unzer UI Examples - + @@ -46,14 +30,14 @@

              Example data:

                -
              • Username: paypal-customer@heidelpay.de
              • -
              • Password: heidelpay
              • +
              • Username: paypal-buyer@unzer.com
              • +
              • Password: unzer1234
              Attention: We recommend to create your own PayPal test account here.

              Click here to open our test data in new tab.

              -
              +
              @@ -70,29 +54,55 @@
              - + +

              PayPal

              - +
              + +
              + +

              PayPal Express

              +
              + @@ -46,8 +30,8 @@

              Example data:

                -
              • Username: paypal-customer@heidelpay.de
              • -
              • Password: heidelpay
              • +
              • Username: paypal-buyer@unzer.com
              • +
              • Password: unzer1234
              Attention: We recommend to create your own PayPal test account here. @@ -55,7 +39,9 @@
              - +
              + +
              + + + + + + + +

              Click here to open our test data in new tab.

              + +
              +
              +
              + +
              +
              + + + + diff --git a/vendor/unzerdev/php-sdk/examples/PaylaterDirectDebit/Constants.php b/vendor/unzerdev/php-sdk/examples/PaylaterDirectDebit/Constants.php new file mode 100644 index 0000000..a8a77f2 --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PaylaterDirectDebit/Constants.php @@ -0,0 +1,9 @@ +setDebugMode(true)->setDebugHandler(new ExampleDebugHandler()); + + // Use the quote or order id from your shop + $orderId = 'o' . str_replace(['0.', ' '], '', microtime(false)); + + /** @var PaylaterDirectDebit $paymentType */ + $paymentType = $unzer->fetchPaymentType($paymentTypeId); + + // A customer with matching addresses is mandatory for Direct Debit payment type + $address = (new Address()) + ->setName('Linda Heideich') + ->setStreet('Vangerowstr. 18') + ->setCity('Heidelberg') + ->setZip('69155') + ->setCountry('DE'); + $customer = CustomerFactory::createCustomer('Linda', 'Heideich') + ->setBirthDate('2000-02-12') + ->setBillingAddress($address) + ->setShippingAddress($address) + ->setEmail('linda.heideich@test.de'); + + // A Basket is mandatory for Paylater Direct Debit payment type + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross($orderAmount) + ->setVat(19) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('Hat'); + + $currency = 'EUR'; + $basket = new Basket($orderId); + $basket->setTotalValueGross($orderAmount) + ->addBasketItem($basketItem) + ->setCurrencyCode($currency); + + $riskData = (new RiskData()) + ->setThreatMetrixId($threatMetrixId) + ->setCustomerGroup(CustomerGroups::GOOD) + ->setConfirmedAmount(99.99) + ->setConfirmedOrders(2) + ->setRegistrationLevel(CustomerRegistrationLevel::REGISTERED) + ->setRegistrationDate('20160412'); + + // initialize the payment + $authorize = (new Authorization($orderAmount, $currency, RETURN_CONTROLLER_URL)) + ->setRiskData($riskData); + + $unzer->performAuthorization( + $authorize, + $paymentType, + $customer, + null, + $basket + ); + + // You'll need to remember the shortId to show it on the success or failure page + $_SESSION['PaymentId'] = $authorize->getPaymentId(); + $_SESSION['ShortId'] = $authorize->getShortId(); + $_SESSION['additionalPaymentInformation'] = sprintf("Descriptor: %s", $authorize->getDescriptor()); + + // Redirect to the success or failure depending on the state of the transaction + if ($authorize->isSuccess()) { + redirect(SUCCESS_URL); + } + + // Check the result message of the transaction to find out what went wrong. + $merchantMessage = $authorize->getMessage()->getCustomer(); +} catch (UnzerApiException $e) { + $merchantMessage = $e->getMerchantMessage(); + $clientMessage = $e->getClientMessage(); +} catch (RuntimeException $e) { + $merchantMessage = $e->getMessage(); +} +redirect(FAILURE_URL, $merchantMessage, $clientMessage); diff --git a/vendor/unzerdev/php-sdk/examples/PaylaterDirectDebit/index.php b/vendor/unzerdev/php-sdk/examples/PaylaterDirectDebit/index.php new file mode 100644 index 0000000..430c412 --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PaylaterDirectDebit/index.php @@ -0,0 +1,109 @@ + + + + + + + Unzer UI Examples + + + + + + + + +

              Click here to open our test data in new tab.
              +

              + + +
              +
              + +
              + +
              + +
              +
              + + + + + diff --git a/vendor/unzerdev/php-sdk/examples/PaylaterInstallment/Constants.php b/vendor/unzerdev/php-sdk/examples/PaylaterInstallment/Constants.php new file mode 100644 index 0000000..dd238d2 --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PaylaterInstallment/Constants.php @@ -0,0 +1,12 @@ +setDebugMode(true)->setDebugHandler(new ExampleDebugHandler()); + + // Use the quote or order id from your shop + $orderId = 'o' . str_replace(['0.', ' '], '', microtime(false)); + + /** @var \UnzerSDK\Resources\PaymentTypes\PaylaterInstallment $paymentType */ + $paymentType = $unzer->fetchPaymentType($paymentTypeId); + + // A customer with matching addresses is mandatory for Installment payment type + $address = (new Address()) + ->setName('Linda Heideich') + ->setStreet('Vangerowstr. 18') + ->setCity('Heidelberg') + ->setZip('69155') + ->setCountry('DE'); + $customer = CustomerFactory::createCustomer('Linda', 'Heideich') + ->setBirthDate('2000-02-12') + ->setBillingAddress($address) + ->setShippingAddress($address) + ->setEmail('linda.heideich@test.de'); + + // A Basket is mandatory for Paylater Installment payment type + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross($orderAmount) + ->setVat(19) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('Hat'); + + $currency = 'EUR'; + $basket = new Basket($orderId); + $basket->setTotalValueGross($orderAmount) + ->addBasketItem($basketItem) + ->setCurrencyCode($currency); + + $riskData = (new RiskData()) + ->setThreatMetrixId($threatMetrixId) + ->setCustomerGroup(CustomerGroups::GOOD) + ->setConfirmedAmount(99.99) + ->setConfirmedOrders(2) + ->setRegistrationLevel(CustomerRegistrationLevel::REGISTERED) + ->setRegistrationDate('20160412'); + + // initialize the payment + $authorize = (new Authorization($orderAmount, $currency, RETURN_CONTROLLER_URL)) + ->setRiskData($riskData); + + $unzer->performAuthorization( + $authorize, + $paymentType, + $customer, + null, + $basket + ); + + // You'll need to remember the shortId to show it on the success or failure page + $_SESSION['PaymentId'] = $authorize->getPaymentId(); + $_SESSION['ShortId'] = $authorize->getShortId(); + $_SESSION['additionalPaymentInformation'] = sprintf("Descriptor: %s", $authorize->getDescriptor()); + + // Redirect to the success or failure depending on the state of the transaction + if ($authorize->isSuccess()) { + redirect(SUCCESS_URL); + } + + // Check the result message of the transaction to find out what went wrong. + $merchantMessage = $authorize->getMessage()->getCustomer(); +} catch (UnzerApiException $e) { + $merchantMessage = $e->getMerchantMessage(); + $clientMessage = $e->getClientMessage(); +} catch (RuntimeException $e) { + $merchantMessage = $e->getMessage(); +} +redirect(FAILURE_URL, $merchantMessage, $clientMessage); diff --git a/vendor/unzerdev/php-sdk/examples/PaylaterInstallment/index.php b/vendor/unzerdev/php-sdk/examples/PaylaterInstallment/index.php new file mode 100644 index 0000000..886ecae --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PaylaterInstallment/index.php @@ -0,0 +1,136 @@ + + + + + + + Unzer UI Examples + + + + + + + + +

              Click here to open our test data in new tab.
              +

              + +
              +
              +
              +
              + +
              +
              + + +
              + + + + + diff --git a/vendor/unzerdev/php-sdk/examples/PaylaterInvoice/Constants.php b/vendor/unzerdev/php-sdk/examples/PaylaterInvoice/Constants.php new file mode 100644 index 0000000..5bad530 --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PaylaterInvoice/Constants.php @@ -0,0 +1,12 @@ +setDebugMode(true)->setDebugHandler(new ExampleDebugHandler()); + + $orderId = 'o' . str_replace(['0.', ' '], '', microtime(false)); + + // A Basket is mandatory for Invoice Secured payment type + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross(119.00) + ->setVat(19.00) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('Hat'); + + $basket = new Basket($orderId); + $basket->setTotalValueGross(119.00) + ->addBasketItem($basketItem) + ->setCurrencyCode('EUR') + ->setOrderId($orderId); + + $riskData = (new RiskData()) + ->setThreatMetrixId($threatMetrixId) + ->setCustomerGroup(CustomerGroups::GOOD) + ->setConfirmedAmount(99.99) + ->setConfirmedOrders(2) + ->setRegistrationLevel(CustomerRegistrationLevel::REGISTERED) + ->setRegistrationDate('20160412'); + + $authorization = (new Authorization(119.00, 'EUR', CONTROLLER_URL)) + ->setRiskData($riskData); + + $paymentType = $unzer->fetchPaymentType($paymentTypeId); + + $transaction = $unzer->performAuthorization($authorization, $paymentType, $customerId, null, $basket); + + // You'll need to remember the shortId to show it on the success or failure page + $_SESSION['ShortId'] = $transaction->getShortId(); + $_SESSION['PaymentId'] = $transaction->getPaymentId(); + $_SESSION['isAuthorizeTransaction'] = true; + $_SESSION['additionalPaymentInformation'] = + sprintf( + "Please transfer the amount of %f %s to the following account:

              " + . "Holder: %s
              " + . "IBAN: %s
              " + . "BIC: %s

              " + . "Please use only this identification number as the descriptor:
              " + . "%s", + $transaction->getAmount(), + $transaction->getCurrency(), + $transaction->getHolder(), + $transaction->getIban(), + $transaction->getBic(), + $transaction->getDescriptor() + ); + + // To avoid redundant code this example redirects to the general ReturnController which contains the code example to handle payment results. + redirect(RETURN_CONTROLLER_URL); + +} catch (UnzerApiException $e) { + $merchantMessage = $e->getMerchantMessage(); + $clientMessage = $e->getClientMessage(); +} catch (RuntimeException $e) { + $merchantMessage = $e->getMessage(); +} +// Write the merchant message to your log. +// Show the client message to the customer (it is localized). +redirect(FAILURE_URL, $merchantMessage, $clientMessage); diff --git a/vendor/unzerdev/php-sdk/examples/PaylaterInvoice/index.php b/vendor/unzerdev/php-sdk/examples/PaylaterInvoice/index.php new file mode 100644 index 0000000..c00162c --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PaylaterInvoice/index.php @@ -0,0 +1,142 @@ + + + + + + + Unzer UI Examples + + + + + + + + +

              Click here to open our test data in new tab.

              + +
              +
              + +
              +
              +
              +
              + +
              +
              + + + + + diff --git a/vendor/unzerdev/php-sdk/examples/Pending.php b/vendor/unzerdev/php-sdk/examples/Pending.php index 4e5f41d..311a19c 100644 --- a/vendor/unzerdev/php-sdk/examples/Pending.php +++ b/vendor/unzerdev/php-sdk/examples/Pending.php @@ -2,25 +2,8 @@ /** * This is the pending page for the example payments. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ session_start(); @@ -28,25 +11,33 @@ - -

              Pending

              -

              - The payment transaction has been completed, however it has the state pending.
              - The status of the payment is not definite at the moment.
              - You can create the Order in your shop but should set its status to pending payment. -

              -

              - Please use the webhook feature to be informed about later changes of the payment. - You should ship only if the status changes to success. - Please look for ShortId ' . $_SESSION['ShortId'] . ' in Unzer Insights to see the transaction.

              '; - } - if (isset($_SESSION['PaymentId']) && !empty($_SESSION['PaymentId'])) { - echo '

              The PaymentId of your transaction is \'' . $_SESSION['PaymentId'] . '\'.

              '; - } - ?> -

              -

              start again

              - + + + + + + +
              +

              Pending

              +

              + The payment transaction has been completed, however it has the state pending.
              + The status of the payment is not definite at the moment.
              + You can create the Order in your shop but should set its status to pending payment. +

              +

              + Please use the webhook feature to be informed about later changes of the payment. + You should ship only if the status changes to success. + Please look for ShortId ' . $_SESSION['ShortId'] . ' in Unzer Insights to see the transaction.

              '; + } + if (isset($_SESSION['PaymentId']) && !empty($_SESSION['PaymentId'])) { + echo '

              The PaymentId of your transaction is \'' . $_SESSION['PaymentId'] . '\'.

              '; + } + ?> +

              + start again +
              + diff --git a/vendor/unzerdev/php-sdk/examples/PostFinanceCard/Constants.php b/vendor/unzerdev/php-sdk/examples/PostFinanceCard/Constants.php new file mode 100644 index 0000000..36f6f97 --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PostFinanceCard/Constants.php @@ -0,0 +1,13 @@ +setDebugMode(true)->setDebugHandler(new ExampleDebugHandler()); + + // Create a charge transaction to get the redirectUrl. + $transaction = new \UnzerSDK\Resources\TransactionTypes\Charge(12.32, 'CHF', RETURN_CONTROLLER_URL); + $unzer->performCharge($transaction, $paymentTypeId); + + // You'll need to remember the paymentId for later in the ReturnController + $_SESSION['PaymentId'] = $transaction->getPaymentId(); + $_SESSION['ShortId'] = $transaction->getShortId(); + + // Redirect to the PostFinance page + if (!$transaction->isError() && $transaction->getRedirectUrl() !== null) { + redirect($transaction->getRedirectUrl()); + } + + // Check the result message of the charge to find out what went wrong. + $merchantMessage = $transaction->getMessage()->getCustomer(); +} catch (UnzerApiException $e) { + $merchantMessage = $e->getMerchantMessage(); + $clientMessage = $e->getClientMessage(); +} catch (RuntimeException $e) { + $merchantMessage = $e->getMessage(); +} +redirect(FAILURE_URL, $merchantMessage, $clientMessage); diff --git a/vendor/unzerdev/php-sdk/examples/PostFinanceCard/index.php b/vendor/unzerdev/php-sdk/examples/PostFinanceCard/index.php new file mode 100644 index 0000000..d5cdfe1 --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PostFinanceCard/index.php @@ -0,0 +1,72 @@ + + + + + + + Unzer UI Examples + + + + + + + + +

              Click here to open our test data in new tab.

              + +
              +
              +
              + +
              +
              + + + + diff --git a/vendor/unzerdev/php-sdk/examples/PostFinanceEfinance/Constants.php b/vendor/unzerdev/php-sdk/examples/PostFinanceEfinance/Constants.php new file mode 100644 index 0000000..f8fa1be --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PostFinanceEfinance/Constants.php @@ -0,0 +1,13 @@ +setDebugMode(true)->setDebugHandler(new ExampleDebugHandler()); + + // Create a charge transaction to get the redirectUrl. + $transaction = new \UnzerSDK\Resources\TransactionTypes\Charge(12.32, 'CHF', RETURN_CONTROLLER_URL); + $unzer->performCharge($transaction, $paymentTypeId); + + // You'll need to remember the paymentId for later in the ReturnController + $_SESSION['PaymentId'] = $transaction->getPaymentId(); + $_SESSION['ShortId'] = $transaction->getShortId(); + + // Redirect to the PostFinance page + if (!$transaction->isError() && $transaction->getRedirectUrl() !== null) { + redirect($transaction->getRedirectUrl()); + } + + // Check the result message of the charge to find out what went wrong. + $merchantMessage = $transaction->getMessage()->getCustomer(); +} catch (UnzerApiException $e) { + $merchantMessage = $e->getMerchantMessage(); + $clientMessage = $e->getClientMessage(); +} catch (RuntimeException $e) { + $merchantMessage = $e->getMessage(); +} +redirect(FAILURE_URL, $merchantMessage, $clientMessage); diff --git a/vendor/unzerdev/php-sdk/examples/PostFinanceEfinance/index.php b/vendor/unzerdev/php-sdk/examples/PostFinanceEfinance/index.php new file mode 100644 index 0000000..cf121b8 --- /dev/null +++ b/vendor/unzerdev/php-sdk/examples/PostFinanceEfinance/index.php @@ -0,0 +1,72 @@ + + + + + + + Unzer UI Examples + + + + + + + + +

              Click here to open our test data in new tab.

              + +
              +
              +
              + +
              +
              + + + + diff --git a/vendor/unzerdev/php-sdk/examples/Prepayment/Constants.php b/vendor/unzerdev/php-sdk/examples/Prepayment/Constants.php index 2900500..2f0965b 100644 --- a/vendor/unzerdev/php-sdk/examples/Prepayment/Constants.php +++ b/vendor/unzerdev/php-sdk/examples/Prepayment/Constants.php @@ -2,25 +2,8 @@ /** * This file defines the constants needed for the Prepayment example. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ require_once __DIR__ . '/../Constants.php'; diff --git a/vendor/unzerdev/php-sdk/examples/Prepayment/Controller.php b/vendor/unzerdev/php-sdk/examples/Prepayment/Controller.php index d5db27d..3dca705 100644 --- a/vendor/unzerdev/php-sdk/examples/Prepayment/Controller.php +++ b/vendor/unzerdev/php-sdk/examples/Prepayment/Controller.php @@ -3,25 +3,8 @@ * This is the controller for the Prepayment example. * It is called when the pay button on the index page is clicked. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ diff --git a/vendor/unzerdev/php-sdk/examples/Prepayment/index.php b/vendor/unzerdev/php-sdk/examples/Prepayment/index.php index 07a5785..87ea973 100644 --- a/vendor/unzerdev/php-sdk/examples/Prepayment/index.php +++ b/vendor/unzerdev/php-sdk/examples/Prepayment/index.php @@ -2,25 +2,8 @@ /** * This file provides an example implementation of the Prepayment payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -45,7 +28,9 @@
              - +
              + +
              + @@ -50,7 +34,9 @@
              - +
              + +
              + @@ -47,7 +31,7 @@

              Click here to open our test data in new tab.

              -
              +
              @@ -55,7 +39,9 @@
              - +
              + +
              + @@ -49,7 +33,9 @@
              - +
              + +
              + + + + + + +
              - - - -

              Success

              -

              - The order has been successfully placed. +

              Success

              +

              The order has been successfully placed.

              - Please look for ShortId ' . $_SESSION['ShortId'] . ' in Unzer Insights to see the transaction.

              '; - } - if (isset($_SESSION['PaymentId']) && !empty($_SESSION['PaymentId'])) { - echo '

              The PaymentId of your transaction is \'' . $_SESSION['PaymentId'] . '\'.

              '; - } - if (isset($_SESSION['PaymentTypeId']) && !empty($_SESSION['PaymentTypeId'])) { - echo '

              The TypeId for the recurring payment is \'' . $_SESSION['PaymentTypeId'] . '\'. You can use it + if ($shortId !== null) { + $defaultTransactionMessage = '

              Please look for ShortId ' . $shortId . ' in Unzer Insights to see the transaction.

              '; + $paylaterTransactionMessage = '

              Please use the "descriptor" to look for the transaction in the Unzer Pay Later Merchant Portal.

              '; + echo preg_match('/[\d]{4}.[\d]{4}.[\d]{4}/', $shortId) ? $defaultTransactionMessage : $paylaterTransactionMessage; + } + + $isManageable = false; + if ($paymentId !== null) { + echo '

              The PaymentId of your transaction is \'' . $paymentId . '\'.

              '; + $unzer = new Unzer(UNZER_PAPI_PRIVATE_KEY); + $payment = $unzer->fetchPayment($paymentId); + $isManageable = $payment->getPaymentType()->supportsDirectPaymentCancel() || $payment->getAuthorization() !== null; + } + + if ($paymentTypeId !== null) { + echo '

              The TypeId for the recurring payment is \'' . $paymentTypeId . '\'. You can use it now for subsequent transactions.

              - +
              '; - } - ?> -

              -

              start again

              - + } + + if ($isManageable) { + echo '

              As a merchant you can charge or cancel the Payment here: Manage Payment

              '; + } + ?> + start again +
              + diff --git a/vendor/unzerdev/php-sdk/examples/Webhooks/Constants.php b/vendor/unzerdev/php-sdk/examples/Webhooks/Constants.php index b9b5aae..488b84b 100644 --- a/vendor/unzerdev/php-sdk/examples/Webhooks/Constants.php +++ b/vendor/unzerdev/php-sdk/examples/Webhooks/Constants.php @@ -2,25 +2,8 @@ /** * This file defines the constants needed for the Webhooks example. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ require_once __DIR__ . '/../Constants.php'; diff --git a/vendor/unzerdev/php-sdk/examples/Webhooks/Controller.php b/vendor/unzerdev/php-sdk/examples/Webhooks/Controller.php index e3771a3..e7b9c7c 100644 --- a/vendor/unzerdev/php-sdk/examples/Webhooks/Controller.php +++ b/vendor/unzerdev/php-sdk/examples/Webhooks/Controller.php @@ -2,25 +2,8 @@ /** * This is the controller for the Webhook reception tests. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ diff --git a/vendor/unzerdev/php-sdk/examples/Webhooks/fetchAll.php b/vendor/unzerdev/php-sdk/examples/Webhooks/fetchAll.php index 76be7ea..2e636eb 100644 --- a/vendor/unzerdev/php-sdk/examples/Webhooks/fetchAll.php +++ b/vendor/unzerdev/php-sdk/examples/Webhooks/fetchAll.php @@ -2,25 +2,8 @@ /** * This is the controller performing the fetch all command for the Webhook tests. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -59,11 +42,12 @@ function printInfo($title, $text) Unzer UI Examples - + - - + + diff --git a/vendor/unzerdev/php-sdk/examples/Webhooks/index.php b/vendor/unzerdev/php-sdk/examples/Webhooks/index.php index 054f3bf..e8f9921 100644 --- a/vendor/unzerdev/php-sdk/examples/Webhooks/index.php +++ b/vendor/unzerdev/php-sdk/examples/Webhooks/index.php @@ -2,25 +2,8 @@ /** * This is the index controller for the Webhook tests. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -66,11 +49,12 @@ function printInfo($title, $text) Unzer UI Examples - + - - + + diff --git a/vendor/unzerdev/php-sdk/examples/Webhooks/removeAll.php b/vendor/unzerdev/php-sdk/examples/Webhooks/removeAll.php index 32061ab..b6d269a 100644 --- a/vendor/unzerdev/php-sdk/examples/Webhooks/removeAll.php +++ b/vendor/unzerdev/php-sdk/examples/Webhooks/removeAll.php @@ -2,25 +2,8 @@ /** * This is the index controller for the Webhook tests. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -64,11 +47,12 @@ function printInfo($title, $text) Unzer UI Examples - + - - + + diff --git a/vendor/unzerdev/php-sdk/examples/Wechatpay/Constants.php b/vendor/unzerdev/php-sdk/examples/Wechatpay/Constants.php index ae5c8b5..3f0f256 100644 --- a/vendor/unzerdev/php-sdk/examples/Wechatpay/Constants.php +++ b/vendor/unzerdev/php-sdk/examples/Wechatpay/Constants.php @@ -2,25 +2,8 @@ /** * This file defines the constants needed for the WeChatPay example. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ require_once __DIR__ . '/../Constants.php'; diff --git a/vendor/unzerdev/php-sdk/examples/Wechatpay/Controller.php b/vendor/unzerdev/php-sdk/examples/Wechatpay/Controller.php index e46b0f6..f1eba0c 100644 --- a/vendor/unzerdev/php-sdk/examples/Wechatpay/Controller.php +++ b/vendor/unzerdev/php-sdk/examples/Wechatpay/Controller.php @@ -3,25 +3,8 @@ * This is the controller for the WeChatPay example. * It is called when the pay button on the index page is clicked. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ diff --git a/vendor/unzerdev/php-sdk/examples/Wechatpay/index.php b/vendor/unzerdev/php-sdk/examples/Wechatpay/index.php index 0b5f688..43d16d5 100644 --- a/vendor/unzerdev/php-sdk/examples/Wechatpay/index.php +++ b/vendor/unzerdev/php-sdk/examples/Wechatpay/index.php @@ -2,25 +2,8 @@ /** * This file provides an example implementation of the WeChatPay payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\examples */ /** Require the constants of this example */ @@ -36,8 +19,9 @@ Unzer UI Examples - + @@ -54,7 +38,9 @@
              - +
              + +
              + - - + + - +

              @@ -83,6 +66,23 @@ function printMessage($type, $title, $text) ?>
              +
              +
              +
              Apple Pay
              +
              + You can try authorize and charge transactions. + Please make sure to provide the path to the certificates for this payment type. + Notes: +
                +
              • This payment type is available for Apple devices only.
              • +
              • Please refer to this page to learn all about the requirements for Apple Pay.
              • +
              +
              +
              +
              + Try +
              +
              Card
              @@ -155,6 +155,18 @@ function printMessage($type, $title, $text) Try
              +
              +
              +
              + Google Pay +
              +
              +
              +
              +
              + Try +
              +
              @@ -206,7 +218,7 @@ function printMessage($type, $title, $text)
              - Invoice + Invoice (deprecated)
              @@ -220,11 +232,40 @@ function printMessage($type, $title, $text)
              Unzer Invoice
              +
              + With "paylater-invoice" type. +
              +
              +
              + Documentation +
              +
              + Try +
              +
              +
              +
              +
              + Unzer Invoice (deprecated) +
              +
              + With "invoice-secured" type. +
              Try
              +
              +
              +
              + Klarna +
              +
              +
              + Try +
              +
              @@ -251,6 +292,18 @@ function printMessage($type, $title, $text) Try
              +
              +
              +
              + PayU +
              +
              +
              +
              +
              + Try +
              +
              @@ -266,7 +319,7 @@ function printMessage($type, $title, $text)
              - Unzer Direct Debit + Unzer Direct Debit (deprecated)
              @@ -278,7 +331,31 @@ function printMessage($type, $title, $text)
              - Unzer Installment (secured) + Paylater Direct Debit +
              +
              +
              +
              +
              + Try +
              +
              +
              +
              +
              + Paylater Installment +
              +
              +
              +
              +
              + Try +
              +
              +
              +
              +
              + Installment Secured (deprecated)
              @@ -299,6 +376,30 @@ function printMessage($type, $title, $text) Try
              +
              +
              +
              + Post Finance Card +
              +
              +
              +
              +
              + Try +
              +
              +
              +
              +
              + Post Finance eFinance +
              +
              +
              +
              +
              + Try +
              +
              @@ -310,7 +411,7 @@ function printMessage($type, $title, $text) server and redirected to a given RedirectUrl.
              -
              +
              Documentation
              @@ -327,7 +428,7 @@ function printMessage($type, $title, $text) The Payment Page will be shown as an Overlay in your own shop.
              -
              +
              Documentation
              diff --git a/vendor/unzerdev/php-sdk/phpunit.xml b/vendor/unzerdev/php-sdk/phpunit.xml index 58ad406..df90057 100644 --- a/vendor/unzerdev/php-sdk/phpunit.xml +++ b/vendor/unzerdev/php-sdk/phpunit.xml @@ -1,5 +1,6 @@ - + verbose="true" + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"> + + + src/ + + disabled skip - - - src/ - - - \ No newline at end of file + diff --git a/vendor/unzerdev/php-sdk/src/Adapter/ApplepayAdapter.php b/vendor/unzerdev/php-sdk/src/Adapter/ApplepayAdapter.php index 72e496b..824650a 100644 --- a/vendor/unzerdev/php-sdk/src/Adapter/ApplepayAdapter.php +++ b/vendor/unzerdev/php-sdk/src/Adapter/ApplepayAdapter.php @@ -1,29 +1,7 @@ - * - * @package UnzerSDK\Adapter - */ namespace UnzerSDK\Adapter; use UnzerSDK\Constants\ApplepayValidationDomains; @@ -31,6 +9,12 @@ use UnzerSDK\Resources\ExternalResources\ApplepaySession; use UnzerSDK\Services\EnvironmentService; +/** + * This is a wrapper for the applepay http adapter (CURL). + * + * @link https://dev.unzer.com/ + * + */ class ApplepayAdapter { private $request; diff --git a/vendor/unzerdev/php-sdk/src/Adapter/CurlAdapter.php b/vendor/unzerdev/php-sdk/src/Adapter/CurlAdapter.php index 6a282ed..e3ddd2b 100644 --- a/vendor/unzerdev/php-sdk/src/Adapter/CurlAdapter.php +++ b/vendor/unzerdev/php-sdk/src/Adapter/CurlAdapter.php @@ -1,35 +1,21 @@ - * - * @package UnzerSDK\Adapter */ + namespace UnzerSDK\Adapter; use UnzerSDK\Unzer; use UnzerSDK\Services\EnvironmentService; -use function extension_loaded; use UnzerSDK\Exceptions\UnzerApiException; use RuntimeException; + +use function extension_loaded; use function in_array; class CurlAdapter implements HttpAdapterInterface @@ -51,7 +37,7 @@ public function __construct() /** * {@inheritDoc} */ - public function init($url, $payload = null, $httpMethod = HttpAdapterInterface::REQUEST_GET): void + public function init(string $url, string $payload = null, string $httpMethod = HttpAdapterInterface::REQUEST_GET): void { $timeout = EnvironmentService::getTimeout(); $curlVerbose = EnvironmentService::isCurlVerbose(); @@ -69,7 +55,12 @@ public function init($url, $payload = null, $httpMethod = HttpAdapterInterface:: $this->setOption(CURLOPT_VERBOSE, $curlVerbose); $this->setOption(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); - if (in_array($httpMethod, [HttpAdapterInterface::REQUEST_POST, HttpAdapterInterface::REQUEST_PUT], true)) { + $postFieldMethods = [ + HttpAdapterInterface::REQUEST_POST, + HttpAdapterInterface::REQUEST_PUT, + HttpAdapterInterface::REQUEST_PATCH + ]; + if (in_array($httpMethod, $postFieldMethods, true)) { $this->setOption(CURLOPT_POSTFIELDS, $payload); } } diff --git a/vendor/unzerdev/php-sdk/src/Adapter/HttpAdapterInterface.php b/vendor/unzerdev/php-sdk/src/Adapter/HttpAdapterInterface.php index ea01679..4e238b8 100644 --- a/vendor/unzerdev/php-sdk/src/Adapter/HttpAdapterInterface.php +++ b/vendor/unzerdev/php-sdk/src/Adapter/HttpAdapterInterface.php @@ -2,45 +2,30 @@ /** * Http adapters to be used by this api have to implement this interface. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/docs/php-sdk/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Adapter */ + namespace UnzerSDK\Adapter; use UnzerSDK\Exceptions\UnzerApiException; interface HttpAdapterInterface { - public const REQUEST_POST = 'POST'; public const REQUEST_DELETE = 'DELETE'; - public const REQUEST_PUT = 'PUT'; public const REQUEST_GET = 'GET'; + public const REQUEST_PATCH = 'PATCH'; + public const REQUEST_POST = 'POST'; + public const REQUEST_PUT = 'PUT'; /** * Initializes the request. * - * @param string $url The full url to connect to. - * @param string $payload Json encoded payload string. - * @param string $httpMethod The Http method to perform. + * @param string $url The full url to connect to. + * @param string|null $payload Json encoded payload string. + * @param string $httpMethod The Http method to perform. */ - public function init($url, $payload = null, $httpMethod = HttpAdapterInterface::REQUEST_GET): void; + public function init(string $url, string $payload = null, string $httpMethod = HttpAdapterInterface::REQUEST_GET): void; /** * Executes the request and returns the response. diff --git a/vendor/unzerdev/php-sdk/src/Constants/AdditionalAttributes.php b/vendor/unzerdev/php-sdk/src/Constants/AdditionalAttributes.php new file mode 100644 index 0000000..b090361 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Constants/AdditionalAttributes.php @@ -0,0 +1,16 @@ + - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class ApiResponseCodes { // Status codes @@ -62,6 +46,7 @@ class ApiResponseCodes public const API_ERROR_RECURRING_PAYMENT_NOT_SUPPORTED = 'API.500.550.004'; public const API_ERROR_WEBHOOK_EVENT_ALREADY_REGISTERED = 'API.510.310.009'; public const API_ERROR_WEBHOOK_CAN_NOT_BE_FOUND = 'API.510.310.008'; + public const API_ERROR_BASKET_NOT_FOUND = 'API.600.410.024'; public const API_ERROR_BASKET_ITEM_IMAGE_INVALID_URL = 'API.600.630.004'; public const API_ERROR_RECURRING_ALREADY_ACTIVE = 'API.640.550.006'; public const API_ERROR_INVALID_KEY = 'API.710.000.002'; @@ -70,6 +55,7 @@ class ApiResponseCodes public const API_ERROR_FIELD_IS_MISSING = 'API.710.200.100'; public const CORE_ERROR_INVALID_OR_MISSING_LOGIN = 'COR.100.300.600'; + public const CORE_INVALID_IP_NUMBER = 'COR.100.900.401'; public const CORE_ERROR_INSURANCE_ALREADY_ACTIVATED = 'COR.700.400.800'; public const SDM_ERROR_CURRENT_INSURANCE_EVENT = 'SDM.CURRENT_INSURANCE_EVENT'; diff --git a/vendor/unzerdev/php-sdk/src/Constants/ApplepayValidationDomains.php b/vendor/unzerdev/php-sdk/src/Constants/ApplepayValidationDomains.php index 9f9824a..39bf63a 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/ApplepayValidationDomains.php +++ b/vendor/unzerdev/php-sdk/src/Constants/ApplepayValidationDomains.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class ApplepayValidationDomains { // URL list diff --git a/vendor/unzerdev/php-sdk/src/Constants/BasketItemTypes.php b/vendor/unzerdev/php-sdk/src/Constants/BasketItemTypes.php index c2b5976..66b87e4 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/BasketItemTypes.php +++ b/vendor/unzerdev/php-sdk/src/Constants/BasketItemTypes.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class BasketItemTypes { public const GOODS = 'goods'; diff --git a/vendor/unzerdev/php-sdk/src/Constants/CancelReasonCodes.php b/vendor/unzerdev/php-sdk/src/Constants/CancelReasonCodes.php index bb2c659..2dad0da 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/CancelReasonCodes.php +++ b/vendor/unzerdev/php-sdk/src/Constants/CancelReasonCodes.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class CancelReasonCodes { public const REASON_CODE_CANCEL = 'CANCEL'; diff --git a/vendor/unzerdev/php-sdk/src/Constants/CompanyCommercialSectorItems.php b/vendor/unzerdev/php-sdk/src/Constants/CompanyCommercialSectorItems.php index 1d16990..98ef420 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/CompanyCommercialSectorItems.php +++ b/vendor/unzerdev/php-sdk/src/Constants/CompanyCommercialSectorItems.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class CompanyCommercialSectorItems { public const OTHER = 'OTHER'; diff --git a/vendor/unzerdev/php-sdk/src/Constants/CompanyRegistrationTypes.php b/vendor/unzerdev/php-sdk/src/Constants/CompanyRegistrationTypes.php index e0f3ade..7ae0d73 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/CompanyRegistrationTypes.php +++ b/vendor/unzerdev/php-sdk/src/Constants/CompanyRegistrationTypes.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class CompanyRegistrationTypes { public const REGISTRATION_TYPE_REGISTERED = 'registered'; diff --git a/vendor/unzerdev/php-sdk/src/Constants/CompanyTypes.php b/vendor/unzerdev/php-sdk/src/Constants/CompanyTypes.php new file mode 100644 index 0000000..c2744d1 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Constants/CompanyTypes.php @@ -0,0 +1,18 @@ + - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class IdStrings { // Transactions @@ -32,6 +15,7 @@ class IdStrings public const CHARGE = 'chg'; public const PAYOUT = 'out'; public const SHIPMENT = 'shp'; + public const CHARGEBACK = 'cbk'; // Payment Types public const ALIPAY = 'ali'; @@ -40,6 +24,7 @@ class IdStrings public const CARD = 'crd'; public const EPS = 'eps'; public const GIROPAY = 'gro'; + public const GOOGLE_PAY = 'gop'; public const HIRE_PURCHASE_DIRECT_DEBIT = 'hdd'; public const IDEAL = 'idl'; public const INSTALLMENT_SECURED = 'ins'; @@ -47,8 +32,15 @@ class IdStrings public const INVOICE_FACTORING = 'ivf'; public const INVOICE_GUARANTEED = 'ivg'; public const INVOICE_SECURED = 'ivs'; + public const KLARNA = 'kla'; + public const PAYLATER_DIRECT_DEBIT = 'pdd'; + public const PAYLATER_INVOICE = 'piv'; + public const PAYLATER_INSTALLMENT = 'pit'; public const PAYMENT_PAGE = 'ppg'; public const PAYPAL = 'ppl'; + public const PAYU = 'pyu'; + public const POST_FINANCE_CARD = 'pfc'; + public const POST_FINANCE_EFINANCE = 'pfe'; public const PIS = 'pis'; public const PREPAYMENT = 'ppy'; public const PRZELEWY24 = 'p24'; @@ -72,6 +64,7 @@ class IdStrings self::CARD, self::EPS, self::GIROPAY, + self::GOOGLE_PAY, self::HIRE_PURCHASE_DIRECT_DEBIT, self::IDEAL, self::INSTALLMENT_SECURED, @@ -79,8 +72,15 @@ class IdStrings self::INVOICE_FACTORING, self::INVOICE_GUARANTEED, self::INVOICE_SECURED, + self::KLARNA, + self::PAYLATER_DIRECT_DEBIT, + self::PAYLATER_INVOICE, + self::PAYLATER_INSTALLMENT, self::PAYMENT_PAGE, self::PAYPAL, + self::PAYU, + self::POST_FINANCE_CARD, + self::POST_FINANCE_EFINANCE, self::PIS, self::PREPAYMENT, self::PRZELEWY24, diff --git a/vendor/unzerdev/php-sdk/src/Constants/LiabilityShiftIndicator.php b/vendor/unzerdev/php-sdk/src/Constants/LiabilityShiftIndicator.php new file mode 100644 index 0000000..6892d6b --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Constants/LiabilityShiftIndicator.php @@ -0,0 +1,15 @@ + - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - -use RuntimeException; - class PaymentState { public const STATE_PENDING = 0; @@ -34,6 +18,7 @@ class PaymentState public const STATE_PARTLY = 3; public const STATE_PAYMENT_REVIEW = 4; public const STATE_CHARGEBACK = 5; + public const STATE_CREATE = 6; public const STATE_NAME_PENDING = 'pending'; public const STATE_NAME_COMPLETED = 'completed'; @@ -41,6 +26,7 @@ class PaymentState public const STATE_NAME_PARTLY = 'partly'; public const STATE_NAME_PAYMENT_REVIEW = 'payment review'; public const STATE_NAME_CHARGEBACK = 'chargeback'; + public const STATE_NAME_CREATE = 'create'; /** * Returns the name of the state with the given code. @@ -51,7 +37,7 @@ class PaymentState * * @throws RuntimeException A RuntimeException is thrown when the $stateCode is unknown. */ - public static function mapStateCodeToName($stateCode): string + public static function mapStateCodeToName(int $stateCode): string { switch ($stateCode) { case self::STATE_PENDING: @@ -72,6 +58,9 @@ public static function mapStateCodeToName($stateCode): string case self::STATE_CHARGEBACK: $stateName = self::STATE_NAME_CHARGEBACK; break; + case self::STATE_CREATE: + $stateName = self::STATE_NAME_CREATE; + break; default: throw new RuntimeException('Unknown payment state #' . $stateCode); } @@ -88,7 +77,7 @@ public static function mapStateCodeToName($stateCode): string * * @throws RuntimeException A RuntimeException is thrown when the $stateName is unknown. */ - public static function mapStateNameToCode($stateName): int + public static function mapStateNameToCode(string $stateName): int { switch ($stateName) { case self::STATE_NAME_PENDING: diff --git a/vendor/unzerdev/php-sdk/src/Constants/RecurrenceTypes.php b/vendor/unzerdev/php-sdk/src/Constants/RecurrenceTypes.php index 61eeb0b..23e3d79 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/RecurrenceTypes.php +++ b/vendor/unzerdev/php-sdk/src/Constants/RecurrenceTypes.php @@ -1,36 +1,19 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class RecurrenceTypes { /** @var string Recurring with a defined interval and a defined amount.*/ public const SCHEDULED = 'scheduled'; - /** @var string Recurring with a undefined interval and/or an undefined amount.*/ + /** @var string Recurring with an undefined interval and/or an undefined amount.*/ public const UNSCHEDULED = 'unscheduled'; /** @var string If the payment type should be used again for future transactions.*/ diff --git a/vendor/unzerdev/php-sdk/src/Constants/Salutations.php b/vendor/unzerdev/php-sdk/src/Constants/Salutations.php index 65843dc..1ad4cb2 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/Salutations.php +++ b/vendor/unzerdev/php-sdk/src/Constants/Salutations.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class Salutations { public const MR = 'mr'; diff --git a/vendor/unzerdev/php-sdk/src/Constants/ShippingTypes.php b/vendor/unzerdev/php-sdk/src/Constants/ShippingTypes.php new file mode 100644 index 0000000..447164f --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Constants/ShippingTypes.php @@ -0,0 +1,18 @@ + - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class TransactionTypes { public const AUTHORIZATION = 'authorize'; @@ -32,4 +16,5 @@ class TransactionTypes public const REFUND = 'cancel-charge'; public const SHIPMENT = 'shipment'; public const PAYOUT = 'payout'; + public const CHARGEBACK = 'chargeback'; } diff --git a/vendor/unzerdev/php-sdk/src/Constants/WebhookEvents.php b/vendor/unzerdev/php-sdk/src/Constants/WebhookEvents.php index 8b197d3..62faef4 100644 --- a/vendor/unzerdev/php-sdk/src/Constants/WebhookEvents.php +++ b/vendor/unzerdev/php-sdk/src/Constants/WebhookEvents.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Constants */ -namespace UnzerSDK\Constants; - class WebhookEvents { // all events @@ -31,19 +15,21 @@ class WebhookEvents // authorize events public const AUTHORIZE = 'authorize'; - public const AUTHORIZE_SUCCEEDED = 'authorize.succeeded'; + public const AUTHORIZE_CANCELED = 'authorize.canceled'; + public const AUTHORIZE_EXPIRED = 'authorize.expired'; public const AUTHORIZE_FAILED = 'authorize.failed'; public const AUTHORIZE_PENDING = 'authorize.pending'; - public const AUTHORIZE_EXPIRED = 'authorize.expired'; - public const AUTHORIZE_CANCELED = 'authorize.canceled'; + public const AUTHORIZE_RESUMED = 'authorize.resumed'; + public const AUTHORIZE_SUCCEEDED = 'authorize.succeeded'; // charge events public const CHARGE = 'charge'; - public const CHARGE_SUCCEEDED = 'charge.succeeded'; + public const CHARGE_CANCELED = 'charge.canceled'; + public const CHARGE_EXPIRED = 'charge.expired'; public const CHARGE_FAILED = 'charge.failed'; public const CHARGE_PENDING = 'charge.pending'; - public const CHARGE_EXPIRED = 'charge.expired'; - public const CHARGE_CANCELED = 'charge.canceled'; + public const CHARGE_RESUMED = 'charge.resumed'; + public const CHARGE_SUCCEEDED = 'charge.succeeded'; // chargeback events public const CHARGEBACK = 'chargeback'; @@ -63,6 +49,7 @@ class WebhookEvents public const CUSTOMER_UPDATED = 'customer.updated'; // payment events + public const PAYMENT = 'payment'; public const PAYMENT_PENDING = 'payment.pending'; public const PAYMENT_COMPLETED = 'payment.completed'; public const PAYMENT_CANCELED = 'payment.canceled'; @@ -76,17 +63,19 @@ class WebhookEvents public const ALLOWED_WEBHOOKS = [ self::ALL, self::AUTHORIZE, - self::AUTHORIZE_SUCCEEDED, + self::AUTHORIZE_CANCELED, + self::AUTHORIZE_EXPIRED, self::AUTHORIZE_FAILED, self::AUTHORIZE_PENDING, - self::AUTHORIZE_EXPIRED, - self::AUTHORIZE_CANCELED, + self::AUTHORIZE_RESUMED, + self::AUTHORIZE_SUCCEEDED, self::CHARGE, - self::CHARGE_SUCCEEDED, + self::CHARGE_CANCELED, + self::CHARGE_EXPIRED, self::CHARGE_FAILED, self::CHARGE_PENDING, - self::CHARGE_EXPIRED, - self::CHARGE_CANCELED, + self::CHARGE_RESUMED, + self::CHARGE_SUCCEEDED, self::CHARGEBACK, self::PAYOUT, self::PAYOUT_SUCCEEDED, @@ -96,6 +85,7 @@ class WebhookEvents self::CUSTOMER_CREATED, self::CUSTOMER_DELETED, self::CUSTOMER_UPDATED, + self::PAYMENT, self::PAYMENT_PENDING, self::PAYMENT_COMPLETED, self::PAYMENT_CANCELED, diff --git a/vendor/unzerdev/php-sdk/src/Exceptions/ApplepayMerchantValidationException.php b/vendor/unzerdev/php-sdk/src/Exceptions/ApplepayMerchantValidationException.php index ba61e82..5d671c4 100644 --- a/vendor/unzerdev/php-sdk/src/Exceptions/ApplepayMerchantValidationException.php +++ b/vendor/unzerdev/php-sdk/src/Exceptions/ApplepayMerchantValidationException.php @@ -2,26 +2,8 @@ /* * This exception is thrown whenever the apple merchant validation request returns an error. * - * Copyright (C) 2021 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author David Owusu - * - * @package UnzerSDK - * */ namespace UnzerSDK\Exceptions; diff --git a/vendor/unzerdev/php-sdk/src/Exceptions/UnzerApiException.php b/vendor/unzerdev/php-sdk/src/Exceptions/UnzerApiException.php index 0bd9a9b..39d2092 100644 --- a/vendor/unzerdev/php-sdk/src/Exceptions/UnzerApiException.php +++ b/vendor/unzerdev/php-sdk/src/Exceptions/UnzerApiException.php @@ -2,26 +2,10 @@ /** * This exception is thrown whenever the api returns an error. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Exceptions */ + namespace UnzerSDK\Exceptions; use Exception; @@ -40,12 +24,12 @@ class UnzerApiException extends Exception /** * UnzerApiException constructor. * - * @param string $merchantMessage - * @param string $clientMessage - * @param string $code - * @param string $errorId + * @param string $merchantMessage + * @param string $clientMessage + * @param string $code + * @param string|null $errorId */ - public function __construct($merchantMessage = '', $clientMessage = '', $code = null, $errorId = null) + public function __construct($merchantMessage = '', $clientMessage = '', $code = null, string $errorId = null) { $merchantMessage = empty($merchantMessage) ? static::MESSAGE : $merchantMessage; $this->clientMessage = empty($clientMessage) ? static::CLIENT_MESSAGE : $clientMessage; diff --git a/vendor/unzerdev/php-sdk/src/Interfaces/CancelServiceInterface.php b/vendor/unzerdev/php-sdk/src/Interfaces/CancelServiceInterface.php index fed9982..efa5314 100644 --- a/vendor/unzerdev/php-sdk/src/Interfaces/CancelServiceInterface.php +++ b/vendor/unzerdev/php-sdk/src/Interfaces/CancelServiceInterface.php @@ -2,26 +2,10 @@ /** * The interface for the CancelService. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Interfaces */ + namespace UnzerSDK\Interfaces; use UnzerSDK\Constants\CancelReasonCodes; @@ -118,7 +102,7 @@ public function cancelCharge( /** * Performs a Cancellation transaction on the Payment. - * If no amount is given a full cancel will be performed i. e. all Charges and Authorizations will be cancelled. + * If no amount is given a full cancel will be performed i.e. all Charges and Authorizations will be cancelled. * * @param Payment|string $payment The Payment object or the id of the Payment to be cancelled. * @param float|null $amount The amount to be canceled. @@ -131,17 +115,45 @@ public function cancelCharge( * @return Cancellation[] An array holding all Cancellation objects created with this cancel call. * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. - * @throws RuntimeException A RuntimeException is thrown when there is a error while using the SDK. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function cancelPayment( $payment, float $amount = null, - $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, + ?string $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, string $referenceText = null, float $amountNet = null, float $amountVat = null ): array; + /** + * Performs a Cancellation transaction on the Payment. Should only be used for "paylater-invoice" payments. + * If no Cancellation is given a full cancel will be performed. + * + * @param Payment|string $payment The Payment object or the id of the Payment to be cancelled. + * @param Cancellation|null $cancellation + * + * @return Cancellation A Cancellation object created with this cancel call. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function cancelAuthorizedPayment($payment, ?Cancellation $cancellation = null): Cancellation; + + /** + * Performs a Cancellation transaction on the Payment. Should only be used for "paylater-invoice" payments. + * If no Cancellation is given a full cancel will be performed. + * + * @param Payment|string $payment The Payment object or the id of the Payment to be cancelled. + * @param Cancellation|null $cancellation + * + * @return Cancellation A Cancellation object created with this cancel call. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function cancelChargedPayment($payment, ?Cancellation $cancellation = null): Cancellation; + /** * Cancel the given amount of the payments authorization. * diff --git a/vendor/unzerdev/php-sdk/src/Interfaces/DebugHandlerInterface.php b/vendor/unzerdev/php-sdk/src/Interfaces/DebugHandlerInterface.php index 8552c80..66736d8 100644 --- a/vendor/unzerdev/php-sdk/src/Interfaces/DebugHandlerInterface.php +++ b/vendor/unzerdev/php-sdk/src/Interfaces/DebugHandlerInterface.php @@ -2,26 +2,10 @@ /** * Use this interface in order to implement a custom handler for debug information. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Interfaces */ + namespace UnzerSDK\Interfaces; interface DebugHandlerInterface diff --git a/vendor/unzerdev/php-sdk/src/Interfaces/PaymentServiceInterface.php b/vendor/unzerdev/php-sdk/src/Interfaces/PaymentServiceInterface.php index d3cfd31..477e03e 100644 --- a/vendor/unzerdev/php-sdk/src/Interfaces/PaymentServiceInterface.php +++ b/vendor/unzerdev/php-sdk/src/Interfaces/PaymentServiceInterface.php @@ -2,26 +2,10 @@ /** * The interface for the PaymentService. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Interfaces */ + namespace UnzerSDK\Interfaces; use DateTime; @@ -29,8 +13,10 @@ use UnzerSDK\Resources\AbstractUnzerResource; use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\Customer; +use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; use UnzerSDK\Resources\InstalmentPlans; use UnzerSDK\Resources\Metadata; +use UnzerSDK\Resources\PaylaterInstallmentPlans; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Paypage; @@ -42,6 +28,45 @@ interface PaymentServiceInterface { + /** + * Performs an Authorization transaction and returns the resulting Authorization resource. + * + * @param Authorization $authorization The Authorization object containing transaction specific information. + * @param BasePaymentType|string $paymentType The PaymentType object or the id of the PaymentType to use. + * @param Customer|string|null $customer The Customer object or the id of the customer resource to reference. + * @param Metadata|null $metadata The Metadata object containing custom information for the payment. + * @param Basket|null $basket The Basket object corresponding to the payment. + * The Basket object will be created automatically if it does not exist + * yet (i.e. has no id). + * + * @return Authorization The resulting object of the Authorization resource. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function performAuthorization( + Authorization $authorization, + $paymentType, + $customer = null, + Metadata $metadata = null, + Basket $basket = null + ): Authorization; + + /** + * Update an Authorization transaction with PATCH method and returns the resulting Authorization resource. + * + * @param Payment|string $payment The Payment object or ID the transaction belongs to. + * @param Authorization $authorization The Authorization object containing transaction specific information. + * The Basket object will be created automatically if it does not exist + * yet (i.e. has no id). + * + * @return Authorization The resulting object of the Authorization resource. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function updateAuthorization($payment, Authorization $authorization): Authorization; + /** * Performs an Authorization transaction and returns the resulting Authorization resource. * @@ -65,6 +90,10 @@ interface PaymentServiceInterface * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * + * @deprecated since 1.2.0.0 please use performAuthorization() instead. + * @see performAuthorization + * */ public function authorize( $amount, @@ -81,6 +110,45 @@ public function authorize( $recurrenceType = null ): Authorization; + /** + * Performs a Charge transaction and returns the resulting Charge resource. + * + * @param Charge $charge The Charge object containing transaction specific information. + * @param string|BasePaymentType $paymentType The PaymentType object or the id of the PaymentType to use. + * @param Customer|string|null $customer The Customer object or the id of the customer resource to reference. + * @param Metadata|null $metadata The Metadata object containing custom information for the payment. + * @param Basket|null $basket The Basket object corresponding to the payment. + * The Basket object will be created automatically if it does not exist + * yet (i.e. has no id). + * + * @return Charge The resulting object of the Charge resource. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function performCharge( + Charge $charge, + $paymentType, + $customer = null, + Metadata $metadata = null, + Basket $basket = null + ): Charge; + + /** + * Update a Charge transaction with PATCH method and returns the resulting Charge resource. + * + * @param Payment|string $payment The Payment object or ID the transaction belongs to. + * @param Charge $charge The Charge object containing transaction specific information. + * The Basket object will be created automatically if it does not exist + * yet (i.e. has no id). + * + * @return Charge The resulting object of the Charge resource. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function updateCharge($payment, Charge $charge): Charge; + /** * Performs a Charge transaction and returns the resulting Charge resource. * @@ -105,6 +173,10 @@ public function authorize( * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * + * @deprecated since 1.2.0.0 please use performCharge() instead. + * @see performCharge + * */ public function charge( $amount, @@ -121,6 +193,23 @@ public function charge( $recurrenceType = null ): Charge; + /** + * Performs a Charge transaction for a previously authorized payment. + * To perform a full charge of the authorized amount leave the amount null. + * + * @param string|Payment $payment The Payment object the Authorization to charge belongs to. + * @param Charge $charge The Charge object containing transaction specific information. + * + * @return Charge The resulting object of the Charge resource. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function performChargeOnPayment( + $payment, + Charge $charge + ): Charge; + /** * Performs a Charge transaction for the Authorization of the given Payment object. * To perform a full charge of the authorized amount leave the amount null. @@ -134,6 +223,9 @@ public function charge( * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * + * @deprecated since 1.2.0.0 please use performChargeOnPayment() instead. + * */ public function chargeAuthorization( $payment, @@ -147,7 +239,6 @@ public function chargeAuthorization( * * @param Payment|string $payment The Payment object to be charged. * @param float|null $amount The amount to charge. - * @param string|null $currency The Currency of the charged amount. * @param string|null $orderId The order id from the shop. * @param string|null $invoiceId The invoice id from the shop. * @@ -155,11 +246,13 @@ public function chargeAuthorization( * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * + * @deprecated since 1.2.0.0 please use performChargeOnPayment() instead. + * */ public function chargePayment( $payment, float $amount = null, - string $currency = null, string $orderId = null, string $invoiceId = null ): Charge; @@ -186,16 +279,16 @@ public function chargePayment( * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function payout( - $amount, - $currency, + float $amount, + string $currency, $paymentType, - $returnUrl, + string $returnUrl, $customer = null, - $orderId = null, - $metadata = null, - $basket = null, - $invoiceId = null, - $referenceText = null + string $orderId = null, + Metadata $metadata = null, + Basket $basket = null, + string $invoiceId = null, + string $referenceText = null ): Payout; /** @@ -234,9 +327,9 @@ public function ship($payment, string $invoiceId = null, string $orderId = null) * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function initPayPageCharge( - Paypage $paypage, + Paypage $paypage, Customer $customer = null, - Basket $basket = null, + Basket $basket = null, Metadata $metadata = null ): Paypage; @@ -262,9 +355,9 @@ public function initPayPageCharge( * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function initPayPageAuthorize( - Paypage $paypage, + Paypage $paypage, Customer $customer = null, - Basket $basket = null, + Basket $basket = null, Metadata $metadata = null ): Paypage; @@ -282,9 +375,18 @@ public function initPayPageAuthorize( * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function fetchInstallmentPlans( - $amount, - $currency, - $effectiveInterest, + float $amount, + string $currency, + float $effectiveInterest, DateTime $orderDate = null ): InstalmentPlans; + + /** + * Returns an InstallmentPlans object containing all available instalment plan options. + * + * @param InstallmentPlansQuery $plansRequest + * + * @return PaylaterInstallmentPlans + */ + public function fetchPaylaterInstallmentPlans(InstallmentPlansQuery $plansRequest): PaylaterInstallmentPlans; } diff --git a/vendor/unzerdev/php-sdk/src/Interfaces/ResourceServiceInterface.php b/vendor/unzerdev/php-sdk/src/Interfaces/ResourceServiceInterface.php index 94c058e..ce977b2 100644 --- a/vendor/unzerdev/php-sdk/src/Interfaces/ResourceServiceInterface.php +++ b/vendor/unzerdev/php-sdk/src/Interfaces/ResourceServiceInterface.php @@ -2,40 +2,27 @@ /** * The interface for the ResourceService. * - * Copyright (C) 2020 - today Unzer E-Com GmbH + * @link https://docs.unzer.com/ * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @link https://docs.unzer.com/ - * - * @author Simon Gabriel - * - * @package UnzerSDK\Interfaces */ + namespace UnzerSDK\Interfaces; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\AbstractUnzerResource; use UnzerSDK\Resources\Basket; +use UnzerSDK\Resources\Config; use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\Keypair; use UnzerSDK\Resources\Metadata; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; +use UnzerSDK\Resources\PaymentTypes\Paypage; use UnzerSDK\Resources\Recurring; use UnzerSDK\Resources\TransactionTypes\Authorization; use UnzerSDK\Resources\TransactionTypes\Cancellation; use UnzerSDK\Resources\TransactionTypes\Charge; +use UnzerSDK\Resources\TransactionTypes\Chargeback; use UnzerSDK\Resources\TransactionTypes\Payout; use UnzerSDK\Resources\TransactionTypes\Shipment; use RuntimeException; @@ -63,14 +50,14 @@ public function fetchPayout($payment): Payout; * @param string|BasePaymentType $paymentType The payment to activate recurring payment for. * @param string $returnUrl The URL to which the customer gets redirected in case of a 3ds * transaction - * @param string $recurrenceType Recurrence type used for recurring payment. + * @param string|null $recurrenceType Recurrence type used for recurring payment. * * @return Recurring The recurring object. * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function activateRecurringPayment($paymentType, $returnUrl, string $recurrenceType = null): Recurring; + public function activateRecurringPayment($paymentType, string $returnUrl, string $recurrenceType = null): Recurring; /** * Fetch and return payment by given payment id or payment object. @@ -95,7 +82,20 @@ public function fetchPayment($payment): Payment; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchPaymentByOrderId($orderId): Payment; + public function fetchPaymentByOrderId(string $orderId): Payment; + + /** + * Fetch and return payPage by given payPageId or payPage object. + * If a payPage object is given it will be updated as well, thus you do not rely on the returned object. + * + * @param Paypage|string $payPage The payment object or paymentId to fetch. + * + * @return Paypage The fetched payPage object. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function fetchPayPage($payPage): Paypage; /** * Fetch public key and configured payment types from API. @@ -107,12 +107,12 @@ public function fetchPaymentByOrderId($orderId): Payment; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchKeypair($detailed = false): Keypair; + public function fetchKeypair(bool $detailed = false): Keypair; /** * Create Metadata resource. * - * @param Metadata $metadata The Metadata object to be created. + * @param Metadata|string $metadata The Metadata object to be created. * * @return Metadata The fetched Metadata resource. * @@ -146,7 +146,11 @@ public function fetchMetadata($metadata): Metadata; public function createBasket(Basket $basket): Basket; /** - * Fetches and returns the given Basket (by object or id). + * Fetches and returns the given Basket (by object or id). Since the PAPI provides 2 basket versions, this method performs up to two request. + * Firstly the basket gets fetched from the "v2" endpoint. + * Only If PAPI returns a specific "basket not found" error the function tries to fetch from the "v1" basket endpoint. + * + * @see \UnzerSDK\Constants\ApiResponseCodes::API_ERROR_BASKET_NOT_FOUND * * @param Basket|string $basket Basket object or id of basket to be fetched. * @@ -205,7 +209,7 @@ public function updatePaymentType(BasePaymentType $paymentType): BasePaymentType * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchPaymentType($typeId): BasePaymentType; + public function fetchPaymentType(string $typeId): BasePaymentType; /** * Create an API resource for the given customer object. @@ -253,7 +257,7 @@ public function fetchCustomer($customer): Customer; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchCustomerByExtCustomerId($customerId): Customer; + public function fetchCustomerByExtCustomerId(string $customerId): Customer; /** * Update and return a Customer object via API. @@ -303,7 +307,7 @@ public function fetchAuthorization($payment): Authorization; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchChargeById($payment, $chargeId): Charge; + public function fetchChargeById($payment, string $chargeId): Charge; /** * Update local charge object. @@ -317,6 +321,32 @@ public function fetchChargeById($payment, $chargeId): Charge; */ public function fetchCharge(Charge $charge): Charge; + /** + * Fetch a chargeback object by combination of payment id, chargeback id and charge id. + * Chargeback ids are not unique to a merchant but to the payment. + * + * @param Payment|string $payment The payment object or payment id to fetch the authorization from. + * @param string $chargebackId The id of the chargeback to fetch. + * + * @return Chargeback|AbstractUnzerResource The fetched chargeback. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function fetchChargebackById(string $paymentId, string $chargebackId, ?string $chargeId): Chargeback; + + /** + * Update local chargeback object. + * + * @param Chargeback $chargeback The chargeback object to be fetched. + * + * @return Chargeback|AbstractUnzerResource The fetched chargeback. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function fetchChargeback(Chargeback $chargeback): Chargeback; + /** * Fetch a cancellation on an authorization (aka reversal). * @@ -328,7 +358,7 @@ public function fetchCharge(Charge $charge): Charge; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchReversalByAuthorization($authorization, $cancellationId): Cancellation; + public function fetchReversalByAuthorization(Authorization $authorization, string $cancellationId): Cancellation; /** * Fetches a cancellation resource on an authorization (aka reversal) via payment and cancellation id. @@ -341,7 +371,7 @@ public function fetchReversalByAuthorization($authorization, $cancellationId): C * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchReversal($payment, $cancellationId): Cancellation; + public function fetchReversal($payment, string $cancellationId): Cancellation; /** * Fetch a cancellation resource on a charge (aka refund) via id. @@ -355,7 +385,7 @@ public function fetchReversal($payment, $cancellationId): Cancellation; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchRefundById($payment, $chargeId, $cancellationId): Cancellation; + public function fetchRefundById($payment, string $chargeId, string $cancellationId): Cancellation; /** * Fetch a cancellation resource on a Charge (aka refund). @@ -368,7 +398,33 @@ public function fetchRefundById($payment, $chargeId, $cancellationId): Cancellat * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchRefund(Charge $charge, $cancellationId): Cancellation; + public function fetchRefund(Charge $charge, string $cancellationId): Cancellation; + + /** + * Fetch a cancellation resource of a charged payment (aka refund). + * + * @param Payment|string $payment The payment object to fetch the cancellation for. + * @param string $cancellationId The id of the cancellation to fetch. + * + * @return Cancellation The fetched cancellation (refund). + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function fetchPaymentRefund($payment, string $cancellationId): Cancellation; + + /** + * Fetch a cancellation resource of an authorized payment (aka reversal). + * + * @param Payment|string $payment The payment object to fetch the cancellation for. + * @param string $cancellationId The id of the cancellation to fetch. + * + * @return Cancellation The fetched cancellation (refund). + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function fetchPaymentReversal($payment, string $cancellationId): Cancellation; /** * Fetch a shipment resource of the given payment by id. @@ -381,5 +437,19 @@ public function fetchRefund(Charge $charge, $cancellationId): Cancellation; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchShipment($payment, $shipmentId): Shipment; + public function fetchShipment($payment, string $shipmentId): Shipment; + + /** + * Get the configuration for the given payment type. + * + * @param BasePaymentType $paymentType + * @param Config|null $config Can be used to add query params to the GET request. + * + * @return Config + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * This will also occur if the given payment type has no configuration. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function fetchConfig(BasePaymentType $paymentType, ?Config $config = null): Config; } diff --git a/vendor/unzerdev/php-sdk/src/Interfaces/UnzerParentInterface.php b/vendor/unzerdev/php-sdk/src/Interfaces/UnzerParentInterface.php index af1fb64..fae0a5b 100644 --- a/vendor/unzerdev/php-sdk/src/Interfaces/UnzerParentInterface.php +++ b/vendor/unzerdev/php-sdk/src/Interfaces/UnzerParentInterface.php @@ -2,26 +2,10 @@ /** * This interface defines the methods for a parent Unzer object. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Interfaces */ + namespace UnzerSDK\Interfaces; use UnzerSDK\Unzer; @@ -47,5 +31,5 @@ public function getUnzerObject(): Unzer; * * @return string */ - public function getUri($appendId = true, $httpMethod = HttpAdapterInterface::REQUEST_GET): string; + public function getUri(bool $appendId = true, string $httpMethod = HttpAdapterInterface::REQUEST_GET): string; } diff --git a/vendor/unzerdev/php-sdk/src/Interfaces/WebhookServiceInterface.php b/vendor/unzerdev/php-sdk/src/Interfaces/WebhookServiceInterface.php index f9ae2d8..48c89e2 100644 --- a/vendor/unzerdev/php-sdk/src/Interfaces/WebhookServiceInterface.php +++ b/vendor/unzerdev/php-sdk/src/Interfaces/WebhookServiceInterface.php @@ -2,26 +2,10 @@ /** * The interface for the WebhookService. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Interfaces */ + namespace UnzerSDK\Interfaces; use UnzerSDK\Exceptions\UnzerApiException; @@ -67,7 +51,7 @@ public function fetchWebhook($webhook): Webhook; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function updateWebhook($webhook): Webhook; + public function updateWebhook(Webhook $webhook): Webhook; /** * Deletes the given Webhook resource. @@ -122,5 +106,5 @@ public function registerMultipleWebhooks(string $url, array $events): array; * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function fetchResourceFromEvent($eventJson = null): AbstractUnzerResource; + public function fetchResourceFromEvent(string $eventJson = null): AbstractUnzerResource; } diff --git a/vendor/unzerdev/php-sdk/src/Resources/AbstractUnzerResource.php b/vendor/unzerdev/php-sdk/src/Resources/AbstractUnzerResource.php index 69aa655..6124a0c 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/AbstractUnzerResource.php +++ b/vendor/unzerdev/php-sdk/src/Resources/AbstractUnzerResource.php @@ -2,30 +2,15 @@ /** * This is the base class for all resource types managed by the api. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Resources */ + namespace UnzerSDK\Resources; use DateTime; use UnzerSDK\Adapter\HttpAdapterInterface; +use UnzerSDK\Constants\AdditionalAttributes; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Unzer; use UnzerSDK\Interfaces\UnzerParentInterface; @@ -36,12 +21,19 @@ use ReflectionProperty; use RuntimeException; use stdClass; + use function count; use function is_array; use function is_callable; use function is_float; use function is_object; +/** + * This is a class representing a resource on Unzer payment API. + * + * @link https://docs.unzer.com/ + * + */ abstract class AbstractUnzerResource implements UnzerParentInterface { /** @var string $id */ @@ -59,8 +51,6 @@ abstract class AbstractUnzerResource implements UnzerParentInterface /** @var array $additionalAttributes */ protected $additionalAttributes = []; - // - /** * Returns the API name of the resource. * @@ -84,22 +74,22 @@ public function getId(): ?string /** * This setter must be public to enable fetching a resource by setting the id and then call fetch. * - * @param int $resourceId + * @param string|null $resourceId * * @return $this */ - public function setId($resourceId): self + public function setId(?string $resourceId): self { $this->id = $resourceId; return $this; } /** - * @param UnzerParentInterface $parentResource + * @param UnzerParentInterface|null $parentResource * * @return $this */ - public function setParentResource($parentResource): self + public function setParentResource(?UnzerParentInterface $parentResource): self { $this->parentResource = $parentResource; return $this; @@ -160,6 +150,16 @@ public function setSpecialParams(array $specialParams): self return $this; } + /** + * Returns the API version for this resource. + * + * @return string + */ + public function getApiVersion(): string + { + return Unzer::API_VERSION; + } + /** * @param array $additionalAttributes * @@ -179,8 +179,11 @@ protected function setAdditionalAttributes(array $additionalAttributes): Abstrac * @param mixed $value * * @return AbstractUnzerResource + * + * @see AdditionalAttributes + * */ - protected function setAdditionalAttribute(string $attribute, $value): AbstractUnzerResource + public function setAdditionalAttribute(string $attribute, $value): AbstractUnzerResource { $this->additionalAttributes[$attribute] = $value; return $this; @@ -191,16 +194,22 @@ protected function setAdditionalAttribute(string $attribute, $value): AbstractUn * * @param string $attribute * + * @see AdditionalAttributes + * * @return mixed */ - protected function getAdditionalAttribute(string $attribute) + public function getAdditionalAttribute(string $attribute) { return $this->additionalAttributes[$attribute] ?? null; } - // - - // + /** + * @return array + */ + public function getAdditionalAttributes() + { + return $this->additionalAttributes; + } /** * {@inheritDoc} @@ -219,7 +228,7 @@ public function getUnzerObject(): Unzer * * @throws RuntimeException */ - public function getUri($appendId = true, $httpMethod = HttpAdapterInterface::REQUEST_GET): string + public function getUri(bool $appendId = true, string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { $uri = [rtrim($this->getParentResource()->getUri(), '/'), $this->getResourcePath($httpMethod)]; if ($appendId) { @@ -236,7 +245,7 @@ public function getUri($appendId = true, $httpMethod = HttpAdapterInterface::REQ /** * This method updates the properties of the resource. * - * @param $object + * @param $object * @param stdClass $response */ private static function updateValues($object, stdClass $response): void @@ -270,10 +279,6 @@ private static function updateValues($object, stdClass $response): void } } - // - - // - /** * @return ResourceService * @@ -312,17 +317,13 @@ protected function fetchResource(AbstractUnzerResource $resource): void $this->getResourceService()->fetchResource($resource); } - // - - // - /** * Specify data which should be serialized to JSON * * @link http://php.net/manual/en/jsonserializable.jsonserialize.php * - * @return mixed data which can be serialized by json_encode, - * which is a value of any type other than a resource. + * @return false|string data which can be serialized by json_encode, + * which is a value of any type other than a resource. */ public function jsonSerialize() { @@ -336,53 +337,13 @@ public function jsonSerialize() */ public function expose() { - // Add resources properties - $properties = get_object_vars($this); - foreach ($properties as $property => $value) { - if (self::propertyShouldBeSkipped($property, $value)) { - unset($properties[$property]); - continue; - } - - // expose child objects if possible - if ($value instanceof self) { - $value = $value->expose(); - } - - // reduce floats to 4 decimal places and update the property in object - if (is_float($value)) { - $value = ValueService::limitFloats($value); - self::setItemProperty($this, $property, $value); - } - - // handle additional values - if ($property === 'additionalAttributes') { - if (!is_array($value) || empty($value)) { - unset($properties[$property]); - continue; - } - $value = $this->exposeAdditionalAttributes($value); - } - - $properties[$property] = $value; - } - //--------------------- - - // Add linked resources if any - $resources = []; - /** - * @var string $attributeName - * @var AbstractUnzerResource $linkedResource - */ - foreach ($this->getLinkedResources() as $attributeName => $linkedResource) { - $resources[$attributeName . 'Id'] = $linkedResource ? $linkedResource->getId() : ''; - } + $properties = $this->exposeProperties(); + $resources = $this->exposeLinkedResources(); if (count($resources) > 0) { ksort($resources); $properties['resources'] = $resources; } - //--------------------- // Add special params if any foreach ($this->getSpecialParams() as $attributeName => $specialParam) { @@ -395,11 +356,11 @@ public function expose() } /** - * @param $value + * @param array $value * * @return array */ - private function exposeAdditionalAttributes($value): array + private function exposeAdditionalAttributes(array $value): array { foreach ($value as $attributeName => $attributeValue) { $attributeValue = ValueService::limitFloats($attributeValue); @@ -412,12 +373,12 @@ private function exposeAdditionalAttributes($value): array /** * Returns true if the given property should be skipped. * - * @param $property - * @param $value + * @param string $property + * @param $value * * @return bool */ - private static function propertyShouldBeSkipped($property, $value): bool + private static function propertyShouldBeSkipped(string $property, $value): bool { $skipProperty = false; @@ -454,12 +415,8 @@ private static function setItemProperty($item, $key, $value): void } } - // - - // - /** - * Return the resources which should be referenced by Id within the resource section of the resource data. + * Return the resources which should be referenced by ID within the resource section of the resource data. * Override this to define the linked resources. * * @return array @@ -477,7 +434,7 @@ public function getLinkedResources(): array * * @return string */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return self::getResourceName($httpMethod); } @@ -488,9 +445,10 @@ protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_G * * @param stdClass $response * @param string $method + * * @noinspection PhpUnusedParameterInspection */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { self::updateValues($this, $response); @@ -517,5 +475,73 @@ public function getExternalId(): ?string return null; } - // + /** + * Exposes properties + * + * @return array + */ + private function exposeProperties(): array + { + $properties = get_object_vars($this); + foreach ($properties as $property => $value) { + if (self::propertyShouldBeSkipped($property, $value)) { + unset($properties[$property]); + continue; + } + + // expose child objects if possible + if ($value instanceof self) { + $value = $value->expose(); + } + + // reduce floats to 4 decimal places and update the property in object + if (is_float($value)) { + $value = ValueService::limitFloats($value); + self::setItemProperty($this, $property, $value); + } + + // handle additional values + if ($property === 'additionalAttributes') { + if (!is_array($value) || empty($value)) { + unset($properties[$property]); + continue; + } + $value = $this->exposeAdditionalAttributes($value); + } + + // handle additionalTransactionData values + if ($property === 'additionalTransactionData') { + foreach ($value as $key => $data) { + if ($data instanceof self) { + $value->$key = $data->expose(); + } + } + } + + $properties[$property] = $value; + } + + return $properties; + } + + /** + * Expose linked resources if any. + * + * @return array + */ + private function exposeLinkedResources(): array + { + $exposedResources = []; + /** + * @var string $attributeName + * @var AbstractUnzerResource $linkedResource + */ + foreach ($this->getLinkedResources() as $attributeName => $linkedResource) { + $resourceId = $linkedResource ? $linkedResource->getId() : null; + if ($resourceId !== null) { + $exposedResources[$attributeName . 'Id'] = $resourceId; + } + } + return $exposedResources; + } } diff --git a/vendor/unzerdev/php-sdk/src/Resources/Basket.php b/vendor/unzerdev/php-sdk/src/Resources/Basket.php index 4f89d70..3ce76ec 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Basket.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Basket.php @@ -1,45 +1,45 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Resources\EmbeddedResources\BasketItem; use stdClass; + use function count; +/** + * This represents the basket resource. + * + * @link https://docs.unzer.com/ + * + */ class Basket extends AbstractUnzerResource { - /** @var float $amountTotalGross */ + /** + * @var float $amountTotalGross + * + * @deprecated since 1.1.5.0 @see $totalValueGross. + */ protected $amountTotalGross = 0.0; - /** @var float $amountTotalDiscount */ + /** + * @var float $amountTotalDiscount + * + * @deprecated since 1.1.5.0 @see Please set $amountDiscountPerUnitGross for each element of $basketItems instead. + */ protected $amountTotalDiscount = 0.0; - /** @var float $amountTotalVat */ + /** + * @var float $amountTotalVat + * + * @deprecated since 1.1.5.0 Please set the $vat in percent for each element of $basketItems instead, if not already happened. The actual amount is not required anymore. + */ protected $amountTotalVat = 0.0; + /** @var float $totalValueGross */ + protected $totalValueGross = 0.0; + /** @var string $currencyCode */ protected $currencyCode; @@ -49,12 +49,14 @@ class Basket extends AbstractUnzerResource /** @var string $note */ protected $note; - /** @var array $basketItems */ + /** @var BasketItem[] $basketItems */ private $basketItems; /** * Basket constructor. * + * @deprecated since 1.1.5.0 Please call constructor without parameters and use setter functions instead. + * * @param float $amountTotalGross * @param string $currencyCode * @param string $orderId @@ -72,10 +74,10 @@ public function __construct( $this->setBasketItems($basketItems); } - // - /** * @return float + * + * @deprecated since 1.1.5.0 @see getTotalValueGross(). */ public function getAmountTotalGross(): float { @@ -85,6 +87,8 @@ public function getAmountTotalGross(): float /** * @param float $amountTotalGross * + * @deprecated since 1.1.5.0 @see setTotalValueGross(). + * * @return Basket */ public function setAmountTotalGross(float $amountTotalGross): Basket @@ -96,6 +100,27 @@ public function setAmountTotalGross(float $amountTotalGross): Basket /** * @return float */ + public function getTotalValueGross(): float + { + return $this->totalValueGross; + } + + /** + * @param float $totalValueGross + * + * @return Basket + */ + public function setTotalValueGross(float $totalValueGross): Basket + { + $this->totalValueGross = $totalValueGross; + return $this; + } + + /** + * @return float + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + */ public function getAmountTotalDiscount(): float { return $this->amountTotalDiscount; @@ -104,6 +129,8 @@ public function getAmountTotalDiscount(): float /** * @param float $amountTotalDiscount * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + * * @return Basket */ public function setAmountTotalDiscount(float $amountTotalDiscount): Basket @@ -114,6 +141,8 @@ public function setAmountTotalDiscount(float $amountTotalDiscount): Basket /** * @return float + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. */ public function getAmountTotalVat(): float { @@ -123,6 +152,8 @@ public function getAmountTotalVat(): float /** * @param float $amountTotalVat * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + * * @return Basket */ public function setAmountTotalVat(float $amountTotalVat): Basket @@ -171,7 +202,7 @@ public function getNote(): ?string * * @return Basket */ - public function setNote($note): Basket + public function setNote(?string $note): Basket { $this->note = $note; return $this; @@ -241,15 +272,11 @@ public function addBasketItem(BasketItem $basketItem): Basket * * @return BasketItem|null */ - public function getBasketItemByIndex($index): ?BasketItem + public function getBasketItemByIndex(int $index): ?BasketItem { return $this->basketItems[$index] ?? null; } - // - - // - /** * Add the dynamically set meta data. * {@inheritDoc} @@ -269,6 +296,17 @@ public function expose(): array return $returnArray; } + /** + * {@inheritDoc} + */ + public function getApiVersion(): string + { + if (!empty($this->getTotalValueGross())) { + return 'v2'; + } + return parent::getApiVersion(); + } + /** * Returns the key of the last BasketItem in the Array. * @@ -283,7 +321,7 @@ private function getKeyOfLastBasketItemAdded() /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'baskets'; } @@ -291,7 +329,7 @@ protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_G /** * {@inheritDoc} */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -305,6 +343,4 @@ public function handleResponse(stdClass $response, $method = HttpAdapterInterfac $this->setBasketItems($items); } } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/Config.php b/vendor/unzerdev/php-sdk/src/Resources/Config.php new file mode 100644 index 0000000..8d61ce0 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/Config.php @@ -0,0 +1,167 @@ +dataPrivacyConsent; + } + + /** + * @param string $dataPrivacyConsent + * + * @return Config + */ + public function setDataPrivacyConsent(string $dataPrivacyConsent): Config + { + $this->dataPrivacyConsent = $dataPrivacyConsent; + return $this; + } + + /** + * @return string + */ + public function getDataPrivacyDeclaration(): ?string + { + return $this->dataPrivacyDeclaration; + } + + /** + * @param string $dataPrivacyDeclaration + * + * @return Config + */ + public function setDataPrivacyDeclaration(string $dataPrivacyDeclaration): Config + { + $this->dataPrivacyDeclaration = $dataPrivacyDeclaration; + return $this; + } + + /** + * @return string + */ + public function getTermsAndConditions(): ?string + { + return $this->termsAndConditions; + } + + /** + * @param string $termsAndConditions + * + * @return Config + */ + public function setTermsAndConditions(string $termsAndConditions): Config + { + $this->termsAndConditions = $termsAndConditions; + return $this; + } + + /** Get query parameter used for GET request. + * + * @return array + */ + public function getQueryParams(): array + { + return $this->queryParams; + } + + /** Set query parameter used for GET request. + * + * @param array $queryParams + * + * @return Config + */ + public function setQueryParams(array $queryParams): Config + { + $this->queryParams = $queryParams; + return $this; + } + + /** Get the 'customerType' value from query parameter array. + * + * @return string + */ + public function getCustomerType(): ?string + { + return ($this->queryParams[self::QUERY_KEY_CUSTOMER_TYPE] ?? null); + } + + /** Set the 'customerType' as query parameter for GET requests. + * + * @param string|null $customerType + * + * @return Config + */ + public function setCustomerType(?string $customerType): self + { + $this->queryParams[self::QUERY_KEY_CUSTOMER_TYPE] = $customerType; + return $this; + } + + /** Get the 'country' value from query parameter array. + * + * @return string + */ + public function getCountry(): ?string + { + return ($this->queryParams[self::PARAM_KEY_COUNTRY] ?? null); + } + + /** Set the 'country' as query parameter for GET requests. + * + * @param string|null $country + * + * @return Config + */ + public function setCountry(?string $country): self + { + $this->queryParams[self::PARAM_KEY_COUNTRY] = $country; + return $this; + } + + /** + * {@inheritDoc} + */ + public function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string + { + return parent::getResourcePath($httpMethod) . $this->getQueryString(); + } + + /** Return the query string created from 'queryParams'. + * + * @return string|null + */ + private function getQueryString(): ?string + { + $query = http_build_query($this->queryParams); + return $query ? '?' . $query : null; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/Customer.php b/vendor/unzerdev/php-sdk/src/Resources/Customer.php index 5f48970..08933a7 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Customer.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Customer.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; use UnzerSDK\Adapter\HttpAdapterInterface; @@ -30,8 +8,15 @@ use UnzerSDK\Resources\EmbeddedResources\CompanyInfo; use UnzerSDK\Traits\HasGeoLocation; use stdClass; + use function in_array; +/** + * This represents the customer resource. + * + * @link https://docs.unzer.com/ + * + */ class Customer extends AbstractUnzerResource { use HasGeoLocation; @@ -72,6 +57,9 @@ class Customer extends AbstractUnzerResource /** @var CompanyInfo $companyInfo */ protected $companyInfo; + /** @var string $language */ + protected $language; + /** * Customer constructor. */ @@ -81,8 +69,6 @@ public function __construct() $this->shippingAddress = new Address(); } - // - /** * @return string|null */ @@ -92,11 +78,11 @@ public function getFirstname(): ?string } /** - * @param string $firstname + * @param string|null $firstname * * @return Customer */ - public function setFirstname($firstname): Customer + public function setFirstname(?string $firstname): Customer { $this->firstname = $firstname; return $this; @@ -111,11 +97,11 @@ public function getLastname(): ?string } /** - * @param string $lastname + * @param string|null $lastname * * @return Customer */ - public function setLastname($lastname): Customer + public function setLastname(?string $lastname): Customer { $this->lastname = $lastname; return $this; @@ -130,11 +116,11 @@ public function getSalutation(): string } /** - * @param string $salutation + * @param string|null $salutation * * @return Customer */ - public function setSalutation($salutation): Customer + public function setSalutation(?string $salutation): Customer { $allowedSalutations = [Salutations::MR, Salutations::MRS, Salutations::UNKNOWN]; $this->salutation = in_array($salutation, $allowedSalutations, true) ? $salutation : Salutations::UNKNOWN; @@ -150,11 +136,11 @@ public function getBirthDate(): ?string } /** - * @param string $birthday + * @param string|null $birthday * * @return Customer */ - public function setBirthDate($birthday): Customer + public function setBirthDate(?string $birthday): Customer { $this->birthDate = $birthday; return $this; @@ -169,11 +155,11 @@ public function getCompany(): ?string } /** - * @param string $company + * @param string|null $company * * @return Customer */ - public function setCompany($company): Customer + public function setCompany(?string $company): Customer { $this->company = $company; return $this; @@ -188,11 +174,11 @@ public function getEmail(): ?string } /** - * @param string $email + * @param string|null $email * * @return Customer */ - public function setEmail($email): Customer + public function setEmail(?string $email): Customer { $this->email = $email; return $this; @@ -207,11 +193,11 @@ public function getPhone(): ?string } /** - * @param string $phone + * @param string|null $phone * * @return Customer */ - public function setPhone($phone): Customer + public function setPhone(?string $phone): Customer { $this->phone = $phone; return $this; @@ -226,11 +212,11 @@ public function getMobile(): ?string } /** - * @param string $mobile + * @param string|null $mobile * * @return Customer */ - public function setMobile($mobile): Customer + public function setMobile(?string $mobile): Customer { $this->mobile = $mobile; return $this; @@ -283,11 +269,11 @@ public function getCustomerId(): ?string } /** - * @param string $customerId + * @param string|null $customerId * * @return Customer */ - public function setCustomerId($customerId): Customer + public function setCustomerId(?string $customerId): Customer { $this->customerId = $customerId; return $this; @@ -302,32 +288,43 @@ public function getCompanyInfo(): ?CompanyInfo } /** - * @param CompanyInfo $companyInfo + * @param CompanyInfo|null $companyInfo * * @return Customer */ - public function setCompanyInfo(CompanyInfo $companyInfo): Customer + public function setCompanyInfo(?CompanyInfo $companyInfo): Customer { $this->companyInfo = $companyInfo; return $this; } - // + /** + * @return string + */ + public function getLanguage(): string + { + return $this->language; + } - // + /** + * @param string|null $language + * + * @return Customer + */ + public function setLanguage(?string $language): Customer + { + $this->language = $language; + return $this; + } /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'customers'; } - // - - // - /** * {@inheritDoc} */ @@ -339,14 +336,13 @@ public function getExternalId(): ?string /** * {@inheritDoc} */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { if (isset($response->companyInfo) && $this->companyInfo === null) { $this->companyInfo = new CompanyInfo(); + $this->companyInfo->instantiateObjectsFromResponse($response->companyInfo); } parent::handleResponse($response, $method); } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/CustomerFactory.php b/vendor/unzerdev/php-sdk/src/Resources/CustomerFactory.php index 83bb9cf..777c142 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/CustomerFactory.php +++ b/vendor/unzerdev/php-sdk/src/Resources/CustomerFactory.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; use UnzerSDK\Constants\CompanyCommercialSectorItems; @@ -29,6 +7,12 @@ use UnzerSDK\Resources\EmbeddedResources\Address; use UnzerSDK\Resources\EmbeddedResources\CompanyInfo; +/** + * Creates the different Customer objects. + * + * @link https://docs.unzer.com/ + * + */ class CustomerFactory { /** diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Address.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Address.php index 5162c40..48e3b6f 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Address.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Address.php @@ -1,31 +1,15 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources */ -namespace UnzerSDK\Resources\EmbeddedResources; - -use UnzerSDK\Resources\AbstractUnzerResource; - class Address extends AbstractUnzerResource { /** @var string $name */ @@ -46,7 +30,8 @@ class Address extends AbstractUnzerResource /** @var string country */ protected $country; - // + /** @var string|null shippingType */ + protected $shippingType; /** * @return string|null @@ -57,11 +42,11 @@ public function getName(): ?string } /** - * @param string $name + * @param string|null $name * * @return Address */ - public function setName($name): Address + public function setName(?string $name): Address { $this->name = $name; return $this; @@ -76,11 +61,11 @@ public function getStreet(): ?string } /** - * @param string $street + * @param string|null $street * * @return Address */ - public function setStreet($street): Address + public function setStreet(?string $street): Address { $this->street = $street; return $this; @@ -95,11 +80,11 @@ public function getState(): ?string } /** - * @param string $state + * @param string|null $state * * @return Address */ - public function setState($state): Address + public function setState(?string $state): Address { $this->state = $state; return $this; @@ -114,11 +99,11 @@ public function getZip(): ?string } /** - * @param string $zip + * @param string|null $zip * * @return Address */ - public function setZip($zip): Address + public function setZip(?string $zip): Address { $this->zip = $zip; return $this; @@ -133,11 +118,11 @@ public function getCity(): ?string } /** - * @param string $city + * @param string|null $city * * @return Address */ - public function setCity($city): Address + public function setCity(?string $city): Address { $this->city = $city; return $this; @@ -152,15 +137,32 @@ public function getCountry(): ?string } /** - * @param string $country + * @param string|null $country * * @return Address */ - public function setCountry($country): Address + public function setCountry(?string $country): Address { $this->country = $country; return $this; } - // + /** + * @return string|null + */ + public function getShippingType(): ?string + { + return $this->shippingType; + } + + /** + * @param string|null $shippingType + * + * @return Address + */ + public function setShippingType(?string $shippingType): Address + { + $this->shippingType = $shippingType; + return $this; + } } diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Amount.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Amount.php index 6a82d5d..f915180 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Amount.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Amount.php @@ -1,31 +1,15 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources */ -namespace UnzerSDK\Resources\EmbeddedResources; - -use UnzerSDK\Resources\AbstractUnzerResource; - class Amount extends AbstractUnzerResource { private $total = 0.0; @@ -36,8 +20,6 @@ class Amount extends AbstractUnzerResource /** @var string $currency */ private $currency; - // - /** * @return float */ @@ -132,6 +114,4 @@ protected function setCurrency(string $currency): self $this->currency = $currency; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/ApplePayHeader.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/ApplePayHeader.php index 094f12f..c33d46a 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/ApplePayHeader.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/ApplePayHeader.php @@ -1,31 +1,15 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources */ -namespace UnzerSDK\Resources\EmbeddedResources; - -use UnzerSDK\Resources\AbstractUnzerResource; - class ApplePayHeader extends AbstractUnzerResource { /** @var string|null */ diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/BasketItem.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/BasketItem.php index fcfdad5..bffe0eb 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/BasketItem.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/BasketItem.php @@ -1,31 +1,15 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources */ -namespace UnzerSDK\Resources\EmbeddedResources; - -use UnzerSDK\Resources\AbstractUnzerResource; - class BasketItem extends AbstractUnzerResource { /** @var string $basketItemReferenceId */ @@ -37,19 +21,45 @@ class BasketItem extends AbstractUnzerResource /** @var float $vat */ protected $vat = 0.0; - /** @var float $amountDiscount */ + /** + * @var float $amountDiscount + * + * @deprecated since 1.1.5.0 @see $amountDiscountPerUnitGross. + */ protected $amountDiscount = 0.0; - /** @var float $amountGross */ + /** @var float $amountDiscountPerUnitGross */ + protected $amountDiscountPerUnitGross = 0.0; + + /** + * @var float $amountGross + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + */ protected $amountGross = 0.0; - /** @var float $amountVat */ + /** + * @var float $amountVat + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + */ protected $amountVat = 0.0; - /** @var float $amountPerUnit */ + /** + * @var float $amountPerUnit + * + * @deprecated since 1.1.5.0 @see amountPerUnitGross + */ protected $amountPerUnit = 0.0; - /** @var float $amountNet */ + /** @var float $amountPerUnitGross */ + protected $amountPerUnitGross = 0.0; + + /** + * @var float $amountNet + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + */ protected $amountNet = 0.0; /** @var string $unit */ @@ -70,6 +80,8 @@ class BasketItem extends AbstractUnzerResource /** * BasketItem constructor. * + * @deprecated since 1.1.5.0 Please call constructor without parameters and use setter functions instead. + * * @param string $title * @param float $amountNet * @param float $amountPerUnit @@ -87,8 +99,6 @@ public function __construct( $this->setAmountPerUnit($amountPerUnit); } - // - /** * @return string|null */ @@ -102,7 +112,7 @@ public function getBasketItemReferenceId(): ?string * * @return BasketItem */ - public function setBasketItemReferenceId($basketItemReferenceId): BasketItem + public function setBasketItemReferenceId(?string $basketItemReferenceId): BasketItem { $this->basketItemReferenceId = $basketItemReferenceId; return $this; @@ -148,6 +158,8 @@ public function setVat(float $vat): BasketItem /** * @return float + * + * @deprecated since 1.1.5.0 @see $getAmountDiscountPerUnitGross. */ public function getAmountDiscount(): float { @@ -157,6 +169,8 @@ public function getAmountDiscount(): float /** * @param float $amountDiscount * + * @deprecated since 1.1.5.0 @see $setAmountDiscountPerUnitGross. + * * @return BasketItem */ public function setAmountDiscount(float $amountDiscount): BasketItem @@ -167,6 +181,8 @@ public function setAmountDiscount(float $amountDiscount): BasketItem /** * @return float + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. */ public function getAmountGross(): float { @@ -176,6 +192,8 @@ public function getAmountGross(): float /** * @param float $amountGross * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + * * @return BasketItem */ public function setAmountGross(float $amountGross): BasketItem @@ -187,6 +205,46 @@ public function setAmountGross(float $amountGross): BasketItem /** * @return float */ + public function getAmountDiscountPerUnitGross(): float + { + return $this->amountDiscountPerUnitGross; + } + + /** + * @param float $amountDiscountPerUnitGross + * + * @return BasketItem + */ + public function setAmountDiscountPerUnitGross(float $amountDiscountPerUnitGross): BasketItem + { + $this->amountDiscountPerUnitGross = $amountDiscountPerUnitGross; + return $this; + } + + /** + * @return float + */ + public function getAmountPerUnitGross(): float + { + return $this->amountPerUnitGross; + } + + /** + * @param float $amountPerUnitGross + * + * @return BasketItem + */ + public function setAmountPerUnitGross(float $amountPerUnitGross): BasketItem + { + $this->amountPerUnitGross = $amountPerUnitGross; + return $this; + } + + /** + * @return float + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + */ public function getAmountVat(): float { return $this->amountVat; @@ -195,6 +253,8 @@ public function getAmountVat(): float /** * @param float $amountVat * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + * * @return BasketItem */ public function setAmountVat(float $amountVat): BasketItem @@ -205,6 +265,8 @@ public function setAmountVat(float $amountVat): BasketItem /** * @return float + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. */ public function getAmountPerUnit(): float { @@ -214,6 +276,8 @@ public function getAmountPerUnit(): float /** * @param float $amountPerUnit * + * @deprecated since 1.1.5.0 @see setAmountPerUnitGross + * * @return BasketItem */ public function setAmountPerUnit(float $amountPerUnit): BasketItem @@ -224,6 +288,8 @@ public function setAmountPerUnit(float $amountPerUnit): BasketItem /** * @return float + * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. */ public function getAmountNet(): float { @@ -233,6 +299,8 @@ public function getAmountNet(): float /** * @param float $amountNet * + * @deprecated since 1.1.5.0 Property is redundant and is no longer needed. + * * @return BasketItem */ public function setAmountNet(float $amountNet): BasketItem @@ -254,7 +322,7 @@ public function getUnit(): ?string * * @return BasketItem */ - public function setUnit($unit): BasketItem + public function setUnit(?string $unit): BasketItem { $this->unit = $unit; return $this; @@ -292,7 +360,7 @@ public function getImageUrl(): ?string * * @return BasketItem */ - public function setImageUrl($imageUrl): BasketItem + public function setImageUrl(?string $imageUrl): BasketItem { $this->imageUrl = $imageUrl; return $this; @@ -311,7 +379,7 @@ public function getSubTitle(): ?string * * @return BasketItem */ - public function setSubTitle($subTitle): BasketItem + public function setSubTitle(?string $subTitle): BasketItem { $this->subTitle = $subTitle; return $this; @@ -333,11 +401,9 @@ public function getType(): ?string * * @return BasketItem */ - public function setType($type): BasketItem + public function setType(?string $type): BasketItem { $this->type = $type; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CardDetails.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CardDetails.php index 557313a..1cfc65f 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CardDetails.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CardDetails.php @@ -1,31 +1,15 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources */ -namespace UnzerSDK\Resources\EmbeddedResources; - -use UnzerSDK\Resources\AbstractUnzerResource; - class CardDetails extends AbstractUnzerResource { /** @var string|null $cardType */ @@ -49,8 +33,6 @@ class CardDetails extends AbstractUnzerResource /** @var string|null $issuerPhoneNumber */ protected $issuerPhoneNumber; - // - /** * @return string|null */ @@ -64,7 +46,7 @@ public function getCardType(): ?string * * @return CardDetails */ - protected function setCardType($cardType): CardDetails + protected function setCardType(?string $cardType): CardDetails { $this->cardType = $cardType; return $this; @@ -83,7 +65,7 @@ public function getAccount(): ?string * * @return CardDetails */ - protected function setAccount($account): CardDetails + protected function setAccount(?string $account): CardDetails { $this->account = $account; return $this; @@ -102,7 +84,7 @@ public function getCountryIsoA2(): ?string * * @return CardDetails */ - protected function setCountryIsoA2($countryIsoA2): CardDetails + protected function setCountryIsoA2(?string $countryIsoA2): CardDetails { $this->countryIsoA2 = $countryIsoA2; return $this; @@ -121,7 +103,7 @@ public function getCountryName(): ?string * * @return CardDetails */ - protected function setCountryName($countryName): CardDetails + protected function setCountryName(?string $countryName): CardDetails { $this->countryName = $countryName; return $this; @@ -140,7 +122,7 @@ public function getIssuerName(): ?string * * @return CardDetails */ - protected function setIssuerName($issuerName): CardDetails + protected function setIssuerName(?string $issuerName): CardDetails { $this->issuerName = $issuerName; return $this; @@ -159,7 +141,7 @@ public function getIssuerUrl(): ?string * * @return CardDetails */ - protected function setIssuerUrl($issuerUrl): CardDetails + protected function setIssuerUrl(?string $issuerUrl): CardDetails { $this->issuerUrl = $issuerUrl; return $this; @@ -178,11 +160,9 @@ public function getIssuerPhoneNumber(): ?string * * @return CardDetails */ - protected function setIssuerPhoneNumber($issuerPhoneNumber): CardDetails + protected function setIssuerPhoneNumber(?string $issuerPhoneNumber): CardDetails { $this->issuerPhoneNumber = $issuerPhoneNumber; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CardTransactionData.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CardTransactionData.php new file mode 100644 index 0000000..4d6bdb0 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CardTransactionData.php @@ -0,0 +1,79 @@ +recurrenceType; + } + + /** + * @param string|null $recurrenceType + * + * @return CardTransactionData + */ + public function setRecurrenceType(?string $recurrenceType): CardTransactionData + { + $this->recurrenceType = $recurrenceType; + + return $this; + } + + /** + * @return string|null + */ + public function getLiability(): ?string + { + return $this->liability; + } + + /** + * @param string|null $liability + * + * @return CardTransactionData + */ + public function setLiability(?string $liability): CardTransactionData + { + $this->liability = $liability; + return $this; + } + + /** + * @return string|null + */ + public function getExemptionType(): ?string + { + return $this->exemptionType; + } + + /** + * @param string|null $exemptionType + * + * @return CardTransactionData + */ + public function setExemptionType(?string $exemptionType): CardTransactionData + { + $this->exemptionType = $exemptionType; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CompanyInfo.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CompanyInfo.php index 0deafec..8b9026c 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CompanyInfo.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CompanyInfo.php @@ -1,33 +1,19 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources - */ + namespace UnzerSDK\Resources\EmbeddedResources; use UnzerSDK\Constants\CompanyCommercialSectorItems; use UnzerSDK\Resources\AbstractUnzerResource; +use stdClass; + use function is_string; +/** + * Company info class for B2B customer classes. + * + * @link https://docs.unzer.com/ + * + */ class CompanyInfo extends AbstractUnzerResource { /** @var string $registrationType */ @@ -42,7 +28,11 @@ class CompanyInfo extends AbstractUnzerResource /** @var string $commercialSector */ protected $commercialSector = CompanyCommercialSectorItems::OTHER; - // + /** @var string|null $companyType */ + protected $companyType; + + /** @var CompanyOwner|null $owner */ + protected $owner; /** * @return string|null @@ -57,7 +47,7 @@ public function getRegistrationType(): ?string * * @return CompanyInfo */ - public function setRegistrationType($registrationType): CompanyInfo + public function setRegistrationType(?string $registrationType): CompanyInfo { $this->registrationType = $this->removeRestrictedSymbols($registrationType); return $this; @@ -76,7 +66,7 @@ public function getCommercialRegisterNumber(): ?string * * @return CompanyInfo */ - public function setCommercialRegisterNumber($commercialRegisterNumber): CompanyInfo + public function setCommercialRegisterNumber(?string $commercialRegisterNumber): CompanyInfo { $this->commercialRegisterNumber = empty($commercialRegisterNumber) ? $commercialRegisterNumber : $this->removeRestrictedSymbols($commercialRegisterNumber); @@ -96,7 +86,7 @@ public function getFunction(): ?string * * @return CompanyInfo */ - public function setFunction($function): CompanyInfo + public function setFunction(?string $function): CompanyInfo { $this->function = $this->removeRestrictedSymbols($function); return $this; @@ -121,9 +111,57 @@ public function setCommercialSector(string $commercialSector): CompanyInfo return $this; } - // + /** + * @return string|null + */ + public function getCompanyType(): ?string + { + return $this->companyType; + } + + /** + * @param string|null $companyType + * + * @return CompanyInfo + */ + public function setCompanyType(?string $companyType): CompanyInfo + { + $this->companyType = $companyType; + return $this; + } + + /** + * @return CompanyOwner|null + */ + public function getOwner(): ?CompanyOwner + { + return $this->owner; + } - // + /** + * @param CompanyOwner|null $owner + * + * @return CompanyInfo + */ + public function setOwner(?CompanyOwner $owner): CompanyInfo + { + $this->owner = $owner; + return $this; + } + + /** + * Create instances of necessary properties to handle API responses. + * + * @param stdClass $response + * + * @return void + */ + public function instantiateObjectsFromResponse(stdClass $response): void + { + if (isset($response->owner) && $this->owner === null) { + $this->owner = new CompanyOwner(); + } + } /** * Removes some restricted symbols from the given value. @@ -132,7 +170,7 @@ public function setCommercialSector(string $commercialSector): CompanyInfo * * @return mixed */ - private function removeRestrictedSymbols($value) + private function removeRestrictedSymbols(?string $value) { if (!is_string($value)) { return $value; @@ -140,6 +178,4 @@ private function removeRestrictedSymbols($value) return str_replace(['<', '>'], '', $value); } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CompanyOwner.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CompanyOwner.php new file mode 100644 index 0000000..ab69350 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/CompanyOwner.php @@ -0,0 +1,80 @@ +firstname; + } + + /** + * @param string|null $firstname + * + * @return CompanyOwner + */ + public function setFirstname(?string $firstname): CompanyOwner + { + $this->firstname = $firstname; + return $this; + } + + /** + * @return string|null + */ + public function getLastname(): ?string + { + return $this->lastname; + } + + /** + * @param string|null $lastname + * + * @return CompanyOwner + */ + public function setLastname(?string $lastname): CompanyOwner + { + $this->lastname = $lastname; + return $this; + } + + /** + * @return string|null + */ + public function getBirthdate(): ?string + { + return $this->birthdate; + } + + /** + * @param string|null $birthdate + * + * @return CompanyOwner + */ + public function setBirthdate(?string $birthdate): CompanyOwner + { + $this->birthdate = $birthdate; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GeoLocation.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GeoLocation.php index ac5c980..c47238f 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GeoLocation.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GeoLocation.php @@ -1,31 +1,15 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources */ -namespace UnzerSDK\Resources\EmbeddedResources; - -use UnzerSDK\Resources\AbstractUnzerResource; - class GeoLocation extends AbstractUnzerResource { /** @var string|null $clientIp */ @@ -34,8 +18,6 @@ class GeoLocation extends AbstractUnzerResource /** @var string|null $countryCode */ private $countryCode; - // - /** * @return string|null */ @@ -49,7 +31,7 @@ public function getClientIp(): ?string * * @return GeoLocation */ - protected function setClientIp($clientIp): GeoLocation + protected function setClientIp(?string $clientIp): GeoLocation { $this->clientIp = $clientIp; return $this; @@ -68,7 +50,7 @@ public function getCountryCode(): ?string * * @return GeoLocation */ - protected function setCountryCode($countryCode): GeoLocation + protected function setCountryCode(?string $countryCode): GeoLocation { $this->countryCode = $countryCode; return $this; @@ -79,10 +61,8 @@ protected function setCountryCode($countryCode): GeoLocation * * @return GeoLocation */ - protected function setCountryIsoA2($countryCode): GeoLocation + protected function setCountryIsoA2(?string $countryCode): GeoLocation { return $this->setCountryCode($countryCode); } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/IntermediateSigningKey.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/IntermediateSigningKey.php new file mode 100644 index 0000000..1964a77 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/IntermediateSigningKey.php @@ -0,0 +1,52 @@ +signedKey; + } + + public function setSignedKey(SignedKey $signedKey): IntermediateSigningKey + { + $this->signedKey = $signedKey; + return $this; + } + + public function getSignatures(): array + { + return $this->signatures; + } + + public function setSignatures(array $signatures): IntermediateSigningKey + { + $this->signatures = $signatures; + return $this; + } + + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void + { + parent::handleResponse($response, $method); + + if (isset($response->signedKey)) { + $this->signedKey = new SignedKey(); + $this->signedKey->handleResponse($response->signedKey); + } + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/SignedKey.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/SignedKey.php new file mode 100644 index 0000000..103aca1 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/SignedKey.php @@ -0,0 +1,50 @@ +keyExpiration = $keyExpiration; + $this->keyValue = $keyValue; + } + + public function getKeyExpiration(): string + { + return $this->keyExpiration; + } + + public function setKeyExpiration(string $keyExpiration): SignedKey + { + $this->keyExpiration = $keyExpiration; + return $this; + } + + public function getKeyValue(): string + { + return $this->keyValue; + } + + public function setKeyValue(string $keyValue): SignedKey + { + $this->keyValue = $keyValue; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/SignedMessage.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/SignedMessage.php new file mode 100644 index 0000000..647474d --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/GooglePay/SignedMessage.php @@ -0,0 +1,62 @@ +tag = $tag; + $this->ephemeralPublicKey = $ephemeralPublicKey; + $this->encryptedMessage = $encryptedMessage; + } + + public function getTag(): string + { + return $this->tag; + } + + public function setTag(string $tag): SignedMessage + { + $this->tag = $tag; + return $this; + } + + public function getEphemeralPublicKey(): string + { + return $this->ephemeralPublicKey; + } + + public function setEphemeralPublicKey(string $ephemeralPublicKey): SignedMessage + { + $this->ephemeralPublicKey = $ephemeralPublicKey; + return $this; + } + + public function getEncryptedMessage(): string + { + return $this->encryptedMessage; + } + + public function setEncryptedMessage(string $encryptedMessage): SignedMessage + { + $this->encryptedMessage = $encryptedMessage; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Message.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Message.php index b3094c7..97a0e8b 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Message.php +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Message.php @@ -1,31 +1,15 @@ - * - * @package UnzerSDK\Resources\EmbeddedResources */ -namespace UnzerSDK\Resources\EmbeddedResources; - -use UnzerSDK\Resources\AbstractUnzerResource; - class Message extends AbstractUnzerResource { /** @var string $code */ @@ -37,8 +21,6 @@ class Message extends AbstractUnzerResource /** @var string $merchant */ private $merchant = ''; - // - /** * @return string */ @@ -90,11 +72,9 @@ public function getMerchant(): ?string * * @return Message */ - protected function setMerchant($merchant): Message + protected function setMerchant(?string $merchant): Message { $this->merchant = $merchant; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentPlan.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentPlan.php new file mode 100644 index 0000000..344a935 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentPlan.php @@ -0,0 +1,162 @@ +secciUrl; + } + + /** + * @param string $secciUrl + * + * @return InstallmentPlan + */ + public function setSecciUrl(string $secciUrl): InstallmentPlan + { + $this->secciUrl = $secciUrl; + return $this; + } + + /** + * @return int + */ + public function getNumberOfRates(): int + { + return $this->numberOfRates; + } + + /** + * @param int $numberOfRates + * + * @return InstallmentPlan + */ + public function setNumberOfRates(int $numberOfRates): InstallmentPlan + { + $this->numberOfRates = $numberOfRates; + return $this; + } + + /** + * @return mixed + */ + public function getTotalAmount() + { + return $this->totalAmount; + } + + /** + * @param mixed $totalAmount + * + * @return InstallmentPlan + */ + public function setTotalAmount($totalAmount) + { + $this->totalAmount = $totalAmount; + return $this; + } + + /** + * @return mixed + */ + public function getNominalInterestRate() + { + return $this->nominalInterestRate; + } + + /** + * @param mixed $nominalInterestRate + * + * @return InstallmentPlan + */ + public function setNominalInterestRate($nominalInterestRate) + { + $this->nominalInterestRate = $nominalInterestRate; + return $this; + } + + /** + * @return float + */ + public function getEffectiveInterestRate(): float + { + return $this->effectiveInterestRate; + } + + /** + * @param float $effectiveInterestRate + * + * @return InstallmentPlan + */ + public function setEffectiveInterestRate(float $effectiveInterestRate): InstallmentPlan + { + $this->effectiveInterestRate = $effectiveInterestRate; + return $this; + } + + /** + * @return InstallmentRate[]|null + */ + public function getInstallmentRates(): ?array + { + return $this->installmentRates; + } + + /** + * @param InstallmentRate[] $installmentRates + * + * @return InstallmentPlan + */ + protected function setInstallmentRates(array $installmentRates): InstallmentPlan + { + $this->installmentRates = $installmentRates; + return $this; + } + + /** + * {@inheritDoc} + */ + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void + { + parent::handleResponse($response, $method); + + if (isset($response->installmentRates)) { + $rates = []; + foreach ($response->installmentRates as $rate) { + $rates[] = new InstallmentRate($rate->date, $rate->rate); + } + $this->setInstallmentRates($rates); + } + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentPlansQuery.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentPlansQuery.php new file mode 100644 index 0000000..7d949c4 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentPlansQuery.php @@ -0,0 +1,110 @@ +amount = $amount; + $this->currency = $currency; + $this->country = $country; + $this->customerType = $customerType; + } + + /** + * @return float + */ + public function getAmount(): float + { + return $this->amount; + } + + /** + * @param float $amount + * + * @return InstallmentPlansQuery + */ + public function setAmount(float $amount): InstallmentPlansQuery + { + $this->amount = $amount; + return $this; + } + + /** + * @return string + */ + public function getCurrency(): string + { + return $this->currency; + } + + /** + * @param string $currency + * + * @return InstallmentPlansQuery + */ + public function setCurrency(string $currency): InstallmentPlansQuery + { + $this->currency = $currency; + return $this; + } + + /** + * @return string + */ + public function getCountry(): string + { + return $this->country; + } + + /** + * @param string $country + * + * @return InstallmentPlansQuery + */ + public function setCountry(string $country): InstallmentPlansQuery + { + $this->country = $country; + return $this; + } + + /** + * @return string + */ + public function getCustomerType(): string + { + return $this->customerType; + } + + /** + * @param string $customerType + * + * @return InstallmentPlansQuery + */ + public function setCustomerType(string $customerType): InstallmentPlansQuery + { + $this->customerType = $customerType; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentRate.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentRate.php new file mode 100644 index 0000000..d65ed0e --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/Paylater/InstallmentRate.php @@ -0,0 +1,66 @@ +date = $date; + $this->rate = $rate; + } + + /** + * @return string|null + */ + public function getDate(): ?string + { + return $this->date; + } + + /** + * @param string|null $date + * + * @return InstallmentRate + */ + public function setDate(?string $date): InstallmentRate + { + $this->date = $date; + return $this; + } + + /** + * @return string|null + */ + public function getRate(): ?string + { + return $this->rate; + } + + /** + * @param string|null $rate + * + * @return InstallmentRate + */ + public function setRate(?string $rate): InstallmentRate + { + $this->rate = $rate; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/RiskData.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/RiskData.php new file mode 100644 index 0000000..cc43919 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/RiskData.php @@ -0,0 +1,171 @@ +threatMetrixId; + } + + /** + * @param string|null $threatMetrixId + * + * @return RiskData + */ + public function setThreatMetrixId(?string $threatMetrixId): RiskData + { + $this->threatMetrixId = $threatMetrixId; + return $this; + } + + /** + * @return string|null + */ + public function getRegistrationLevel(): ?string + { + return $this->registrationLevel; + } + + /** + * @param string|null $registrationLevel + * + * @return RiskData + */ + public function setRegistrationLevel(?string $registrationLevel): RiskData + { + $this->registrationLevel = $registrationLevel; + return $this; + } + + /** + * @return string|null + */ + public function getRegistrationDate(): ?string + { + return $this->registrationDate; + } + + /** + * @param string|null $registrationDate Dateformat must be "YYYYMMDD". + * + * @return RiskData + */ + public function setRegistrationDate(?string $registrationDate): RiskData + { + $this->registrationDate = $registrationDate; + return $this; + } + + /** + * @return string|null + */ + public function getCustomerId(): ?string + { + return $this->customerId; + } + + /** + * @param string|null $customerId + * + * @return RiskData + */ + public function setCustomerId(?string $customerId): RiskData + { + $this->customerId = $customerId; + return $this; + } + + /** + * @return string|null + */ + public function getCustomerGroup(): ?string + { + return $this->customerGroup; + } + + /** + * @param string|null $customerGroup + * + * @see CustomerGroups + * + * @return RiskData + */ + public function setCustomerGroup(?string $customerGroup): RiskData + { + $this->customerGroup = $customerGroup; + return $this; + } + + /** + * @return int|null + */ + public function getConfirmedOrders(): ?int + { + return $this->confirmedOrders; + } + + /** + * @param int|null $confirmedOrders + * + * @return RiskData + */ + public function setConfirmedOrders(?int $confirmedOrders): RiskData + { + $this->confirmedOrders = $confirmedOrders; + return $this; + } + + /** + * @return float|null + */ + public function getConfirmedAmount(): ?float + { + return $this->confirmedAmount; + } + + /** + * @param float|null $confirmedAmount + * + * @return RiskData + */ + public function setConfirmedAmount(?float $confirmedAmount): RiskData + { + $this->confirmedAmount = $confirmedAmount; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/ShippingData.php b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/ShippingData.php new file mode 100644 index 0000000..9529bac --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/EmbeddedResources/ShippingData.php @@ -0,0 +1,80 @@ +deliveryTrackingId; + } + + /** + * @param string|null $deliveryTrackingId + * + * @return ShippingData + */ + public function setDeliveryTrackingId(?string $deliveryTrackingId): ShippingData + { + $this->deliveryTrackingId = $deliveryTrackingId; + return $this; + } + + /** + * @return string|null + */ + public function getDeliveryService(): ?string + { + return $this->deliveryService; + } + + /** + * @param string|null $deliveryService + * + * @return ShippingData + */ + public function setDeliveryService(?string $deliveryService): ShippingData + { + $this->deliveryService = $deliveryService; + return $this; + } + + /** + * @return string|null + */ + public function getReturnTrackingId(): ?string + { + return $this->returnTrackingId; + } + + /** + * @param string|null $returnTrackingId + * + * @return ShippingData + */ + public function setReturnTrackingId(?string $returnTrackingId): ShippingData + { + $this->returnTrackingId = $returnTrackingId; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/ExternalResources/ApplepaySession.php b/vendor/unzerdev/php-sdk/src/Resources/ExternalResources/ApplepaySession.php index 8fb4a41..2f3ebc7 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/ExternalResources/ApplepaySession.php +++ b/vendor/unzerdev/php-sdk/src/Resources/ExternalResources/ApplepaySession.php @@ -1,31 +1,13 @@ - * - * @package UnzerSDK - * */ - -namespace UnzerSDK\Resources\ExternalResources; - class ApplepaySession { /** diff --git a/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlan.php b/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlan.php index a632652..bcdcf85 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlan.php +++ b/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlan.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; use DateTime; @@ -30,6 +8,12 @@ use UnzerSDK\Traits\CanAuthorizeWithCustomer; use stdClass; +/** + * Resource representing the installment plan for Installment Secured. + * + * @link https://docs.unzer.com/ + * + */ class InstalmentPlan extends BasePaymentType { use CanAuthorizeWithCustomer; @@ -80,30 +64,30 @@ class InstalmentPlan extends BasePaymentType private $installmentRates; /** - * @param int $numberOfRates - * @param string $dayOfPurchase - * @param float $totalPurchaseAmount - * @param float $totalInterestAmount - * @param float $totalAmount - * @param float $effectiveInterestRate - * @param float $nominalInterestRate - * @param float $feeFirstRate - * @param float $feePerRate - * @param float $monthlyRate - * @param float $lastRate + * @param int|null $numberOfRates + * @param string|null $dayOfPurchase + * @param float|null $totalPurchaseAmount + * @param float|null $totalInterestAmount + * @param float|null $totalAmount + * @param float|null $effectiveInterestRate + * @param float|null $nominalInterestRate + * @param float|null $feeFirstRate + * @param float|null $feePerRate + * @param float|null $monthlyRate + * @param float|null $lastRate */ public function __construct( - $numberOfRates = null, - $dayOfPurchase = null, - $totalPurchaseAmount = null, - $totalInterestAmount = null, - $totalAmount = null, - $effectiveInterestRate = null, - $nominalInterestRate = null, - $feeFirstRate = null, - $feePerRate = null, - $monthlyRate = null, - $lastRate = null + int $numberOfRates = null, + string $dayOfPurchase = null, + float $totalPurchaseAmount = null, + float $totalInterestAmount = null, + float $totalAmount = null, + float $effectiveInterestRate = null, + float $nominalInterestRate = null, + float $feeFirstRate = null, + float $feePerRate = null, + float $monthlyRate = null, + float $lastRate = null ) { $this->numberOfRates = $numberOfRates; $this->dayOfPurchase = $dayOfPurchase; @@ -118,8 +102,6 @@ public function __construct( $this->lastRate = $lastRate; } - // - /** * @return string|null */ @@ -152,7 +134,7 @@ public function getNumberOfRates(): ?int * * @return $this */ - public function setNumberOfRates($numberOfRates): self + public function setNumberOfRates(?int $numberOfRates): self { $this->numberOfRates = $numberOfRates; return $this; @@ -190,7 +172,7 @@ public function getTotalPurchaseAmount(): ?float * * @return $this */ - public function setTotalPurchaseAmount($totalPurchaseAmount): self + public function setTotalPurchaseAmount(?float $totalPurchaseAmount): self { $this->totalPurchaseAmount = $totalPurchaseAmount; return $this; @@ -209,7 +191,7 @@ public function getTotalInterestAmount(): ?float * * @return $this */ - public function setTotalInterestAmount($totalInterestAmount): self + public function setTotalInterestAmount(?float $totalInterestAmount): self { $this->totalInterestAmount = $totalInterestAmount; return $this; @@ -228,7 +210,7 @@ public function getTotalAmount(): ?float * * @return $this */ - public function setTotalAmount($totalAmount): self + public function setTotalAmount(?float $totalAmount): self { $this->totalAmount = $totalAmount; return $this; @@ -247,7 +229,7 @@ public function getEffectiveInterestRate(): ?float * * @return $this */ - public function setEffectiveInterestRate($effectiveInterestRate): self + public function setEffectiveInterestRate(?float $effectiveInterestRate): self { $this->effectiveInterestRate = $effectiveInterestRate; return $this; @@ -266,7 +248,7 @@ public function getNominalInterestRate(): ?float * * @return $this */ - public function setNominalInterestRate($nominalInterestRate): self + public function setNominalInterestRate(?float $nominalInterestRate): self { $this->nominalInterestRate = $nominalInterestRate; return $this; @@ -285,7 +267,7 @@ public function getFeeFirstRate(): ?float * * @return $this */ - public function setFeeFirstRate($feeFirstRate): self + public function setFeeFirstRate(?float $feeFirstRate): self { $this->feeFirstRate = $feeFirstRate; return $this; @@ -304,7 +286,7 @@ public function getFeePerRate(): ?float * * @return $this */ - public function setFeePerRate($feePerRate): self + public function setFeePerRate(?float $feePerRate): self { $this->feePerRate = $feePerRate; return $this; @@ -323,7 +305,7 @@ public function getMonthlyRate(): ?float * * @return $this */ - public function setMonthlyRate($monthlyRate): self + public function setMonthlyRate(?float $monthlyRate): self { $this->monthlyRate = $monthlyRate; return $this; @@ -342,7 +324,7 @@ public function getLastRate(): ?float * * @return $this */ - public function setLastRate($lastRate): self + public function setLastRate(?float $lastRate): self { $this->lastRate = $lastRate; return $this; @@ -406,10 +388,6 @@ protected function setInstallmentRates(array $installmentRates): InstalmentPlan return $this; } - // - - // - /** * {@inheritDoc} */ @@ -426,7 +404,7 @@ public function getTransactionParams(): array /** * {@inheritDoc} */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -438,6 +416,4 @@ public function handleResponse(stdClass $response, $method = HttpAdapterInterfac $this->setInstallmentRates($rates); } } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlans.php b/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlans.php index 4bd2bea..fce2478 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlans.php +++ b/vendor/unzerdev/php-sdk/src/Resources/InstalmentPlans.php @@ -1,35 +1,19 @@ - * - * @package UnzerSDK\Resources */ -namespace UnzerSDK\Resources; - -use DateTime; -use UnzerSDK\Adapter\HttpAdapterInterface; -use stdClass; - class InstalmentPlans extends AbstractUnzerResource { /** @var float */ @@ -67,8 +51,6 @@ public function __construct( $this->setOrderDate($orderDate); } - // - /** * @return float */ @@ -164,10 +146,6 @@ public function setOrderDate($orderDate): InstalmentPlans return $this; } - // - - // - /** * Returns the parameter array containing the values for the query string. * @@ -192,18 +170,13 @@ protected function getQueryArray(): array */ protected function getQueryString(): string { - $getParameterArray = $this->getQueryArray(); - foreach ($getParameterArray as $key=> $parameter) { - $getParameterArray[$key] = $key . '=' . $parameter; - } - - return '?' . implode('&', $getParameterArray); + return '?' . http_build_query($this->getQueryArray()); } /** * {@inheritDoc} */ - public function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + public function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'plans' . $this->getQueryString(); } @@ -211,7 +184,7 @@ public function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET) /** * {@inheritDoc} */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -225,6 +198,4 @@ public function handleResponse(stdClass $response, $method = HttpAdapterInterfac $this->setPlans($plans); } } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/Keypair.php b/vendor/unzerdev/php-sdk/src/Resources/Keypair.php index 49b8d96..6308e6e 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Keypair.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Keypair.php @@ -1,32 +1,16 @@ - * - * @package UnzerSDK\Resources */ -namespace UnzerSDK\Resources; - -use UnzerSDK\Adapter\HttpAdapterInterface; -use stdClass; - class Keypair extends AbstractUnzerResource { /** @var string $publicKey */ @@ -64,8 +48,6 @@ class Keypair extends AbstractUnzerResource /** @var bool $validateBasket */ private $validateBasket; - // - /** * @return string|null */ @@ -143,7 +125,7 @@ public function getSecureLevel(): string * * @return Keypair */ - protected function setSecureLevel($secureLevel): Keypair + protected function setSecureLevel(?string $secureLevel): Keypair { $this->secureLevel = $secureLevel; return $this; @@ -162,7 +144,7 @@ public function getAlias(): string * * @return Keypair */ - protected function setAlias($alias): Keypair + protected function setAlias(?string $alias): Keypair { $this->alias = $alias; return $this; @@ -181,7 +163,7 @@ public function getMerchantName(): string * * @return Keypair */ - protected function setMerchantName($merchantName): Keypair + protected function setMerchantName(?string $merchantName): Keypair { $this->merchantName = $merchantName; return $this; @@ -200,7 +182,7 @@ public function getMerchantAddress(): string * * @return Keypair */ - protected function setMerchantAddress($merchantAddress): Keypair + protected function setMerchantAddress(?string $merchantAddress): Keypair { $this->merchantAddress = $merchantAddress; return $this; @@ -259,20 +241,16 @@ public function isValidateBasket(): ?bool * * @return Keypair */ - protected function setValidateBasket($validateBasket): Keypair + protected function setValidateBasket(?bool $validateBasket): Keypair { $this->validateBasket = $validateBasket; return $this; } - // - - // - /** * @inheritDoc */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -291,10 +269,8 @@ public function handleResponse(stdClass $response, $method = HttpAdapterInterfac /** * @inheritDoc */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return parent::getResourcePath($httpMethod) . ($this->isDetailed() ? '/types' : ''); } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/Metadata.php b/vendor/unzerdev/php-sdk/src/Resources/Metadata.php index 384b01b..3d2f667 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Metadata.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Metadata.php @@ -1,35 +1,20 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; use UnzerSDK\Adapter\HttpAdapterInterface; +use stdClass; + use function count; use function in_array; use function is_callable; -use stdClass; +/** + * This represents the metadata resource. + * + * @link https://docs.unzer.com/ + * + */ class Metadata extends AbstractUnzerResource { private $metadata = []; @@ -37,8 +22,6 @@ class Metadata extends AbstractUnzerResource protected $shopType; protected $shopVersion; - // - /** * @return string|null */ @@ -85,7 +68,7 @@ public function setShopVersion(string $shopVersion): Metadata * * @return Metadata */ - public function addMetadata($name, $value): Metadata + public function addMetadata(string $name, string $value): Metadata { if (!in_array(strtolower($name), ['sdkversion', 'sdktype', 'shoptype', 'shopversion'])) { $this->metadata[$name] = $value; @@ -101,15 +84,11 @@ public function addMetadata($name, $value): Metadata * * @return mixed */ - public function getMetadata($name) + public function getMetadata(string $name) { return $this->metadata[$name] ?? null; } - //> - - // - /** * Add the dynamically set meta data. * {@inheritDoc} @@ -121,10 +100,10 @@ public function expose() } /** - * Add custom properties (i. e. properties without setter) to the metadata array. + * Add custom properties (i.e. properties without setter) to the metadata array. * {@inheritDoc} */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -135,6 +114,4 @@ public function handleResponse(stdClass $response, $method = HttpAdapterInterfac } } } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaylaterInstallmentPlans.php b/vendor/unzerdev/php-sdk/src/Resources/PaylaterInstallmentPlans.php new file mode 100644 index 0000000..4e132d2 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/PaylaterInstallmentPlans.php @@ -0,0 +1,205 @@ +amount; + } + + /** + * @param float $amount + * + * @return PaylaterInstallmentPlans + */ + public function setAmount(float $amount): PaylaterInstallmentPlans + { + $this->amount = $amount; + return $this; + } + + /** + * @return string + */ + public function getCurrency(): ?string + { + return $this->currency; + } + + /** + * @param string $currency + * + * @return InstalmentPlans + */ + public function setCurrency(string $currency): PaylaterInstallmentPlans + { + $this->currency = $currency; + return $this; + } + + /** + * @return string + */ + public function getCountry(): ?string + { + return $this->country; + } + + /** + * @param string $country + * + * @return PaylaterInstallmentPlans + */ + public function setCountry(string $country): PaylaterInstallmentPlans + { + $this->country = $country; + return $this; + } + + /** + * @return string + */ + public function getCustomerType(): ?string + { + return $this->customerType; + } + + /** + * @param string $customerType + * + * @return PaylaterInstallmentPlans + */ + public function setCustomerType(string $customerType): PaylaterInstallmentPlans + { + $this->customerType = $customerType; + return $this; + } + + /** + * @return InstallmentPlan[] + */ + public function getPlans(): array + { + return $this->plans; + } + + /** + * @param stdClass[] $plans + * + * @return InstalmentPlans + */ + protected function setPlans(array $plans): PaylaterInstallmentPlans + { + $this->plans = $plans; + return $this; + } + + /** + * {@inheritDoc} + */ + public function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string + { + return 'plans' . $this->getQueryString(); + } + + /** + * Returns the query string for this resource. + * + * @return string + */ + protected function getQueryString(): string + { + return '?' . http_build_query($this->getQueryArray()); + } + + /** + * Returns the parameter array containing the values for the query string. + * + * @return array + */ + protected function getQueryArray(): array + { + $parameters = []; + if ($this->queryParameter === null) { + return $parameters; + } + + return $this->getQueryParameter()->expose(); + } + + /** + * @return InstallmentPlansQuery + */ + public function getQueryParameter(): InstallmentPlansQuery + { + return $this->queryParameter; + } + + /** + * @param InstallmentPlansQuery $queryParameter + * + * @return PaylaterInstallmentPlans + */ + public function setQueryParameter(InstallmentPlansQuery $queryParameter): PaylaterInstallmentPlans + { + $this->queryParameter = $queryParameter; + return $this; + } + + /** + * {@inheritDoc} + */ + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void + { + parent::handleResponse($response, $method); + + if (isset($response->plans)) { + $plans = []; + foreach ($response->plans as $plan) { + $instalment = new InstallmentPlan(); + $instalment->handleResponse($plan); + $plans[] = $instalment; + } + $this->setPlans($plans); + } + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/Payment.php b/vendor/unzerdev/php-sdk/src/Resources/Payment.php index 624241e..f91ae33 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Payment.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Payment.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; use UnzerSDK\Adapter\HttpAdapterInterface; @@ -36,6 +14,7 @@ use UnzerSDK\Resources\TransactionTypes\Authorization; use UnzerSDK\Resources\TransactionTypes\Cancellation; use UnzerSDK\Resources\TransactionTypes\Charge; +use UnzerSDK\Resources\TransactionTypes\Chargeback; use UnzerSDK\Resources\TransactionTypes\Payout; use UnzerSDK\Resources\TransactionTypes\Shipment; use UnzerSDK\Services\IdService; @@ -48,6 +27,12 @@ use function is_string; +/** + * This represents the payment resource. + * + * @link https://docs.unzer.com/ + * + */ class Payment extends AbstractUnzerResource { use HasPaymentState; @@ -67,9 +52,28 @@ class Payment extends AbstractUnzerResource /** @var array $shipments */ private $shipments = []; - /** @var array $charges */ + /** @var Charge[] $charges */ private $charges = []; + /** @var Chargeback[] $chargebacks */ + private $chargebacks = []; + + + /** + * Associative array using the ID of the cancellations as the key. + * + * @var array $reversals + */ + private $reversals = []; + + /** + * Associative array using the ID of the cancellations as the key. + * + * @var array $refunds + */ + private $refunds = []; + + /** @var Customer $customer */ private $customer; @@ -85,6 +89,9 @@ class Payment extends AbstractUnzerResource /** @var Basket $basket */ private $basket; + /** @var Paypage $payPage */ + private $payPage; + /** * @param null $parent */ @@ -95,8 +102,6 @@ public function __construct($parent = null) $this->setParentResource($parent); } - // - /** * Returns the redirectUrl set by the API. * @@ -114,12 +119,28 @@ public function getRedirectUrl(): ?string * * @return Payment */ - protected function setRedirectUrl($redirectUrl): Payment + protected function setRedirectUrl(?string $redirectUrl): Payment { $this->redirectUrl = $redirectUrl; return $this; } + /** + * @return Chargeback[] + */ + public function getChargebacks(): array + { + return $this->chargebacks; + } + + /** + * @param array $chargebacks + */ + public function setChargebacks(array $chargebacks): void + { + $this->chargebacks = $chargebacks; + } + /** * Retrieves the Authorization object of this payment. * Fetches the Authorization if it has not been fetched before and the lazy flag is not set. @@ -133,7 +154,7 @@ protected function setRedirectUrl($redirectUrl): Payment * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function getAuthorization($lazy = false) + public function getAuthorization(bool $lazy = false) { $authorization = $this->authorization; if (!$lazy && $authorization !== null) { @@ -169,7 +190,7 @@ public function setAuthorization(Authorization $authorize): Payment * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function getPayout($lazy = false) + public function getPayout(bool $lazy = false) { $payout = $this->payout; if (!$lazy && $payout !== null) { @@ -216,6 +237,20 @@ public function addCharge(Charge $charge): self return $this; } + /** + * Adds a Charge object to this Payment and stores it in the charges array. + * + * @param Charge $chargeback + * + * @return $this + */ + private function addChargeback(Chargeback $chargeback): self + { + $chargeback->setPayment($this); + $this->chargebacks[] = $chargeback; + return $this; + } + /** * Retrieves a Charge object from the charges array of this Payment object by its Id. * Fetches the Charge if it has not been fetched before and the lazy flag is not set. @@ -230,7 +265,7 @@ public function addCharge(Charge $charge): self * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function getCharge($chargeId, $lazy = false): ?Charge + public function getCharge(string $chargeId, bool $lazy = false): ?Charge { /** @var Charge $charge */ foreach ($this->charges as $charge) { @@ -244,6 +279,38 @@ public function getCharge($chargeId, $lazy = false): ?Charge return null; } + /** + * Retrieves a Chargeback object from the chargebacks array of this Payment object by its ID. + * Fetches the Charge if it has not been fetched before and the lazy flag is not set. + * Returns null if the Charge does not exist. + * + * @param string $chargeId The ID of the Charge to be retrieved. + * @param bool $lazy Enables lazy loading if set to true which results in the object not being updated via + * API and possibly containing just the meta data known from the Payment object response. + * + * @return Charge|null The retrieved Charge object or null if it does not exist. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function getChargeback(string $chargebackId, ?string $chargeId, bool $lazy = false): ?Chargeback + { + /** @var Chargeback $chargeback */ + foreach ($this->chargebacks as $chargeback) { + $parentResource = $chargeback->getParentResource(); + if ($chargeback->getId() === $chargebackId) { + if ($parentResource instanceof Charge && $parentResource->getId() !== $chargeId) { + continue; + } + if (!$lazy) { + $this->getResource($chargeback); + } + return $chargeback; + } + } + return null; + } + /** * Retrieves a Charge object by its index in the charges array. * Fetches the Charge if it has not been fetched before and the lazy flag is not set. @@ -258,7 +325,7 @@ public function getCharge($chargeId, $lazy = false): ?Charge * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function getChargeByIndex($index, $lazy = false) + public function getChargeByIndex(int $index, bool $lazy = false) { $resource = null; if (isset($this->getCharges()[$index])) { @@ -316,6 +383,50 @@ public function getCustomer(): ?Customer return $this->customer; } + /** + * Reference this payment object to the passed PayPage resource. + * The PayPage resource can be passed as PayPage object or the Id of a PayPage resource. + * If the PayPage object has not been created yet via API this is done automatically. + * + * @param PayPage|string|null $payPage The PayPage object or the id of the PayPage to be referenced by the Payment. + * + * @return Payment This Payment object. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function setPayPage($payPage): Payment + { + if (empty($payPage)) { + return $this; + } + + $unzer = $this->getUnzerObject(); + + /** @var PayPage $payPageObject */ + $payPageObject = $payPage; + + if (is_string($payPage)) { + $payPageObject = (new Paypage(0, '', '')) + ->setId($payPage) + ->setPayment($this); + } + + $payPageObject->setParentResource($unzer); + $this->payPage = $payPageObject; + return $this; + } + + /** + * Returns the PayPage object referenced by this Payment. + * + * @return PayPage|null The PayPage object referenced by this Payment or null if no PayPage could be found. + */ + public function getPayPage(): ?PayPage + { + return $this->payPage; + } + /** * Returns the Payment Type object referenced by this Payment or throws a RuntimeException if none exists. * @@ -330,7 +441,7 @@ public function getPaymentType(): ?BasePaymentType * Sets the Payments reference to the given PaymentType resource. * The PaymentType can be either a PaymentType object or the id of a PaymentType resource. * - * @param mixed $paymentType The PaymentType object or the id of the PaymentType to be referenced. + * @param BasePaymentType|string|null $paymentType The PaymentType object or the id of the PaymentType to be referenced. * * @return Payment This Payment object. * @@ -375,7 +486,7 @@ public function getMetadata(): ?Metadata * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function setMetadata($metadata): Payment + public function setMetadata(?Metadata $metadata): Payment { if (!$metadata instanceof Metadata) { return $this; @@ -408,7 +519,7 @@ public function getBasket(): ?Basket * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function setBasket($basket): Payment + public function setBasket(?Basket $basket): Payment { $this->basket = $basket; @@ -439,8 +550,10 @@ public function setBasket($basket): Payment * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * + * @deprecated since 3.2.0 Please use getCancellation() method of a Charge or Authorization object instead. */ - public function getCancellation($cancellationId, $lazy = false): ?Cancellation + public function getCancellation(string $cancellationId, bool $lazy = false): ?Cancellation { /** @var Cancellation $cancellation */ foreach ($this->getCancellations() as $cancellation) { @@ -466,6 +579,12 @@ public function getCancellation($cancellationId, $lazy = false): ?Cancellation */ public function getCancellations(): array { + if (!empty($this->refunds) || !(empty($this->reversals))) { + return array_merge( + array_values($this->reversals), + array_values($this->refunds) + ); + } $refunds = []; /** @var Charge $charge */ @@ -513,7 +632,7 @@ public function getShipments(): array * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function getShipment($shipmentId, $lazy = false): ?Shipment + public function getShipment(string $shipmentId, bool $lazy = false): ?Shipment { /** @var Shipment $shipment */ foreach ($this->getShipments() as $shipment) { @@ -573,7 +692,7 @@ public function getCurrency(): string * @throws UnzerApiException * @throws RuntimeException */ - public function getInitialTransaction($lazy = false): ?AbstractTransactionType + public function getInitialTransaction(bool $lazy = false): ?AbstractTransactionType { return $this->getAuthorization($lazy) ?? $this->getChargeByIndex(0, $lazy); } @@ -591,14 +710,73 @@ protected function setCurrency(string $currency): self return $this; } - // + /** + * @return array Associative array with cancellation id as the key and the Cancellation object as value. + */ + public function getRefunds(): array + { + return $this->refunds; + } + + /** + * @param array $refunds + * + * @return Payment + */ + public function setRefunds(array $refunds): Payment + { + $this->refunds = $refunds; + return $this; + } + + /** + * @param Cancellation $refund + * + * @return Payment + */ + public function addRefund(Cancellation $refund): Payment + { + $this->refunds[$refund->getId()] = $refund; + return $this; + } + + /** + * @return array Associative array with cancellation id as the key and the Cancellation object as value. + */ + public function getReversals(): array + { + return $this->reversals; + } - // + /** + * @param array $reversals + * + * @return Payment + */ + public function setReversals(array $reversals): Payment + { + $this->reversals = $reversals; + return $this; + } + + /** + * Adds a Cancellation to the associative reversal array with the cancellation id as the key. If a cancellation with + * that ID already exists it will be overwritten. + * + * @param Cancellation $reversal + * + * @return Payment + */ + public function addReversal(Cancellation $reversal): Payment + { + $this->reversals[$reversal->getId()] = $reversal; + return $this; + } /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'payments'; } @@ -609,7 +787,7 @@ protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_G * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -634,10 +812,6 @@ public function getExternalId(): ?string return $this->getOrderId(); } - // - - // - /** * Performs a Cancellation transaction on the Payment. * If no amount is given a full cancel will be performed i. e. all Charges and Authorizations will be cancelled. @@ -655,11 +829,11 @@ public function getExternalId(): ?string * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function cancelAmount( - float $amount = null, - $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, - string $paymentReference = null, - float $amountNet = null, - float $amountVat = null + float $amount = null, + ?string $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, + string $paymentReference = null, + float $amountNet = null, + float $amountVat = null ): array { return $this->getUnzerObject()->cancelPayment($this, $amount, $reasonCode, $paymentReference, $amountNet, $amountVat); } @@ -684,17 +858,16 @@ public function cancelAuthorizationAmount(float $amount = null): ?Cancellation /** * Performs a Charge transaction on the payment. * - * @param null $amount The amount to be charged. - * @param null $currency The currency of the charged amount. + * @param float|null $amount The amount to be charged. * * @return Charge|AbstractUnzerResource The resulting Charge object. * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function charge($amount = null, $currency = null): Charge + public function charge(float $amount = null): Charge { - return $this->getUnzerObject()->chargePayment($this, $amount, $currency); + return $this->getUnzerObject()->chargePayment($this, $amount); } /** @@ -708,15 +881,11 @@ public function charge($amount = null, $currency = null): Charge * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function ship($invoiceId = null, $orderId = null) + public function ship(string $invoiceId = null, string $orderId = null) { return $this->getUnzerObject()->ship($this, $invoiceId, $orderId); } - // - - // - /** * @param array $transactions * @@ -749,6 +918,9 @@ private function updateResponseTransactions(array $transactions = []): void case TransactionTypes::PAYOUT: $this->updatePayoutTransaction($transaction); break; + case TransactionTypes::CHARGEBACK: + $this->updateChargebackTransaction($transaction); + break; default: // skip break; @@ -759,12 +931,11 @@ private function updateResponseTransactions(array $transactions = []): void /** * Handles the resources from a response and updates the payment object accordingly. * - * @param $resources + * @param stdClass $resources * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. - * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - private function updateResponseResources($resources): void + private function updateResponseResources(stdClass $resources): void { if (isset($resources->paymentId)) { $this->setId($resources->paymentId); @@ -779,6 +950,11 @@ private function updateResponseResources($resources): void } } + $payPageId = $resources->payPageId ?? null; + if (!empty($payPageId)) { + $this->setPayPage($payPageId); + } + if (isset($resources->typeId) && !empty($resources->typeId) && !$this->paymentType instanceof BasePaymentType) { $this->paymentType = $this->getUnzerObject()->fetchPaymentType($resources->typeId); } @@ -806,7 +982,7 @@ private function updateResponseResources($resources): void * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - private function updateAuthorizationTransaction($transaction): void + private function updateAuthorizationTransaction(stdClass $transaction): void { $transactionId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::AUTHORIZE); $authorization = $this->getAuthorization(true); @@ -814,7 +990,8 @@ private function updateAuthorizationTransaction($transaction): void $authorization = (new Authorization())->setPayment($this)->setId($transactionId); $this->setAuthorization($authorization); } - $authorization->setAmount($transaction->amount); + + $authorization->handleResponse($transaction); } /** @@ -826,7 +1003,7 @@ private function updateAuthorizationTransaction($transaction): void * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - private function updateChargeTransaction($transaction): void + private function updateChargeTransaction(stdClass $transaction): void { $transactionId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::CHARGE); $charge = $this->getCharge($transactionId, true); @@ -834,7 +1011,8 @@ private function updateChargeTransaction($transaction): void $charge = (new Charge())->setPayment($this)->setId($transactionId); $this->addCharge($charge); } - $charge->setAmount($transaction->amount); + + $charge->handleResponse($transaction); } /** @@ -846,20 +1024,28 @@ private function updateChargeTransaction($transaction): void * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - private function updateReversalTransaction($transaction): void + private function updateReversalTransaction(stdClass $transaction): void { $transactionId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::CANCEL); - $authorization = $this->getAuthorization(true); - if (!$authorization instanceof Authorization) { - throw new RuntimeException('The Authorization object can not be found.'); - } - $cancellation = $authorization->getCancellation($transactionId, true); - if (!$cancellation instanceof Cancellation) { + $isPaymentCancellation = IdService::isPaymentCancellation($transaction->url); + if ($isPaymentCancellation) { $cancellation = (new Cancellation())->setPayment($this)->setId($transactionId); - $authorization->addCancellation($cancellation); + $this->addReversal($cancellation); + } else { + $initialTransaction = $this->getInitialTransaction(true); + if (!$initialTransaction instanceof Authorization && !$initialTransaction instanceof Charge) { + throw new RuntimeException('The initial transaction object (Authorize or Charge) can not be found.'); + } + + $cancellation = $initialTransaction->getCancellation($transactionId, true); + if (!$cancellation instanceof Cancellation) { + $cancellation = (new Cancellation())->setPayment($this)->setId($transactionId); + $initialTransaction->addCancellation($cancellation); + } } - $cancellation->setAmount($transaction->amount); + + $cancellation->handleResponse($transaction); } /** @@ -871,22 +1057,30 @@ private function updateReversalTransaction($transaction): void * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - private function updateRefundTransaction($transaction): void + private function updateRefundTransaction(stdClass $transaction): void { $refundId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::CANCEL); - $chargeId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::CHARGE); - - $charge = $this->getCharge($chargeId, true); - if (!$charge instanceof Charge) { - throw new RuntimeException('The Charge object can not be found.'); + $isPaymentCancellation = IdService::isPaymentCancellation($transaction->url); + if ($isPaymentCancellation) { + $cancellation = (new Cancellation())->setPayment($this)->setId($refundId); + $this->addRefund($cancellation); } - $cancellation = $charge->getCancellation($refundId, true); - if (!$cancellation instanceof Cancellation) { - $cancellation = (new Cancellation())->setPayment($this)->setId($refundId); - $charge->addCancellation($cancellation); + if (!$isPaymentCancellation) { + $chargeId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::CHARGE); + $charge = $this->getCharge($chargeId, true); + if (!$charge instanceof Charge) { + throw new RuntimeException('The Charge object can not be found.'); + } + $cancellation = $charge->getCancellation($refundId, true); + + if (!$cancellation instanceof Cancellation) { + $cancellation = (new Cancellation())->setPayment($this)->setId($refundId); + $charge->addCancellation($cancellation); + } } - $cancellation->setAmount($transaction->amount); + + $cancellation->handleResponse($transaction); } /** @@ -898,7 +1092,7 @@ private function updateRefundTransaction($transaction): void * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - private function updateShipmentTransaction($transaction): void + private function updateShipmentTransaction(stdClass $transaction): void { $shipmentId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::SHIPMENT); $shipment = $this->getShipment($shipmentId, true); @@ -906,7 +1100,8 @@ private function updateShipmentTransaction($transaction): void $shipment = (new Shipment())->setId($shipmentId); $this->addShipment($shipment); } - $shipment->setAmount($transaction->amount); + + $shipment->handleResponse($transaction); } /** @@ -918,7 +1113,7 @@ private function updateShipmentTransaction($transaction): void * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - private function updatePayoutTransaction($transaction): void + private function updatePayoutTransaction(stdClass $transaction): void { $payoutId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::PAYOUT); $payout = $this->getPayout(true); @@ -926,8 +1121,50 @@ private function updatePayoutTransaction($transaction): void $payout = (new Payout())->setId($payoutId); $this->setPayout($payout); } - $payout->setAmount($transaction->amount); + + $payout->handleResponse($transaction); } - // + /** + * This updates the local chargeback object referenced by this Payment with the given chargeback transaction from the + * Payment response. + * + * @param stdClass $transaction The transaction from the Payment response containing the chargeback data. + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + private function updateChargebackTransaction(stdClass $transaction): void + { + // does chargeback refer to a specific charge transaction + // Get/create charge instance, if yes. + // does chargeback already exist? + // Add chargeback to charge transaction + $isPaymentChargeback = IdService::isPaymentChargeback($transaction->url); + $chargebackId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::CHARGEBACK); + + + if (!$isPaymentChargeback) { + $chargeId = IdService::getResourceIdFromUrl($transaction->url, IdStrings::CHARGE); + $chargeback = $this->getChargeback($chargebackId, $chargeId, true); + $charge = $this->getCharge($chargeId, true); + if (!$chargeback instanceof Chargeback) { + $chargeback = (new Chargeback())->setId($chargebackId); + $this->addChargeback($chargeback); + + if ($charge instanceof Charge) { + $charge->addChargeback($chargeback); + $chargeback->setParentResource($charge); + } + } + } else { + $chargeback = $this->getChargeback($chargebackId, null, true); + if (!$chargeback instanceof Chargeback) { + $chargeback = (new Chargeback())->setId($chargebackId); + $this->addChargeback($chargeback); + } + } + + $chargeback->handleResponse($transaction); + } } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Alipay.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Alipay.php index 656b2ca..de55328 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Alipay.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Alipay.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Applepay.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Applepay.php index 2eb1263..2f452bb 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Applepay.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Applepay.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use stdClass; @@ -29,13 +7,11 @@ use UnzerSDK\Resources\EmbeddedResources\ApplePayHeader; use UnzerSDK\Traits\CanAuthorize; use UnzerSDK\Traits\CanDirectCharge; -use UnzerSDK\Traits\HasGeoLocation; class Applepay extends BasePaymentType { use CanDirectCharge; use CanAuthorize; - use HasGeoLocation; /** @var string|null $applicationExpirationDate */ private $applicationExpirationDate; @@ -65,7 +41,7 @@ class Applepay extends BasePaymentType protected $header; /** - * ApplePay constructor. + * Apple Pay constructor. * * @param string|null $version * @param string|null $data @@ -84,8 +60,6 @@ public function __construct( $this->header = $header; } - // - /** * @inheritDoc */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Bancontact.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Bancontact.php index b2505e0..a68df46 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Bancontact.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Bancontact.php @@ -1,29 +1,5 @@ - * @author Florian Evertz - * @author Simon Gabriel - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/BasePaymentType.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/BasePaymentType.php index a967f14..0410b1a 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/BasePaymentType.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/BasePaymentType.php @@ -1,34 +1,24 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Resources\AbstractUnzerResource; +use UnzerSDK\Traits\HasGeoLocation; +/** + * This represents a payment type. + * + * @link https://docs.unzer.com/ + * + */ abstract class BasePaymentType extends AbstractUnzerResource { + use HasGeoLocation; + + /** @var bool */ + protected const SUPPORT_DIRECT_PAYMENT_CANCEL = false; + /** * Return true for invoice types. * This enables you to handle the invoice workflow correctly. @@ -43,12 +33,15 @@ public function isInvoiceType(): bool return false; } - // + public function supportsDirectPaymentCancel(): bool + { + return static::SUPPORT_DIRECT_PAYMENT_CANCEL; + } /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { $path = 'types'; if ($httpMethod !== HttpAdapterInterface::REQUEST_GET || $this->id === null) { @@ -68,6 +61,4 @@ public function getTransactionParams(): array { return []; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Card.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Card.php index e7acd48..3a68888 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Card.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Card.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Adapter\HttpAdapterInterface; @@ -30,18 +8,22 @@ use UnzerSDK\Traits\CanDirectCharge; use UnzerSDK\Traits\CanPayout; use UnzerSDK\Traits\CanRecur; -use UnzerSDK\Traits\HasGeoLocation; use UnzerSDK\Validators\ExpiryDateValidator; use RuntimeException; use stdClass; +/** + * This represents the card payment type which supports credit card as well as debit card payments. + * + * @link https://docs.unzer.com/ + * + */ class Card extends BasePaymentType { use CanDirectCharge; use CanAuthorize; use CanPayout; use CanRecur; - use HasGeoLocation; /** @var string $number */ protected $number; @@ -70,19 +52,17 @@ class Card extends BasePaymentType /** * Card constructor. * - * @param string $number - * @param string $expiryDate + * @param string|null $number + * @param string|null $expiryDate * @param string|null $email */ - public function __construct($number, $expiryDate, $email = null) + public function __construct(?string $number, ?string $expiryDate, string $email = null) { $this->setNumber($number); $this->setExpiryDate($expiryDate); $this->setEmail($email); } - // - /** * @return string */ @@ -92,11 +72,11 @@ public function getNumber(): string } /** - * @param string $pan + * @param string|null $pan * * @return Card */ - public function setNumber($pan): Card + public function setNumber(?string $pan): Card { $this->number = $pan; return $this; @@ -111,13 +91,12 @@ public function getExpiryDate(): ?string } /** - * @param string $expiryDate + * @param string|null $expiryDate * * @return Card * - * @throws RuntimeException */ - public function setExpiryDate($expiryDate): Card + public function setExpiryDate(?string $expiryDate): Card { // Null value is allowed to be able to fetch a card object with nothing but the id set. if ($expiryDate === null) { @@ -142,11 +121,11 @@ public function getCvc(): ?string } /** - * @param string $cvc + * @param string|null $cvc * * @return Card */ - public function setCvc($cvc): Card + public function setCvc(?string $cvc): Card { $this->cvc = $cvc; return $this; @@ -165,7 +144,7 @@ public function getCardHolder(): ?string * * @return Card */ - public function setCardHolder($cardHolder): Card + public function setCardHolder(string $cardHolder): Card { $this->cardHolder = $cardHolder; return $this; @@ -184,7 +163,7 @@ public function get3ds(): ?bool * * @return Card */ - public function set3ds($card3ds): Card + public function set3ds(?bool $card3ds): Card { $this->card3ds = $card3ds; return $this; @@ -239,10 +218,6 @@ public function setEmail(?string $email): Card return $this; } - // - - // - /** * Rename internal property names to external property names. * @@ -261,7 +236,7 @@ public function expose() /** * {@inheritDoc} */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -270,6 +245,4 @@ public function handleResponse(stdClass $response, $method = HttpAdapterInterfac $this->cardDetails->handleResponse($response->cardDetails); } } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/EPS.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/EPS.php index af56b47..2011e93 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/EPS.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/EPS.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; @@ -33,8 +11,6 @@ class EPS extends BasePaymentType /** @var string $bic */ protected $bic; - // - /** * @return string|null */ @@ -48,11 +24,9 @@ public function getBic(): ?string * * @return self */ - public function setBic($bic): self + public function setBic(?string $bic): self { $this->bic = $bic; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Giropay.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Giropay.php index bdc0ab1..9d2a6f2 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Giropay.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Giropay.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Googlepay.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Googlepay.php new file mode 100644 index 0000000..120ce02 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Googlepay.php @@ -0,0 +1,146 @@ +protocolVersion = $protocolVersion; + $this->signature = $signature; + $this->intermediateSigningKey = $intermediateSigningKey; + $this->signedMessage = $signedMessage; + } + + public static function getResourceName(): string + { + return 'googlepay'; + } + + /** + * @inheritDoc + */ + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void + { + parent::handleResponse($response, $method); + + if (isset($response->intermediateSigningKey)) { + $this->intermediateSigningKey = new IntermediateSigningKey(); + $this->intermediateSigningKey->handleResponse($response->intermediateSigningKey); + } + } + + public function getNumber(): string + { + return $this->number; + } + + protected function setNumber(string $number): Googlepay + { + $this->number = $number; + return $this; + } + + public function getExpiryDate(): string + { + return $this->expiryDate; + } + + protected function setExpiryDate(string $expiryDate): Googlepay + { + $this->expiryDate = $expiryDate; + return $this; + } + + public function getProtocolVersion(): ?string + { + return $this->protocolVersion; + } + + public function setProtocolVersion(?string $protocolVersion): Googlepay + { + $this->protocolVersion = $protocolVersion; + return $this; + } + + public function getSignature(): ?string + { + return $this->signature; + } + + public function setSignature(?string $signature): Googlepay + { + $this->signature = $signature; + return $this; + } + + public function getIntermediateSigningKey(): ?IntermediateSigningKey + { + return $this->intermediateSigningKey; + } + + public function setIntermediateSigningKey(?IntermediateSigningKey $intermediateSigningKey): Googlepay + { + $this->intermediateSigningKey = $intermediateSigningKey; + return $this; + } + + public function getSignedMessage(): ?SignedMessage + { + return $this->signedMessage; + } + + public function setSignedMessage(?SignedMessage $signedMessage): Googlepay + { + $this->signedMessage = $signedMessage; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Ideal.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Ideal.php index 8f79f46..efed810 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Ideal.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Ideal.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; @@ -33,8 +11,6 @@ class Ideal extends BasePaymentType /** @var string $bic */ protected $bic; - // - /** * @return string|null */ @@ -44,15 +20,13 @@ public function getBic(): ?string } /** - * @param string $bic + * @param string|null $bic * * @return self */ - public function setBic(string $bic): self + public function setBic(?string $bic): self { $this->bic = $bic; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InstallmentSecured.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InstallmentSecured.php index 682b099..1410d71 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InstallmentSecured.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InstallmentSecured.php @@ -2,31 +2,18 @@ /** * This represents the Installment Secured payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\PaymentTypes */ + namespace UnzerSDK\Resources\PaymentTypes; use DateTime; use UnzerSDK\Resources\InstalmentPlan; +/** @deprecated will be replaced by PaylaterInstallment. + * @see PaylaterInstallment + */ class InstallmentSecured extends InstalmentPlan { /** @var string $iban */ @@ -51,8 +38,8 @@ public function __construct(InstalmentPlan $selectedPlan = null, $iban = null, $ { parent::__construct(); - $this->iban = $iban; - $this->bic = $bic; + $this->iban = $iban; + $this->bic = $bic; $this->accountHolder = $accountHolder; $this->setOrderDate($orderDate); $this->setInvoiceDate($invoiceDate); @@ -67,7 +54,7 @@ public function __construct(InstalmentPlan $selectedPlan = null, $iban = null, $ * * @return $this */ - public function selectInstalmentPlan($plan): self + public function selectInstalmentPlan(?InstalmentPlan $plan): self { if ($plan instanceof InstalmentPlan) { $this->handleResponse((object)$plan->expose()); @@ -75,8 +62,6 @@ public function selectInstalmentPlan($plan): self return $this; } - // - /** * @return string|null */ @@ -90,7 +75,7 @@ public function getIban(): ?string * * @return $this */ - public function setIban($iban): self + public function setIban(?string $iban): self { $this->iban = $iban; return $this; @@ -109,7 +94,7 @@ public function getBic(): ?string * * @return $this */ - public function setBic($bic): self + public function setBic(?string $bic): self { $this->bic = $bic; return $this; @@ -128,11 +113,9 @@ public function getAccountHolder(): ?string * * @return $this */ - public function setAccountHolder($accountHolder): self + public function setAccountHolder(?string $accountHolder): self { $this->accountHolder = $accountHolder; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Invoice.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Invoice.php index c7f6469..7717396 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Invoice.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Invoice.php @@ -2,31 +2,18 @@ /** * This represents the invoice payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\PaymentTypes */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; use UnzerSDK\Traits\IsInvoiceType; +/** + * @deprecated since 1.2.3.0 Please switch to PaylaterInvoice. + */ class Invoice extends BasePaymentType { use CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InvoiceSecured.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InvoiceSecured.php index ecfd1c6..8baf4fc 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InvoiceSecured.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/InvoiceSecured.php @@ -2,31 +2,18 @@ /** * This represents the invoice secured payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\PaymentTypes */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectChargeWithCustomer; use UnzerSDK\Traits\IsInvoiceType; +/** + * @deprecated since 1.2.0.0 Please use PaylaterInvoice instead. + */ class InvoiceSecured extends BasePaymentType { use CanDirectChargeWithCustomer; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Klarna.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Klarna.php new file mode 100644 index 0000000..df0f130 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Klarna.php @@ -0,0 +1,8 @@ + - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PayU.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PayU.php new file mode 100644 index 0000000..727f486 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PayU.php @@ -0,0 +1,10 @@ +iban = $iban; + $this->holder = $holder; + } + + public function getIban(): ?string + { + return $this->iban; + } + + public function setIban(string $iban): PaylaterDirectDebit + { + $this->iban = $iban; + return $this; + } + + public function getHolder(): ?string + { + return $this->holder; + } + + public function setHolder(string $holder): PaylaterDirectDebit + { + $this->holder = $holder; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PaylaterInstallment.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PaylaterInstallment.php new file mode 100644 index 0000000..4b83476 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PaylaterInstallment.php @@ -0,0 +1,134 @@ +inquiryId = $inquiryId; + $this->numberOfRates = $numberOfRates; + $this->iban = $iban; + $this->country = $country; + $this->holder = $accountHolder; + } + + /** + * @return string|null + */ + public function getInquiryId(): ?string + { + return $this->inquiryId; + } + + /** + * @param string|null $inquiryId + * + * @return PaylaterInstallment + */ + public function setInquiryId(?string $inquiryId): PaylaterInstallment + { + $this->inquiryId = $inquiryId; + return $this; + } + + /** + * @return int|null + */ + public function getNumberOfRates(): ?int + { + return $this->numberOfRates; + } + + /** + * @param int|null $numberOfRates + * + * @return PaylaterInstallment + */ + public function setNumberOfRates(?int $numberOfRates): PaylaterInstallment + { + $this->numberOfRates = $numberOfRates; + return $this; + } + + /** + * @return string|null + */ + public function getIban(): ?string + { + return $this->iban; + } + + /** + * @param string|null $iban + * + * @return $this + */ + public function setIban(?string $iban): self + { + $this->iban = $iban; + return $this; + } + + /** + * @return string|null + */ + public function getCountry(): ?string + { + return $this->country; + } + + /** + * @param string|null $country + * + * @return $this + */ + public function setCountry(?string $country): self + { + $this->country = $country; + return $this; + } + + /** + * @return string|null + */ + public function getHolder(): ?string + { + return $this->holder; + } + + /** + * @param string|null $holder + * + * @return $this + */ + public function setHolder(?string $holder): self + { + $this->holder = $holder; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PaylaterInvoice.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PaylaterInvoice.php new file mode 100644 index 0000000..fa7b1c0 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PaylaterInvoice.php @@ -0,0 +1,8 @@ + - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Adapter\HttpAdapterInterface; +use UnzerSDK\Constants\AdditionalAttributes; +use UnzerSDK\Constants\ExemptionType; +use UnzerSDK\Constants\RecurrenceTypes; use UnzerSDK\Constants\TransactionTypes; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\AbstractUnzerResource; @@ -39,8 +19,16 @@ use UnzerSDK\Traits\HasOrderId; use RuntimeException; use stdClass; + use function in_array; +/** + * This is the implementation of the Pay Page which allows for displaying a page containing all + * payment types of the merchant. + * + * @link https://docs.unzer.com/ + * + */ class Paypage extends BasePaymentType { use CanDirectCharge; @@ -116,8 +104,6 @@ public function __construct(float $amount, string $currency, string $returnUrl) $this->setReturnUrl($returnUrl); } - // - /** * @return float */ @@ -188,7 +174,7 @@ public function getLogoImage(): ?string * * @return Paypage */ - public function setLogoImage($logoImage): Paypage + public function setLogoImage(?string $logoImage): Paypage { $this->logoImage = $logoImage; return $this; @@ -207,7 +193,7 @@ public function getFullPageImage(): ?string * * @return Paypage */ - public function setFullPageImage($fullPageImage): Paypage + public function setFullPageImage(?string $fullPageImage): Paypage { $this->fullPageImage = $fullPageImage; return $this; @@ -226,7 +212,7 @@ public function getShopName(): ?string * * @return Paypage */ - public function setShopName($shopName): Paypage + public function setShopName(?string $shopName): Paypage { $this->shopName = $shopName; return $this; @@ -245,7 +231,7 @@ public function getShopDescription(): ?string * * @return Paypage */ - public function setShopDescription($shopDescription): Paypage + public function setShopDescription(?string $shopDescription): Paypage { $this->shopDescription = $shopDescription; return $this; @@ -264,7 +250,7 @@ public function getTagline(): ?string * * @return Paypage */ - public function setTagline($tagline): Paypage + public function setTagline(?string $tagline): Paypage { $this->tagline = $tagline; return $this; @@ -283,7 +269,7 @@ public function getTermsAndConditionUrl(): ?string * * @return Paypage */ - public function setTermsAndConditionUrl($termsAndConditionUrl): Paypage + public function setTermsAndConditionUrl(?string $termsAndConditionUrl): Paypage { $this->termsAndConditionUrl = $termsAndConditionUrl; return $this; @@ -302,7 +288,7 @@ public function getPrivacyPolicyUrl(): ?string * * @return Paypage */ - public function setPrivacyPolicyUrl($privacyPolicyUrl): Paypage + public function setPrivacyPolicyUrl(?string $privacyPolicyUrl): Paypage { $this->privacyPolicyUrl = $privacyPolicyUrl; return $this; @@ -321,7 +307,7 @@ public function getImprintUrl(): ?string * * @return Paypage */ - public function setImprintUrl($imprintUrl): Paypage + public function setImprintUrl(?string $imprintUrl): Paypage { $this->imprintUrl = $imprintUrl; return $this; @@ -340,7 +326,7 @@ public function getHelpUrl(): ?string * * @return Paypage */ - public function setHelpUrl($helpUrl): Paypage + public function setHelpUrl(?string $helpUrl): Paypage { $this->helpUrl = $helpUrl; return $this; @@ -359,7 +345,7 @@ public function getContactUrl(): ?string * * @return Paypage */ - public function setContactUrl($contactUrl): Paypage + public function setContactUrl(?string $contactUrl): Paypage { $this->contactUrl = $contactUrl; return $this; @@ -380,6 +366,7 @@ public function getAction(): string */ public function setAction(String $action): Paypage { + $action = strtolower($action); if (in_array($action, [TransactionTypes::CHARGE, TransactionTypes::AUTHORIZATION], true)) { $this->action = $action; } @@ -533,7 +520,7 @@ public function isCard3ds(): ?bool * * @return Paypage */ - public function setCard3ds($card3ds): Paypage + public function setCard3ds(?bool $card3ds): Paypage { $this->card3ds = $card3ds; return $this; @@ -552,51 +539,97 @@ public function getCss(): ?array * * @return Paypage */ - public function setCss($styles): Paypage + public function setCss(?array $styles): Paypage { $this->css = empty($styles) ? null : $styles; return $this; } /** - * @param float|null $effectiveInterestRate + * @return float|null + */ + public function getEffectiveInterestRate(): ?float + { + return $this->getAdditionalAttribute(AdditionalAttributes::EFFECTIVE_INTEREST_RATE); + } + + /** + * @param float $effectiveInterestRate * * @return Paypage */ public function setEffectiveInterestRate(float $effectiveInterestRate): Paypage { - $this->setAdditionalAttribute('effectiveInterestRate', $effectiveInterestRate); + $this->setAdditionalAttribute(AdditionalAttributes::EFFECTIVE_INTEREST_RATE, $effectiveInterestRate); return $this; } /** - * @return float|null + * @return string|null */ - public function getEffectiveInterestRate(): ?float + public function getRecurrenceType(): ?string { - return $this->getAdditionalAttribute('effectiveInterestRate'); + return $this->getAdditionalAttribute(AdditionalAttributes::RECURRENCE_TYPE); } - // + /** + * @param string $recurrenceType + * + * @see RecurrenceTypes + * + * @return Paypage + */ + public function setRecurrenceType(string $recurrenceType): Paypage + { + $this->setAdditionalAttribute(AdditionalAttributes::RECURRENCE_TYPE, $recurrenceType); + return $this; + } - // + /** + * @return string|null + */ + public function getExemptionType(): ?string + { + return $this->getAdditionalAttribute(AdditionalAttributes::EXEMPTION_TYPE); + } + + /** + * @param string $exemptionType + * + * @see ExemptionType + * + * @return Paypage + */ + public function setExemptionType(string $exemptionType): Paypage + { + $this->setAdditionalAttribute(AdditionalAttributes::EXEMPTION_TYPE, $exemptionType); + return $this; + } /** * {@inheritDoc} * Change resource path. */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { + $basePath = 'paypage'; + + if ($httpMethod === HttpAdapterInterface::REQUEST_GET) { + return $basePath; + } + switch ($this->action) { case TransactionTypes::AUTHORIZATION: - return 'paypage/authorize'; + $transactionType = TransactionTypes::AUTHORIZATION; break; case TransactionTypes::CHARGE: // intended Fall-Through default: - return 'paypage/charge'; + $transactionType = TransactionTypes::CHARGE; break; } + + return $basePath . '/' . $transactionType; } /** @@ -606,19 +639,33 @@ protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_G * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { if (isset($response->impressumUrl)) { $response->imprintUrl = $response->impressumUrl; unset($response->impressumUrl); } - parent::handleResponse($response, $method); - /** @var Payment $payment */ $payment = $this->getPayment(); if (isset($response->resources->paymentId)) { - $payment->setId($response->resources->paymentId); + $paymentId = $response->resources->paymentId; + + if (null === $payment) { + $payment = new Payment($this->getUnzerObject()); + $payment->setId($paymentId) + ->setPayPage($this); + $this->setPayment($payment); + $this->fetchPayment(); + } + + $payment->setId($paymentId); + } + + parent::handleResponse($response, $method); + + if (isset($response->additionalAttributes)) { + $this->additionalAttributes = (array)$response->additionalAttributes; } if ($method !== HttpAdapterInterface::REQUEST_GET) { @@ -647,15 +694,13 @@ public function expose() public function getLinkedResources(): array { return [ - 'customer'=> $this->getCustomer(), + 'customer' => $this->getCustomer(), 'metadata' => $this->getMetadata(), 'basket' => $this->getBasket(), 'payment' => $this->getPayment() ]; } - // - /** * Updates the referenced payment object if it exists and if this is not the payment object itself. * This is called from the crud methods to update the payments state whenever anything happens. diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Paypal.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Paypal.php index 1a8c780..17129e1 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Paypal.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Paypal.php @@ -1,29 +1,10 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; +use RuntimeException; +use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\Resources\Recurring; use UnzerSDK\Traits\CanRecur; use UnzerSDK\Traits\CanAuthorize; use UnzerSDK\Traits\CanDirectCharge; @@ -32,13 +13,13 @@ class Paypal extends BasePaymentType { use CanAuthorize; use CanDirectCharge; - use CanRecur; + use CanRecur { + activateRecurring as traitActivateRecurring; + } /** @var string|null $email */ protected $email; - // - /** * @return string|null */ @@ -58,5 +39,19 @@ public function setEmail(string $email): Paypal return $this; } - // + /** + * Activates recurring payment for Paypal. + * + * @param string $returnUrl The URL to which the customer gets redirected in case of a 3ds transaction + * @param null|mixed $recurrenceType Recurrence type used for recurring payment. + * + * @return Recurring + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + */ + public function activateRecurring($returnUrl, $recurrenceType = null): Recurring + { + return $this->traitActivateRecurring($returnUrl, $recurrenceType); + } } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PostFinanceCard.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PostFinanceCard.php new file mode 100644 index 0000000..c839a26 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/PostFinanceCard.php @@ -0,0 +1,10 @@ + - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Przelewy24.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Przelewy24.php index a06758d..db9a665 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Przelewy24.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Przelewy24.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebit.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebit.php index f3218d6..ba7e51e 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebit.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebit.php @@ -2,26 +2,10 @@ /** * This represents the SEPA direct debit payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\PaymentTypes */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; @@ -44,15 +28,13 @@ class SepaDirectDebit extends BasePaymentType protected $holder; /** - * @param string $iban + * @param string|null $iban */ - public function __construct($iban) + public function __construct(?string $iban) { $this->iban = $iban; } - // - /** * @return string|null */ @@ -62,11 +44,11 @@ public function getIban(): ?string } /** - * @param string $iban + * @param string|null $iban * * @return $this */ - public function setIban($iban): self + public function setIban(?string $iban): self { $this->iban = $iban; return $this; @@ -81,11 +63,11 @@ public function getBic(): ?string } /** - * @param string $bic + * @param string|null $bic * * @return $this */ - public function setBic($bic): self + public function setBic(?string $bic): self { $this->bic = $bic; return $this; @@ -100,15 +82,13 @@ public function getHolder(): ?string } /** - * @param string $holder + * @param string|null $holder * * @return $this */ - public function setHolder($holder): self + public function setHolder(?string $holder): self { $this->holder = $holder; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebitSecured.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebitSecured.php index 7c7342d..46fe054 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebitSecured.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/SepaDirectDebitSecured.php @@ -2,32 +2,18 @@ /** * This represents the SEPA direct debit secured payment type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\PaymentTypes */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectChargeWithCustomer; use UnzerSDK\Traits\CanPayoutWithCustomer; use UnzerSDK\Traits\CanRecur; +/** @deprecated please use PaylaterDirectDebit instead. + */ class SepaDirectDebitSecured extends BasePaymentType { use CanDirectChargeWithCustomer; @@ -44,15 +30,13 @@ class SepaDirectDebitSecured extends BasePaymentType protected $holder; /** - * @param string $iban + * @param string|null $iban */ - public function __construct($iban) + public function __construct(?string $iban) { $this->iban = $iban; } - // - /** * @return string|null */ @@ -62,11 +46,11 @@ public function getIban(): ?string } /** - * @param string $iban + * @param string|null $iban * * @return $this */ - public function setIban($iban): self + public function setIban(?string $iban): self { $this->iban = $iban; return $this; @@ -81,11 +65,11 @@ public function getBic(): ?string } /** - * @param string $bic + * @param string|null $bic * * @return $this */ - public function setBic($bic): self + public function setBic(?string $bic): self { $this->bic = $bic; return $this; @@ -100,15 +84,13 @@ public function getHolder(): ?string } /** - * @param string $holder + * @param string|null $holder * * @return $this */ - public function setHolder($holder): self + public function setHolder(?string $holder): self { $this->holder = $holder; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Sofort.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Sofort.php index 3bf5dc4..5f24082 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Sofort.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Sofort.php @@ -1,32 +1,12 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; +use UnzerSDK\Traits\HasAccountInformation; class Sofort extends BasePaymentType { + use HasAccountInformation; use CanDirectCharge; } diff --git a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Wechatpay.php b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Wechatpay.php index bf9a10b..d34a06d 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Wechatpay.php +++ b/vendor/unzerdev/php-sdk/src/Resources/PaymentTypes/Wechatpay.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\PaymentTypes - */ + namespace UnzerSDK\Resources\PaymentTypes; use UnzerSDK\Traits\CanDirectCharge; diff --git a/vendor/unzerdev/php-sdk/src/Resources/Recurring.php b/vendor/unzerdev/php-sdk/src/Resources/Recurring.php index c47916b..942f49a 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Recurring.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Recurring.php @@ -1,29 +1,8 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; +use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Traits\HasAdditionalTransactionData; use UnzerSDK\Traits\HasCustomerMessage; use UnzerSDK\Traits\HasDate; @@ -31,6 +10,12 @@ use UnzerSDK\Traits\HasStates; use UnzerSDK\Traits\HasUniqueAndShortId; +/** + * This represents the Recurring resource. + * + * @link https://docs.unzer.com/ + * + */ class Recurring extends AbstractUnzerResource { use HasStates; @@ -59,8 +44,6 @@ public function __construct(string $paymentType, string $returnUrl) $this->paymentTypeId = $paymentType; } - // - /** * @return string */ @@ -112,20 +95,16 @@ public function getRedirectUrl(): ?string * * @return Recurring */ - protected function setRedirectUrl($redirectUrl): Recurring + protected function setRedirectUrl(?string $redirectUrl): Recurring { $this->redirectUrl = $redirectUrl; return $this; } - // - - // - /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { $parts = [ 'types', @@ -135,6 +114,4 @@ protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_G return implode('/', $parts); } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/AbstractTransactionType.php b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/AbstractTransactionType.php index 4c0614f..1572e8b 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/AbstractTransactionType.php +++ b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/AbstractTransactionType.php @@ -2,36 +2,24 @@ /** * This is the base class for all transaction types. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\TransactionTypes */ + namespace UnzerSDK\Resources\TransactionTypes; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\AbstractUnzerResource; +use UnzerSDK\Resources\EmbeddedResources\CardTransactionData; +use UnzerSDK\Resources\EmbeddedResources\RiskData; +use UnzerSDK\Resources\EmbeddedResources\ShippingData; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Traits\HasAdditionalTransactionData; use UnzerSDK\Traits\HasCustomerMessage; use UnzerSDK\Traits\HasDate; +use UnzerSDK\Traits\HasInvoiceId; use UnzerSDK\Traits\HasOrderId; use UnzerSDK\Traits\HasStates; use UnzerSDK\Traits\HasTraceId; @@ -42,6 +30,7 @@ abstract class AbstractTransactionType extends AbstractUnzerResource { use HasOrderId; + use HasInvoiceId; use HasStates; use HasUniqueAndShortId; use HasTraceId; @@ -49,15 +38,10 @@ abstract class AbstractTransactionType extends AbstractUnzerResource use HasAdditionalTransactionData; use HasDate; - // /** @var Payment $payment */ private $payment; - // - - // - /** * Return the payment property. * @@ -75,7 +59,7 @@ public function getPayment(): ?Payment * * @return $this */ - public function setPayment($payment): self + public function setPayment(Payment $payment): self { $this->payment = $payment; $this->setParentResource($payment); @@ -83,9 +67,9 @@ public function setPayment($payment): self } /** - * Return the Id of the referenced payment object. + * Return the ID of the referenced payment object. * - * @return null|string The Id of the payment object or null if nothing is found. + * @return null|string The ID of the payment object or null if nothing is found. */ public function getPaymentId(): ?string { @@ -106,17 +90,13 @@ public function getRedirectUrl(): ?string return $this->payment->getRedirectUrl(); } - // - - // - /** * {@inheritDoc} * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); @@ -130,9 +110,7 @@ public function handleResponse(stdClass $response, $method = HttpAdapterInterfac $payment->handleResponse((object)['redirectUrl' => $response->redirectUrl]); } - if (isset($response->additionalTransactionData)) { - $this->setAdditionalTransactionData($response->additionalTransactionData); - } + $this->handleAdditionalTransactionData($response); if ($method !== HttpAdapterInterface::REQUEST_GET) { $this->fetchPayment(); @@ -154,15 +132,13 @@ public function getLinkedResources(): array } return [ - 'customer'=> $payment->getCustomer(), + 'customer' => $payment->getCustomer(), 'type' => $paymentType, 'metadata' => $payment->getMetadata(), 'basket' => $payment->getBasket() ]; } - // - /** * Updates the referenced payment object if it exists and if this is not the payment object itself. * This is called from the crud methods to update the payments state whenever anything happens. @@ -177,4 +153,74 @@ public function fetchPayment(): void $this->fetchResource($payment); } } + + /** + * Handle additional transaction data from API response. + * + * @param stdClass $response + * + * @return void + */ + protected function handleAdditionalTransactionData(stdClass $response): void + { + $additionalTransactionData = $response->additionalTransactionData ?? null; + if ($additionalTransactionData !== null) { + $this->setAdditionalTransactionData($additionalTransactionData); + + $this->handleRiskData($additionalTransactionData); + $this->handleShipping($additionalTransactionData); + $this->handleCardTransactionData($additionalTransactionData); + } + } + + /** + * Handle risk data object contained in additional transaction data from API response. + * + * @param stdClass $additionalTransactionData + * + * @return void + */ + protected function handleRiskData(stdClass $additionalTransactionData): void + { + $riskData = $additionalTransactionData->riskData ?? null; + if ($riskData !== null) { + $riskDataObject = $this->getRiskData() ?? new RiskData(); + $riskDataObject->handleResponse($riskData); + $this->setRiskData($riskDataObject); + } + } + + /** + * Handle risk data object contained in additional transaction data from API response. + * + * @param stdClass $additionalTransactionData + * + * @return void + */ + protected function handleShipping(stdClass $additionalTransactionData): void + { + $shipping = $additionalTransactionData->shipping ?? null; + if ($shipping !== null) { + $shippingObject = $this->getShipping() ?? new ShippingData(); + $shippingObject->handleResponse($shipping); + $this->setShipping($shippingObject); + } + } + + /** + * Handle CardTransactionData object contained in additional transaction data from API response. + * + * @param stdClass $additionalTransactionData + * + * @return void + */ + protected function handleCardTransactionData(stdClass $additionalTransactionData): void + { + $card = $additionalTransactionData->card ?? null; + if ($card !== null) { + $cardTransactionData = $this->getCardTransactionData() ?? new CardTransactionData(); + $cardTransactionData->handleResponse($card); + $this->setCardTransactionData($cardTransactionData); + } + } } diff --git a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Authorization.php b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Authorization.php index 8754325..b37ac71 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Authorization.php +++ b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Authorization.php @@ -1,42 +1,28 @@ - * - * @package UnzerSDK\TransactionTypes - */ + namespace UnzerSDK\Resources\TransactionTypes; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\Payment; +use UnzerSDK\Traits\HasAccountInformation; use UnzerSDK\Traits\HasCancellations; -use UnzerSDK\Traits\HasInvoiceId; +use UnzerSDK\Traits\HasDescriptor; use UnzerSDK\Traits\HasRecurrenceType; use RuntimeException; +/** + * This represents the authorization transaction. + * + * @link https://docs.unzer.com/ + * + */ class Authorization extends AbstractTransactionType { use HasCancellations; - use HasInvoiceId; use HasRecurrenceType; + use HasAccountInformation; + use HasDescriptor; /** @var float $amount */ protected $amount = 0.0; @@ -65,19 +51,17 @@ class Authorization extends AbstractTransactionType /** * Authorization constructor. * - * @param float $amount - * @param string $currency - * @param string $returnUrl + * @param float|null $amount + * @param string|null $currency + * @param string|null $returnUrl */ - public function __construct($amount = null, $currency = null, $returnUrl = null) + public function __construct(float $amount = null, string $currency = null, string $returnUrl = null) { $this->setAmount($amount); $this->setCurrency($currency); $this->setReturnUrl($returnUrl); } - // - /** * @return float|null */ @@ -87,11 +71,11 @@ public function getAmount(): ?float } /** - * @param float $amount + * @param float|null $amount * * @return self */ - public function setAmount($amount): self + public function setAmount(?float $amount): self { $this->amount = $amount !== null ? round($amount, 4) : null; return $this; @@ -120,11 +104,11 @@ public function getCurrency(): ?string } /** - * @param string $currency + * @param string|null $currency * * @return self */ - public function setCurrency($currency): self + public function setCurrency(?string $currency): self { $this->currency = $currency; return $this; @@ -139,11 +123,11 @@ public function getReturnUrl(): ?string } /** - * @param string $returnUrl + * @param string|null $returnUrl * * @return self */ - public function setReturnUrl($returnUrl): self + public function setReturnUrl(?string $returnUrl): self { $this->returnUrl = $returnUrl; return $this; @@ -162,7 +146,7 @@ public function isCard3ds(): ?bool * * @return Authorization */ - public function setCard3ds($card3ds): Authorization + public function setCard3ds(?bool $card3ds): Authorization { $this->card3ds = $card3ds; return $this; @@ -177,11 +161,11 @@ public function getPaymentReference(): ?string } /** - * @param $paymentReference + * @param string|null $paymentReference * * @return Authorization */ - public function setPaymentReference($paymentReference): Authorization + public function setPaymentReference(?string $paymentReference): Authorization { $this->paymentReference = $paymentReference; return $this; @@ -200,14 +184,14 @@ public function getExternalOrderId(): ?string * * @return Authorization */ - protected function setExternalOrderId($externalOrderId): Authorization + protected function setExternalOrderId(?string $externalOrderId): Authorization { $this->externalOrderId = $externalOrderId; return $this; } /** - * Returns the reference Id of the insurance provider if applicable. + * Returns the reference ID of the insurance provider if applicable. * * @return string|null */ @@ -217,13 +201,13 @@ public function getZgReferenceId(): ?string } /** - * Sets the reference Id of the insurance provider. + * Sets the reference ID of the insurance provider. * * @param string|null $zgReferenceId * * @return Authorization */ - protected function setZgReferenceId($zgReferenceId): Authorization + protected function setZgReferenceId(?string $zgReferenceId): Authorization { $this->zgReferenceId = $zgReferenceId; return $this; @@ -242,37 +226,31 @@ public function getPDFLink(): ?string * * @return Authorization */ - protected function setPDFLink($PDFLink): Authorization + protected function setPDFLink(?string $PDFLink): Authorization { $this->PDFLink = $PDFLink; return $this; } - // - - // - /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'authorize'; } - // - /** * Full cancel of this authorization. * - * @param null $amount + * @param float|null $amount * * @return Cancellation * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function cancel($amount = null): Cancellation + public function cancel(float $amount = null): Cancellation { return $this->getUnzerObject()->cancelAuthorization($this, $amount); } @@ -280,14 +258,14 @@ public function cancel($amount = null): Cancellation /** * Charge authorization. * - * @param null $amount + * @param float|null $amount * * @return Charge * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ - public function charge($amount = null): Charge + public function charge(float $amount = null): Charge { $payment = $this->getPayment(); if (!$payment instanceof Payment) { diff --git a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Cancellation.php b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Cancellation.php index b2ccbce..26d92e8 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Cancellation.php +++ b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Cancellation.php @@ -1,35 +1,20 @@ - * - * @package UnzerSDK\TransactionTypes - */ + namespace UnzerSDK\Resources\TransactionTypes; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Constants\CancelReasonCodes; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\InstallmentSecured; + use function in_array; +/** + * This represents the cancel transaction. + * + * @link https://docs.unzer.com/ + * + */ class Cancellation extends AbstractTransactionType { /** @@ -62,15 +47,13 @@ class Cancellation extends AbstractTransactionType /** * Authorization constructor. * - * @param float $amount The amount to be cancelled, is transferred as grossAmount in case of Installment Secured. + * @param float|null $amount The amount to be cancelled, is transferred as grossAmount in case of Installment Secured. */ - public function __construct($amount = null) + public function __construct(float $amount = null) { $this->setAmount($amount); } - // - /** * Returns the cancellationAmount (equals grossAmount in case of Installment Secured). * @@ -84,11 +67,11 @@ public function getAmount(): ?float /** * Sets the cancellationAmount (equals grossAmount in case of Installment Secured). * - * @param float $amount + * @param float|null $amount * * @return Cancellation */ - public function setAmount($amount): Cancellation + public function setAmount(?float $amount): self { $this->amount = $amount !== null ? round($amount, 4) : null; return $this; @@ -111,7 +94,7 @@ public function getReasonCode(): ?string * * @return Cancellation */ - public function setReasonCode($reasonCode): Cancellation + public function setReasonCode(?string $reasonCode): Cancellation { if (in_array($reasonCode, array_merge(CancelReasonCodes::REASON_CODE_ARRAY, [null]), true)) { $this->reasonCode = $reasonCode; @@ -132,7 +115,7 @@ public function getPaymentReference(): ?string * * @return Cancellation */ - public function setPaymentReference($paymentReference): Cancellation + public function setPaymentReference(?string $paymentReference): Cancellation { $this->paymentReference = $paymentReference; return $this; @@ -157,7 +140,7 @@ public function getAmountNet(): ?float * * @return Cancellation The resulting cancellation object. */ - public function setAmountNet($amountNet): Cancellation + public function setAmountNet(?float $amountNet): Cancellation { $this->amountNet = $amountNet; return $this; @@ -182,16 +165,12 @@ public function getAmountVat(): ?float * * @return Cancellation */ - public function setAmountVat($amountVat): Cancellation + public function setAmountVat(?float $amountVat): Cancellation { $this->amountVat = $amountVat; return $this; } - // - - // - /** * {@inheritDoc} */ @@ -210,10 +189,8 @@ public function expose() /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'cancels'; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Charge.php b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Charge.php index 7a26acc..d7f1685 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Charge.php +++ b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Charge.php @@ -1,41 +1,29 @@ - * - * @package UnzerSDK\TransactionTypes - */ + namespace UnzerSDK\Resources\TransactionTypes; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\Traits\HasAccountInformation; use UnzerSDK\Traits\HasCancellations; -use UnzerSDK\Traits\HasInvoiceId; +use UnzerSDK\Traits\HasChargebacks; +use UnzerSDK\Traits\HasDescriptor; use UnzerSDK\Traits\HasRecurrenceType; use RuntimeException; +/** + * This represents the charge transaction. + * + * @link https://docs.unzer.com/ + * + */ class Charge extends AbstractTransactionType { use HasCancellations; - use HasInvoiceId; use HasRecurrenceType; + use HasAccountInformation; + use HasDescriptor; + use HasChargebacks; /** @var float $amount */ protected $amount; @@ -46,18 +34,6 @@ class Charge extends AbstractTransactionType /** @var string $returnUrl */ protected $returnUrl; - /** @var string $iban */ - private $iban; - - /** @var string bic */ - private $bic; - - /** @var string $holder */ - private $holder; - - /** @var string $descriptor */ - private $descriptor; - /** @var string $paymentReference */ protected $paymentReference; @@ -67,19 +43,17 @@ class Charge extends AbstractTransactionType /** * Authorization constructor. * - * @param float $amount - * @param string $currency - * @param string $returnUrl + * @param float|null $amount + * @param string|null $currency + * @param string|null $returnUrl */ - public function __construct($amount = null, $currency = null, $returnUrl = null) + public function __construct(float $amount = null, string $currency = null, string $returnUrl = null) { $this->setAmount($amount); $this->setCurrency($currency); $this->setReturnUrl($returnUrl); } - // - /** * @return float|null */ @@ -89,11 +63,11 @@ public function getAmount(): ?float } /** - * @param float $amount + * @param float|null $amount * * @return self */ - public function setAmount($amount): self + public function setAmount(?float $amount): self { $this->amount = $amount !== null ? round($amount, 4) : null; return $this; @@ -107,7 +81,9 @@ public function getCancelledAmount(): ?float $amount = 0.0; foreach ($this->getCancellations() as $cancellation) { /** @var Cancellation $cancellation */ - $amount += $cancellation->getAmount(); + if ($cancellation->isSuccess()) { + $amount += $cancellation->getAmount(); + } } return $amount; @@ -118,7 +94,7 @@ public function getCancelledAmount(): ?float */ public function getTotalAmount(): ?float { - return $this->getAmount() - $this->getCancelledAmount(); + return round($this->getAmount() - $this->getCancelledAmount(), 4); } /** @@ -130,11 +106,11 @@ public function getCurrency(): ?string } /** - * @param string $currency + * @param string|null $currency * * @return self */ - public function setCurrency($currency): self + public function setCurrency(?string $currency): self { $this->currency = $currency; return $this; @@ -149,104 +125,16 @@ public function getReturnUrl(): ?string } /** - * @param string $returnUrl + * @param string|null $returnUrl * * @return self */ - public function setReturnUrl($returnUrl): self + public function setReturnUrl(?string $returnUrl): self { $this->returnUrl = $returnUrl; return $this; } - /** - * Returns the IBAN of the account the customer needs to transfer the amount to. - * E. g. invoice, prepayment, etc. - * - * @return string|null - */ - public function getIban(): ?string - { - return $this->iban; - } - - /** - * @param string $iban - * - * @return self - */ - protected function setIban(string $iban): self - { - $this->iban = $iban; - return $this; - } - - /** - * Returns the BIC of the account the customer needs to transfer the amount to. - * E. g. invoice, prepayment, etc. - * - * @return string|null - */ - public function getBic(): ?string - { - return $this->bic; - } - - /** - * @param string $bic - * - * @return self - */ - protected function setBic(string $bic): self - { - $this->bic = $bic; - return $this; - } - - /** - * Returns the holder of the account the customer needs to transfer the amount to. - * E. g. invoice, prepayment, etc. - * - * @return string|null - */ - public function getHolder(): ?string - { - return $this->holder; - } - - /** - * @param string $holder - * - * @return self - */ - protected function setHolder(string $holder): self - { - $this->holder = $holder; - return $this; - } - - /** - * Returns the Descriptor the customer needs to use when transferring the amount. - * E. g. invoice, prepayment, etc. - * - * @return string|null - */ - public function getDescriptor(): ?string - { - return $this->descriptor; - } - - /** - * @param string $descriptor - * - * @return self - */ - protected function setDescriptor(string $descriptor): self - { - $this->descriptor = $descriptor; - return $this; - } - /** * @return string|null */ @@ -260,7 +148,7 @@ public function getPaymentReference(): ?string * * @return Charge */ - public function setPaymentReference($referenceText): Charge + public function setPaymentReference(?string $referenceText): Charge { $this->paymentReference = $referenceText; return $this; @@ -279,26 +167,20 @@ public function isCard3ds(): ?bool * * @return Charge */ - public function setCard3ds($card3ds): Charge + public function setCard3ds(?bool $card3ds): Charge { $this->card3ds = $card3ds; return $this; } - // - - // - /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'charges'; } - // - /** * Full cancel of this authorization. * Returns the last cancellation object if charge is already canceled. @@ -317,11 +199,11 @@ protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_G * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function cancel( - $amount = null, + float $amount = null, string $reasonCode = null, string $paymentReference = null, - float $amountNet = null, - float $amountVat = null + float $amountNet = null, + float $amountVat = null ): Cancellation { return $this->getUnzerObject()->cancelCharge( $this, diff --git a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Chargeback.php b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Chargeback.php new file mode 100644 index 0000000..7c0c592 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Chargeback.php @@ -0,0 +1,95 @@ +setAmount($amount); + } + + /** + * @return float|null + */ + public function getAmount(): ?float + { + return $this->amount; + } + + /** + * Sets the cancellationAmount (equals grossAmount in case of Installment Secured). + * + * @param float|null $amount + * + * @return Cancellation + */ + public function setAmount(?float $amount): self + { + $this->amount = $amount !== null ? round($amount, 4) : null; + return $this; + } + + /** + * @return string + */ + public function getCurrency(): string + { + return $this->currency; + } + + /** + * @param string $currency + */ + public function setCurrency(string $currency): void + { + $this->currency = $currency; + } + + /** + * @return string|null + */ + public function getPaymentReference(): ?string + { + return $this->paymentReference; + } + + /** + * @param string|null $paymentReference + * + * @return Cancellation + */ + public function setPaymentReference(?string $paymentReference): Chargeback + { + $this->paymentReference = $paymentReference; + return $this; + } + + /** + * {@inheritDoc} + */ + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string + { + return 'chargebacks'; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Payout.php b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Payout.php index 183392f..39f6a93 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Payout.php +++ b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Payout.php @@ -1,36 +1,17 @@ - * - * @package UnzerSDK\TransactionTypes */ -namespace UnzerSDK\Resources\TransactionTypes; - -use UnzerSDK\Adapter\HttpAdapterInterface; -use UnzerSDK\Traits\HasInvoiceId; - class Payout extends AbstractTransactionType { - use HasInvoiceId; - /** @var float|null $amount */ protected $amount; @@ -46,19 +27,17 @@ class Payout extends AbstractTransactionType /** * Payout constructor. * - * @param float $amount - * @param string $currency - * @param null $returnUrl + * @param float|null $amount + * @param string|null $currency + * @param null $returnUrl */ - public function __construct($amount = null, $currency = null, $returnUrl = null) + public function __construct(float $amount = null, string $currency = null, $returnUrl = null) { $this->setAmount($amount); $this->setCurrency($currency); $this->setReturnUrl($returnUrl); } - // - /** * @return float|null */ @@ -68,11 +47,11 @@ public function getAmount(): ?float } /** - * @param float $amount + * @param float|null $amount * * @return self */ - public function setAmount($amount): self + public function setAmount(?float $amount): self { $this->amount = $amount !== null ? round($amount, 4) : null; return $this; @@ -87,11 +66,11 @@ public function getCurrency(): ?string } /** - * @param string $currency + * @param string|null $currency * * @return self */ - public function setCurrency($currency): self + public function setCurrency(?string $currency): self { $this->currency = $currency; return $this; @@ -110,7 +89,7 @@ public function getReturnUrl(): ?string * * @return Payout */ - public function setReturnUrl($returnUrl): Payout + public function setReturnUrl(?string $returnUrl): Payout { $this->returnUrl = $returnUrl; return $this; @@ -135,17 +114,11 @@ public function setPaymentReference($referenceText): Payout return $this; } - // - - // - /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'payouts'; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Shipment.php b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Shipment.php index ee0bf68..55dfbc7 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Shipment.php +++ b/vendor/unzerdev/php-sdk/src/Resources/TransactionTypes/Shipment.php @@ -1,40 +1,20 @@ - * - * @package UnzerSDK\TransactionTypes */ -namespace UnzerSDK\Resources\TransactionTypes; - -use UnzerSDK\Traits\HasInvoiceId; - class Shipment extends AbstractTransactionType { - use HasInvoiceId; - /** @var float|null $amount */ protected $amount; - // - /** * @return float|null */ @@ -44,27 +24,21 @@ public function getAmount(): ?float } /** - * @param float $amount + * @param float|null $amount * * @return Shipment */ - public function setAmount($amount): Shipment + public function setAmount(?float $amount): self { $this->amount = $amount !== null ? round($amount, 4) : null; return $this; } - // - - // - /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'shipments'; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/Webhook.php b/vendor/unzerdev/php-sdk/src/Resources/Webhook.php index 5545780..df2f55c 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Webhook.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Webhook.php @@ -1,29 +1,15 @@ - * - * @package UnzerSDK\Resources */ -namespace UnzerSDK\Resources; - class Webhook extends AbstractUnzerResource { /** @var string $url */ @@ -44,8 +30,6 @@ public function __construct(string $url = '', string $event = '') $this->event = $event; } - // - /** * @return string|null */ @@ -84,17 +68,11 @@ public function setEvent(string $event): Webhook return $this; } - // - - // - /** * {@inheritDoc} */ - protected function getResourcePath($httpMethod = HttpAdapterInterface::REQUEST_GET): string + protected function getResourcePath(string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'webhooks'; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Resources/Webhooks.php b/vendor/unzerdev/php-sdk/src/Resources/Webhooks.php index b169b03..2cb1e82 100644 --- a/vendor/unzerdev/php-sdk/src/Resources/Webhooks.php +++ b/vendor/unzerdev/php-sdk/src/Resources/Webhooks.php @@ -1,37 +1,22 @@ - * - * @package UnzerSDK\Resources - */ + namespace UnzerSDK\Resources; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Constants\WebhookEvents; use RuntimeException; use stdClass; + use function in_array; +/** + * This class represents a group of Webhooks. + * It is a pseudo resource used to manage bulk operations on webhooks. + * It will never receive an id from the API. + * + * @link https://docs.unzer.com/ + * + */ class Webhooks extends AbstractUnzerResource { /** @var string $url */ @@ -55,8 +40,6 @@ public function __construct(string $url = '', array $eventList = []) $this->eventList = $eventList; } - // - /** * @return string */ @@ -105,15 +88,13 @@ public function getWebhookList(): array return $this->webhooks; } - // - /** * @param stdClass $response * @param string $method * * @throws RuntimeException */ - public function handleResponse(stdClass $response, $method = HttpAdapterInterface::REQUEST_GET): void + public function handleResponse(stdClass $response, string $method = HttpAdapterInterface::REQUEST_GET): void { parent::handleResponse($response, $method); diff --git a/vendor/unzerdev/php-sdk/src/Services/CancelService.php b/vendor/unzerdev/php-sdk/src/Services/CancelService.php index df1da55..354cb90 100644 --- a/vendor/unzerdev/php-sdk/src/Services/CancelService.php +++ b/vendor/unzerdev/php-sdk/src/Services/CancelService.php @@ -1,42 +1,27 @@ - * - * @package UnzerSDK\Services - */ + namespace UnzerSDK\Services; +use RuntimeException; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Constants\CancelReasonCodes; use UnzerSDK\Exceptions\UnzerApiException; -use UnzerSDK\Unzer; use UnzerSDK\Interfaces\CancelServiceInterface; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\TransactionTypes\Authorization; use UnzerSDK\Resources\TransactionTypes\Cancellation; use UnzerSDK\Resources\TransactionTypes\Charge; -use RuntimeException; +use UnzerSDK\Unzer; + use function in_array; use function is_string; +/** + * This service provides for functionalities concerning cancel transactions. + * + * @link https://docs.unzer.com/ + * + */ class CancelService implements CancelServiceInterface { /** @var Unzer */ @@ -52,8 +37,6 @@ public function __construct(Unzer $unzer) $this->unzer = $unzer; } - //getUnzer()->getResourceService(); } - // - - // - /** * {@inheritDoc} */ @@ -107,10 +86,6 @@ public function cancelAuthorizationByPayment($payment, float $amount = null): Ca return $this->cancelAuthorization($authorization, $amount); } - // - - // - /** * {@inheritDoc} */ @@ -151,17 +126,13 @@ public function cancelCharge( return $cancellation; } - // - - // - /** * {@inheritDoc} */ public function cancelPayment( $payment, float $amount = null, - $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, + ?string $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, string $referenceText = null, float $amountNet = null, float $amountVat = null @@ -170,6 +141,11 @@ public function cancelPayment( if (is_string($payment)) { $paymentObject = $this->getResourceService()->fetchPayment($payment); } + $paymentType = $paymentObject->getPaymentType(); + if ($paymentType !== null && $paymentType->supportsDirectPaymentCancel()) { + $message = 'The used payment type is not supported by this cancel method. Please use Unzer::cancelAuthorizedPayment() or Unzer::cancelChargedPayment() instead.'; + throw new RuntimeException($message); + } if (!$paymentObject instanceof Payment) { throw new RuntimeException('Invalid payment object.'); @@ -240,11 +216,11 @@ public function cancelPaymentAuthorization($payment, float $amount = null): ?Can /** * @param Payment $payment - * @param string $reasonCode - * @param string $referenceText - * @param float $amountNet - * @param float $amountVat - * @param float $remainingToCancel + * @param ?string $reasonCode + * @param ?string $referenceText + * @param ?float $amountNet + * @param ?float $amountVat + * @param ?float $remainingToCancel * * @return array * @@ -253,22 +229,38 @@ public function cancelPaymentAuthorization($payment, float $amount = null): ?Can */ public function cancelPaymentCharges( Payment $payment, - $reasonCode, - $referenceText, - $amountNet, - $amountVat, - float $remainingToCancel = null + ?string $reasonCode, + ?string $referenceText, + ?float $amountNet, + ?float $amountVat, + ?float $remainingToCancel = null ): array { $cancellations = []; $cancelWholePayment = $remainingToCancel === null; - /** @var Charge $charge */ - foreach ($payment->getCharges() as $charge) { + /** @var array $charge */ + $charges = $payment->getCharges(); + $receiptAmount = $this->calculateReceiptAmount($charges); + foreach ($charges as $index => $charge) { $cancelAmount = null; if (!$cancelWholePayment && $remainingToCancel <= $charge->getTotalAmount()) { $cancelAmount = $remainingToCancel; } + /** @var Charge $charge */ + // Calculate the maximum cancel amount for initial transaction. + if ($index === 0 && $charge->isPending()) { + $maxReversalAmount = $this->calculateMaxReversalAmount($charge, $receiptAmount); + /* If canceled and charged amounts are equal or higher than the initial charge, skip it, + because there won't be anything left to cancel. */ + if ($maxReversalAmount <= 0) { + continue; + } + if ($maxReversalAmount < $cancelAmount) { + $cancelAmount = $maxReversalAmount; + } + } + try { $cancellation = $charge->cancel($cancelAmount, $reasonCode, $referenceText, $amountNet, $amountVat); } catch (UnzerApiException $e) { @@ -290,14 +282,51 @@ public function cancelPaymentCharges( return $cancellations; } - // + /** + * {@inheritDoc} + */ + public function cancelAuthorizedPayment($payment, ?Cancellation $cancellation = null): Cancellation + { + if ($cancellation === null) { + $cancellation = new Cancellation(); + } + + $paymentResource = $this->getResourceService()->getPaymentResource($payment); + + // Authorization is required to build the proper resource path for the cancellation. + $authorization = (new Authorization())->setParentResource($paymentResource); + $cancellation->setPayment($paymentResource) + ->setParentResource($authorization); + + /** @var Cancellation $cancellation */ + $cancellation = $this->getResourceService()->createResource($cancellation); + return $cancellation; + } + + /** + * {@inheritDoc} + */ + public function cancelChargedPayment($payment, ?Cancellation $cancellation = null): Cancellation + { + if ($cancellation === null) { + $cancellation = new Cancellation(); + } + $paymentResource = $this->getResourceService()->getPaymentResource($payment); + + // Charge is required to build the proper resource path for the cancellation. + $charge = (new Charge())->setParentResource($paymentResource); + $cancellation->setPayment($paymentResource) + ->setParentResource($charge); - // + /** @var Cancellation $cancellation */ + $cancellation = $this->getResourceService()->createResource($cancellation); + return $cancellation; + } /** * Throws exception if the passed exception is not to be ignored while cancelling charges or authorization. * - * @param $exception + * @param UnzerApiException $exception * * @throws UnzerApiException */ @@ -324,14 +353,36 @@ private function isExceptionAllowed(UnzerApiException $exception): void * * @return float|null */ - private function updateCancelAmount($remainingToCancel, float $amount): ?float + private function updateCancelAmount(?float $remainingToCancel, float $amount): ?float { $cancelWholePayment = $remainingToCancel === null; if (!$cancelWholePayment) { - $remainingToCancel -= $amount; + $remainingToCancel = round($remainingToCancel - $amount, 4); } return $remainingToCancel; } - // + protected function calculateReceiptAmount(array $charges): float + { + $receiptAmount = 0; + // Sum up Amounts of all successful charges from the list. + foreach ($charges as $charge) { + if ($charge->isSuccess()) { + $receiptAmount += $charge->getAmount(); + } + } + return $receiptAmount; + } + + /** Calculate max reversal amount for a charge and round it to 4th digit. + * + * @param Charge $charge + * @param float $receiptAmount + * + * @return float + */ + private function calculateMaxReversalAmount(Charge $charge, float $receiptAmount): float + { + return round($charge->getAmount() - $receiptAmount - $charge->getCancelledAmount(), 4); + } } diff --git a/vendor/unzerdev/php-sdk/src/Services/EnvironmentService.php b/vendor/unzerdev/php-sdk/src/Services/EnvironmentService.php index ac1ea74..68a048a 100644 --- a/vendor/unzerdev/php-sdk/src/Services/EnvironmentService.php +++ b/vendor/unzerdev/php-sdk/src/Services/EnvironmentService.php @@ -1,49 +1,22 @@ - * - * @package UnzerSDK\Services */ -namespace UnzerSDK\Services; - -use function in_array; -use function is_bool; - class EnvironmentService { private const ENV_VAR_NAME_ENVIRONMENT = 'UNZER_PAPI_ENV'; public const ENV_VAR_VALUE_STAGING_ENVIRONMENT = 'STG'; public const ENV_VAR_VALUE_DEVELOPMENT_ENVIRONMENT = 'DEV'; public const ENV_VAR_VALUE_PROD_ENVIRONMENT = 'PROD'; - - public const ENV_VAR_NAME_VERBOSE_TEST_LOGGING = 'UNZER_PAPI_VERBOSE_TEST_LOGGING'; - - public const ENV_VAR_TEST_PRIVATE_KEY = 'UNZER_PAPI_TEST_PRIVATE_KEY'; - public const ENV_VAR_TEST_PUBLIC_KEY = 'UNZER_PAPI_TEST_PUBLIC_KEY'; - public const ENV_VAR_TEST_PRIVATE_KEY_NON_3DS = 'UNZER_PAPI_TEST_PRIVATE_KEY_NON_3DS'; - public const ENV_VAR_TEST_PUBLIC_KEY_NON_3DS = 'UNZER_PAPI_TEST_PUBLIC_KEY_NON_3DS'; - - public const ENV_VAR_TEST_APPLE_MERCHANT_ID_FOLDER = 'UNZER_APPLE_MERCHANT_ID_PATH'; - public const ENV_VAR_TEST_APPLE_CA_CERTIFICATE = 'UNZER_APPLE_CA_CERTIFICATE_PATH'; - private const ENV_VAR_NAME_TIMEOUT = 'UNZER_PAPI_TIMEOUT'; private const DEFAULT_TIMEOUT = 60; @@ -76,16 +49,6 @@ public function getPapiEnvironment(): string return stripslashes($_SERVER[self::ENV_VAR_NAME_ENVIRONMENT] ?? self::ENV_VAR_VALUE_PROD_ENVIRONMENT); } - /** - * Returns false if the logging in tests is deactivated by environment variable. - * - * @return bool - */ - public static function isTestLoggingActive(): bool - { - return self::getBoolEnvValue(self::ENV_VAR_NAME_VERBOSE_TEST_LOGGING); - } - /** * Returns the timeout set via environment variable or the default timeout. * ATTENTION: Setting this value to 0 will disable the limit. @@ -108,56 +71,4 @@ public static function isCurlVerbose(): bool $curlVerbose = strtolower(stripslashes($_SERVER[self::ENV_VAR_NAME_CURL_VERBOSE] ?? 'false')); return in_array($curlVerbose, ['true', '1'], true); } - - /** - * Returns the private key string set via environment variable. - * Returns the non 3ds version of the key if the non3ds flag is set. - * Returns an empty string if the environment variable is not set. - * - * @param bool $non3ds - * - * @return string - */ - public static function getTestPrivateKey($non3ds = false): string - { - $variableName = $non3ds ? self::ENV_VAR_TEST_PRIVATE_KEY_NON_3DS : self::ENV_VAR_TEST_PRIVATE_KEY; - $key = stripslashes($_SERVER[$variableName] ?? ''); - return empty($key) ? '' : $key; - } - - /** - * Returns the public key string set via environment variable. - * Returns the non 3ds version of the key if the non3ds flag is set. - * Returns an empty string if the environment variable is not set. - * - * @param bool $non3ds - * - * @return string - */ - public static function getTestPublicKey($non3ds = false): string - { - $variableName = $non3ds ? self::ENV_VAR_TEST_PUBLIC_KEY_NON_3DS : self::ENV_VAR_TEST_PUBLIC_KEY; - $key = stripslashes($_SERVER[$variableName] ?? ''); - return empty($key) ? '' : $key; - } - - /** - * Returns the path to apple merchant ID folder set via environment variable. - * - * @return string - */ - public static function getAppleMerchantIdPath(): string - { - return stripslashes($_SERVER[self::ENV_VAR_TEST_APPLE_MERCHANT_ID_FOLDER] ?? ''); - } - - /** - * Returns the CA certificate path set via environment variable. - * - * @return string - */ - public static function getAppleCaCertificatePath(): string - { - return stripslashes($_SERVER[self::ENV_VAR_TEST_APPLE_CA_CERTIFICATE] ?? ''); - } } diff --git a/vendor/unzerdev/php-sdk/src/Services/HttpService.php b/vendor/unzerdev/php-sdk/src/Services/HttpService.php index 4c27504..f6f87ea 100644 --- a/vendor/unzerdev/php-sdk/src/Services/HttpService.php +++ b/vendor/unzerdev/php-sdk/src/Services/HttpService.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\Services - */ + namespace UnzerSDK\Services; use UnzerSDK\Adapter\CurlAdapter; @@ -30,13 +8,22 @@ use UnzerSDK\Unzer; use UnzerSDK\Resources\AbstractUnzerResource; use RuntimeException; + use function in_array; + use const PHP_VERSION; +/** + * This service provides for functionalities concerning http transactions. + * + * @link https://docs.unzer.com/ + * + */ class HttpService { private const URL_PART_STAGING_ENVIRONMENT = 'stg'; private const URL_PART_DEVELOPMENT_ENVIRONMENT = 'dev'; + private const URL_PART_SANDBOX_ENVIRONMENT = 'sbx'; /** @var HttpAdapterInterface $httpAdapter */ private $httpAdapter; @@ -44,8 +31,6 @@ class HttpService /** @var EnvironmentService $environmentService */ private $environmentService; - // - /** * Returns the currently set HttpAdapter. * If it is not set it will create a CurlRequest by default and return it. @@ -95,14 +80,13 @@ public function setEnvironmentService(EnvironmentService $environmentService): H return $this; } - // - /** * send post request to payment server * - * @param $uri string url of the target system - * @param AbstractUnzerResource $resource - * @param string $httpMethod + * @param $uri string|null uri of the target system + * @param ?AbstractUnzerResource $resource + * @param string $httpMethod + * @param string $apiVersion * * @return string * @@ -110,9 +94,10 @@ public function setEnvironmentService(EnvironmentService $environmentService): H * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function send( - $uri = null, - AbstractUnzerResource $resource = null, - $httpMethod = HttpAdapterInterface::REQUEST_GET + ?string $uri = null, + ?AbstractUnzerResource $resource = null, + string $httpMethod = HttpAdapterInterface::REQUEST_GET, + string $apiVersion = Unzer::API_VERSION ): string { if (!$resource instanceof AbstractUnzerResource) { throw new RuntimeException('Transfer object is empty!'); @@ -120,10 +105,10 @@ public function send( $unzerObj = $resource->getUnzerObject(); // perform request - $url = $this->getEnvironmentUrl($uri); + $requestUrl = $this->buildRequestUrl($uri, $apiVersion, $unzerObj); $payload = $resource->jsonSerialize(); - $headers = $this->composerHttpHeaders($unzerObj); - $this->initRequest($url, $payload, $httpMethod, $headers); + $headers = $this->composeHttpHeaders($unzerObj); + $this->initRequest($requestUrl, $payload, $httpMethod, $headers); $httpAdapter = $this->getAdapter(); $response = $httpAdapter->execute(); $responseCode = $httpAdapter->getResponseCode(); @@ -133,7 +118,7 @@ public function send( try { $this->handleErrors($responseCode, $response); } finally { - $this->debugLog($unzerObj, $payload, $headers, $responseCode, $httpMethod, $url, $response); + $this->debugLog($unzerObj, $payload, $headers, $responseCode, $httpMethod, $requestUrl, $response); } return $response; @@ -145,11 +130,11 @@ public function send( * @param string $uri * @param string $payload * @param string $httpMethod - * @param $httpHeaders + * @param array $httpHeaders * * @throws RuntimeException */ - private function initRequest($uri, $payload, $httpMethod, $httpHeaders): void + private function initRequest(string $uri, string $payload, string $httpMethod, array $httpHeaders): void { $httpAdapter = $this->getAdapter(); $httpAdapter->init($uri, $payload, $httpMethod); @@ -166,7 +151,7 @@ private function initRequest($uri, $payload, $httpMethod, $httpHeaders): void * * @throws UnzerApiException */ - private function handleErrors($responseCode, $response): void + private function handleErrors(string $responseCode, ?string $response): void { if ($response === null) { throw new UnzerApiException('The Request returned a null response!'); @@ -199,31 +184,39 @@ private function handleErrors($responseCode, $response): void * @param Unzer $unzerObj * @param string $payload * @param mixed $headers - * @param int $responseCode + * @param string $responseCode * @param string $httpMethod * @param string $url * @param string|null $response */ public function debugLog( - Unzer $unzerObj, - $payload, + Unzer $unzerObj, + string $payload, $headers, - $responseCode, - $httpMethod, + string $responseCode, + string $httpMethod, string $url, - $response + ?string $response ): void { // mask auth string $authHeader = explode(' ', $headers['Authorization']); $authHeader[1] = ValueService::maskValue($authHeader[1]); $headers['Authorization'] = implode(' ', $authHeader); + // log request $unzerObj->debugLog($httpMethod . ': ' . $url); - $writingOperations = [HttpAdapterInterface::REQUEST_POST, HttpAdapterInterface::REQUEST_PUT]; + $writingOperations = [ + HttpAdapterInterface::REQUEST_POST, + HttpAdapterInterface::REQUEST_PUT, + HttpAdapterInterface::REQUEST_PATCH + ]; $unzerObj->debugLog('Headers: ' . json_encode($headers, JSON_UNESCAPED_SLASHES)); if (in_array($httpMethod, $writingOperations, true)) { $unzerObj->debugLog('Request: ' . $payload); } + + // log response + $response = $response ?? ''; $unzerObj->debugLog( 'Response: (' . $responseCode . ') ' . json_encode(json_decode($response, false), JSON_UNESCAPED_SLASHES) @@ -233,25 +226,16 @@ public function debugLog( /** * Returns the environment url. * - * @param $uri + * @param string $uri + * @param string $apiVersion + * @param Unzer $unzer * * @return string */ - private function getEnvironmentUrl($uri): string + private function buildRequestUrl(string $uri, string $apiVersion, Unzer $unzer): string { - $envUrl = []; - switch ($this->getEnvironmentService()->getPapiEnvironment()) { - case EnvironmentService::ENV_VAR_VALUE_STAGING_ENVIRONMENT: - $envUrl[] = self::URL_PART_STAGING_ENVIRONMENT; - break; - case EnvironmentService::ENV_VAR_VALUE_DEVELOPMENT_ENVIRONMENT: - $envUrl[] = self::URL_PART_DEVELOPMENT_ENVIRONMENT; - break; - default: - break; - } - $envUrl[] = Unzer::BASE_URL; - return 'https://' . implode('-', $envUrl) . '/' . Unzer::API_VERSION . $uri; + $envPrefix = $this->getEnvironmentPrefix($unzer); + return "https://" . $envPrefix . Unzer::BASE_URL . "/" . $apiVersion . $uri; } /** @@ -259,9 +243,10 @@ private function getEnvironmentUrl($uri): string * * @return array */ - public function composerHttpHeaders(Unzer $unzer): array + public function composeHttpHeaders(Unzer $unzer): array { $locale = $unzer->getLocale(); + $clientIp = $unzer->getClientIp(); $key = $unzer->getKey(); $httpHeaders = [ 'Authorization' => 'Basic ' . base64_encode($key . ':'), @@ -273,7 +258,48 @@ public function composerHttpHeaders(Unzer $unzer): array if (!empty($locale)) { $httpHeaders['Accept-Language'] = $locale; } + if (!empty($clientIp)) { + $httpHeaders['CLIENTIP'] = $clientIp; + } return $httpHeaders; } + + /** Determine the environment to be used for Api calls and returns the prefix for it. + * Production environment has no prefix. + * + * @param Unzer $unzer + * + * @return string + */ + private function getEnvironmentPrefix(Unzer $unzer): string + { + // Production Environment uses no prefix. + if ($this->isProductionKey($unzer->getKey())) { + return ''; + } + + switch ($this->getEnvironmentService()->getPapiEnvironment()) { + case EnvironmentService::ENV_VAR_VALUE_STAGING_ENVIRONMENT: + $envPrefix = self::URL_PART_STAGING_ENVIRONMENT; + break; + case EnvironmentService::ENV_VAR_VALUE_DEVELOPMENT_ENVIRONMENT: + $envPrefix = self::URL_PART_DEVELOPMENT_ENVIRONMENT; + break; + default: + $envPrefix = self::URL_PART_SANDBOX_ENVIRONMENT; + } + return $envPrefix . '-'; + } + + /** Determine whether key is for production environment. + * + * @param string $privateKey + * + * @return bool + */ + private function isProductionKey(string $privateKey): bool + { + return strpos($privateKey, 'p') === 0; + } } diff --git a/vendor/unzerdev/php-sdk/src/Services/IdService.php b/vendor/unzerdev/php-sdk/src/Services/IdService.php index 1d4e588..aecb23b 100644 --- a/vendor/unzerdev/php-sdk/src/Services/IdService.php +++ b/vendor/unzerdev/php-sdk/src/Services/IdService.php @@ -1,32 +1,17 @@ - * - * @package UnzerSDK\Services */ -namespace UnzerSDK\Services; - -use function count; -use RuntimeException; - class IdService { /** @@ -43,10 +28,10 @@ class IdService * * @throws RuntimeException */ - public static function getResourceIdFromUrl($url, $idString, $onlyLast = false): string + public static function getResourceIdFromUrl(string $url, string $idString, bool $onlyLast = false): string { $matches = []; - $pattern = '/\/([s|p]{1}-' . $idString . '-[a-z\d]+)\/?' . ($onlyLast ? '$':'') . '/'; + $pattern = '/\/([s|p]{1}-' . $idString . '-[a-z\d]+)\/?' . ($onlyLast ? '$' : '') . '/'; preg_match($pattern, $url, $matches); if (count($matches) < 2) { @@ -56,6 +41,36 @@ public static function getResourceIdFromUrl($url, $idString, $onlyLast = false): return $matches[1]; } + /** + * Determine base on the cancellation URL if the transaction refers directly to the payment or not. + * + * @param string $url + * + * @return string + * + * @throws RuntimeException + */ + public static function isPaymentCancellation(string $url): string + { + $pattern = '/\/payments\/[s|p]{1}-pay-[a-z\d]+\/(charges|authorize)\/cancels\/[s|p]{1}-cnl-[a-z\d]+/'; + return preg_match($pattern, $url) === 1; + } + + /** + * Determine base on the chargeback URL if the transaction refers directly to the payment or not. + * + * @param string $url + * + * @return string + * + * @throws RuntimeException + */ + public static function isPaymentChargeback(string $url): string + { + $pattern = '/\/payments\/[s|p]{1}-pay-[a-z\d]+\/(charges|authorize)\/chargebacks\/[s|p]{1}-cbk-[a-z\d]+/'; + return preg_match($pattern, $url) === 1; + } + /** * Behaves like getResourceIdFromUrl but does not throw exception but returns null if the id can not be detected. * @@ -65,7 +80,7 @@ public static function getResourceIdFromUrl($url, $idString, $onlyLast = false): * * @return string|null */ - public static function getResourceIdOrNullFromUrl($url, $idString, $onlyLast = false): ?string + public static function getResourceIdOrNullFromUrl(string $url, string $idString, bool $onlyLast = false): ?string { try { return self::getResourceIdFromUrl($url, $idString, $onlyLast); @@ -79,17 +94,17 @@ public static function getResourceIdOrNullFromUrl($url, $idString, $onlyLast = f * * @return string|null */ - public static function getLastResourceIdFromUrlString($url): ?string + public static function getLastResourceIdFromUrlString(string $url): ?string { return self::getResourceIdOrNullFromUrl($url, '([a-z]{3}|p24)', true); } /** - * @param $typeId + * @param string $typeId * * @return string|null */ - public static function getResourceTypeFromIdString($typeId): ?string + public static function getResourceTypeFromIdString(string $typeId): ?string { $typeIdString = null; diff --git a/vendor/unzerdev/php-sdk/src/Services/PaymentService.php b/vendor/unzerdev/php-sdk/src/Services/PaymentService.php index a30bd37..33eb0bb 100644 --- a/vendor/unzerdev/php-sdk/src/Services/PaymentService.php +++ b/vendor/unzerdev/php-sdk/src/Services/PaymentService.php @@ -1,32 +1,13 @@ - * - * @package UnzerSDK\Services - */ + namespace UnzerSDK\Services; use DateTime; use UnzerSDK\Constants\TransactionTypes; use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; +use UnzerSDK\Resources\PaylaterInstallmentPlans; +use UnzerSDK\Resources\PaymentTypes\PaylaterInstallment; use UnzerSDK\Unzer; use UnzerSDK\Interfaces\PaymentServiceInterface; use UnzerSDK\Resources\AbstractUnzerResource; @@ -44,6 +25,12 @@ use UnzerSDK\Resources\TransactionTypes\Shipment; use RuntimeException; +/** + * This service provides for functionalities concerning payment transactions. + * + * @link https://docs.unzer.com/ + * + */ class PaymentService implements PaymentServiceInterface { /** @var Unzer */ @@ -59,8 +46,6 @@ public function __construct(Unzer $unzer) $this->unzer = $unzer; } - //getUnzer()->getResourceService(); } - // + public function performAuthorization( + Authorization $authorization, + $paymentType, + $customer = null, + Metadata $metadata = null, + Basket $basket = null + ): Authorization { + $payment = $this->createPayment($paymentType); + $paymentType = $payment->getPaymentType(); + $authorization->setSpecialParams($paymentType !== null ? $paymentType->getTransactionParams() : []); + + $payment->setAuthorization($authorization)->setCustomer($customer)->setMetadata($metadata)->setBasket($basket); - // + $this->getResourceService()->createResource($authorization); + return $authorization; + } - // + /** + * {@inheritDoc} + * + * @param Authorization $payment + */ + public function updateAuthorization($payment, Authorization $authorization): Authorization + { + $authorization->setId(null); + $paymentResource = $this->getResourceService()->getPaymentResource($payment); + $authorization->setPayment($paymentResource); + $this->getResourceService()->patchResource($authorization); + return $authorization; + } /** * {@inheritDoc} @@ -118,8 +128,7 @@ public function authorize( $authorization = (new Authorization($amount, $currency, $returnUrl)) ->setOrderId($orderId) ->setInvoiceId($invoiceId) - ->setPaymentReference($referenceText) - ->setSpecialParams($paymentType !== null ? $paymentType->getTransactionParams() : []); + ->setPaymentReference($referenceText); if ($card3ds !== null) { $authorization->setCard3ds($card3ds); } @@ -128,13 +137,40 @@ public function authorize( if ($recurrenceType !== null) { $authorization->setRecurrenceType($recurrenceType); } - $this->getResourceService()->createResource($authorization); + $this->performAuthorization($authorization, $paymentType, $customer, $metadata, $basket); return $authorization; } - // + /** + * {@inheritDoc} + */ + public function performCharge(Charge $charge, $paymentType, $customer = null, Metadata $metadata = null, Basket $basket = null): Charge + { + $payment = $this->createPayment($paymentType); + $paymentType = $payment->getPaymentType(); + + /** @var Charge $charge */ + $charge->setSpecialParams($paymentType->getTransactionParams() ?? []); + $payment->addCharge($charge)->setCustomer($customer)->setMetadata($metadata)->setBasket($basket); + + $this->getResourceService()->createResource($charge); + + return $charge; + } - // + /** + * {@inheritDoc} + * + * @param Charge $payment + */ + public function updateCharge($payment, Charge $charge): Charge + { + $charge->setId(null); + $paymentResource = $this->getResourceService()->getPaymentResource($payment); + $charge->setPayment($paymentResource); + $this->getResourceService()->patchResource($charge); + return $charge; + } /** * {@inheritDoc} @@ -160,8 +196,7 @@ public function charge( $charge = (new Charge($amount, $currency, $returnUrl)) ->setOrderId($orderId) ->setInvoiceId($invoiceId) - ->setPaymentReference($paymentReference) - ->setSpecialParams($paymentType->getTransactionParams() ?? []); + ->setPaymentReference($paymentReference); if ($card3ds !== null) { $charge->setCard3ds($card3ds); } @@ -170,9 +205,8 @@ public function charge( if ($recurrenceType !== null) { $charge->setRecurrenceType($recurrenceType); } - $this->getResourceService()->createResource($charge); - return $charge; + return $this->performCharge($charge, $paymentType, $customer, $metadata, $basket); } /** @@ -184,8 +218,7 @@ public function chargeAuthorization( string $orderId = null, string $invoiceId = null ): Charge { - $paymentResource = $this->getResourceService()->getPaymentResource($payment); - return $this->chargePayment($paymentResource, $amount, $orderId, $invoiceId); + return $this->chargePayment($payment, $amount, $orderId, $invoiceId); } /** @@ -194,41 +227,47 @@ public function chargeAuthorization( public function chargePayment( $payment, float $amount = null, - string $currency = null, string $orderId = null, string $invoiceId = null ): Charge { - $charge = new Charge($amount, $currency); - $charge->setPayment($payment); + $charge = new Charge($amount); + if ($orderId !== null) { $charge->setOrderId($orderId); } if ($invoiceId !== null) { $charge->setInvoiceId($invoiceId); } - $payment->addCharge($charge); - $this->getResourceService()->createResource($charge); - return $charge; + + return $this->performChargeOnPayment($payment, $charge); } - // + /** + * {@inheritDoc} + */ + public function performChargeOnPayment($payment, Charge $charge): Charge + { + $paymentResource = $this->getResourceService()->getPaymentResource($payment); + $paymentResource->addCharge($charge); + $this->getResourceService()->createResource($charge); - // + return $charge; + } /** * {@inheritDoc} */ public function payout( - $amount, - $currency, + float $amount, + string $currency, $paymentType, - $returnUrl, + string $returnUrl, $customer = null, - $orderId = null, - $metadata = null, - $basket = null, - $invoiceId = null, - $referenceText = null + string $orderId = null, + Metadata $metadata = null, + Basket $basket = null, + string $invoiceId = null, + string $referenceText = null ): Payout { $payment = $this->createPayment($paymentType); $payout = (new Payout($amount, $currency, $returnUrl)) @@ -241,10 +280,6 @@ public function payout( return $payout; } - // - - // - /** * {@inheritDoc} */ @@ -257,12 +292,6 @@ public function ship($payment, string $invoiceId = null, string $orderId = null) return $shipment; } - // - - // - - // - /** * {@inheritDoc} */ @@ -287,17 +316,13 @@ public function initPayPageAuthorize( return $this->initPayPage($paypage, TransactionTypes::AUTHORIZATION, $customer, $basket, $metadata); } - // - - // - /** * {@inheritDoc} */ public function fetchInstallmentPlans( - $amount, - $currency, - $effectiveInterest, + float $amount, + string $currency, + float $effectiveInterest, DateTime $orderDate = null ): InstalmentPlans { $ins = (new InstallmentSecured(null, null, null))->setParentResource($this->unzer); @@ -307,9 +332,16 @@ public function fetchInstallmentPlans( return $plans; } - // - - // + /** + * {@inheritDoc} + */ + public function fetchPaylaterInstallmentPlans( + InstallmentPlansQuery $paylaterInstallmentPlansQuery + ): PaylaterInstallmentPlans { + $paylaterInstallment = (new PaylaterInstallment(null, null, null, null))->setParentResource($this->unzer); + $plans = (new PaylaterInstallmentPlans())->setQueryParameter($paylaterInstallmentPlansQuery)->setParentResource($paylaterInstallment); + return $this->unzer->getResourceService()->fetchResource($plans); + } /** * Creates the PayPage for the requested transaction method. @@ -331,14 +363,14 @@ public function fetchInstallmentPlans( * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ private function initPayPage( - Paypage $paypage, - $action, + Paypage $paypage, + string $action, Customer $customer = null, - Basket $basket = null, + Basket $basket = null, Metadata $metadata = null ): Paypage { $paypage->setAction($action)->setParentResource($this->unzer); - $payment = $this->createPayment($paypage)->setBasket($basket)->setCustomer($customer)->setMetadata($metadata); + $payment = $this->createPayment($paypage)->setBasket($basket)->setCustomer($customer)->setMetadata($metadata)->setPayPage($paypage); $this->getResourceService()->createResource($paypage->setPayment($payment)); return $paypage; } @@ -357,6 +389,4 @@ private function createPayment($paymentType): AbstractUnzerResource { return (new Payment($this->unzer))->setPaymentType($paymentType); } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Services/ResourceNameService.php b/vendor/unzerdev/php-sdk/src/Services/ResourceNameService.php index cfdbf4c..599b108 100644 --- a/vendor/unzerdev/php-sdk/src/Services/ResourceNameService.php +++ b/vendor/unzerdev/php-sdk/src/Services/ResourceNameService.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Services */ -namespace UnzerSDK\Services; - class ResourceNameService { /** @@ -33,7 +17,7 @@ class ResourceNameService * * @return string */ - public static function getClassShortName($classString): string + public static function getClassShortName(string $classString): string { $classNameParts = explode('\\', $classString); return end($classNameParts); @@ -46,7 +30,7 @@ public static function getClassShortName($classString): string * * @return string */ - public static function getClassShortNameKebapCase($classString): string + public static function getClassShortNameKebapCase(string $classString): string { return self::toKebapCase(self::getClassShortName($classString)); } @@ -58,7 +42,7 @@ public static function getClassShortNameKebapCase($classString): string * * @return string */ - private static function toKebapCase($str): string + private static function toKebapCase(string $str): string { $kebapCaseString = preg_replace_callback( '/([A-Z][a-z])+/', diff --git a/vendor/unzerdev/php-sdk/src/Services/ResourceService.php b/vendor/unzerdev/php-sdk/src/Services/ResourceService.php index 0feacbc..aac29e3 100644 --- a/vendor/unzerdev/php-sdk/src/Services/ResourceService.php +++ b/vendor/unzerdev/php-sdk/src/Services/ResourceService.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\Services - */ + namespace UnzerSDK\Services; use DateTime; @@ -30,7 +8,17 @@ use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Constants\IdStrings; use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\Resources\Config; use UnzerSDK\Resources\PaymentTypes\Applepay; +use UnzerSDK\Resources\PaymentTypes\Googlepay; +use UnzerSDK\Resources\PaymentTypes\Klarna; +use UnzerSDK\Resources\PaymentTypes\PaylaterDirectDebit; +use UnzerSDK\Resources\PaymentTypes\PaylaterInstallment; +use UnzerSDK\Resources\PaymentTypes\Paypage; +use UnzerSDK\Resources\PaymentTypes\PayU; +use UnzerSDK\Resources\PaymentTypes\PostFinanceCard; +use UnzerSDK\Resources\PaymentTypes\PostFinanceEfinance; +use UnzerSDK\Resources\TransactionTypes\Chargeback; use UnzerSDK\Unzer; use UnzerSDK\Interfaces\ResourceServiceInterface; use UnzerSDK\Resources\AbstractUnzerResource; @@ -49,6 +37,7 @@ use UnzerSDK\Resources\PaymentTypes\Ideal; use UnzerSDK\Resources\PaymentTypes\Invoice; use UnzerSDK\Resources\PaymentTypes\InvoiceSecured; +use UnzerSDK\Resources\PaymentTypes\PaylaterInvoice; use UnzerSDK\Resources\PaymentTypes\Paypal; use UnzerSDK\Resources\PaymentTypes\PIS; use UnzerSDK\Resources\PaymentTypes\Prepayment; @@ -66,9 +55,16 @@ use UnzerSDK\Traits\CanRecur; use RuntimeException; use stdClass; + use function in_array; use function is_string; +/** + * This service provides for all methods to manage resources with the api. + * + * @link https://docs.unzer.com/ + * + */ class ResourceService implements ResourceServiceInterface { /** @var Unzer */ @@ -84,8 +80,6 @@ public function __construct(Unzer $unzer) $this->unzer = $unzer; } - // - - // - /** * Send request to API. * * @param AbstractUnzerResource $resource * @param string $httpMethod + * @param string $apiVersion * * @return stdClass * @@ -120,11 +111,12 @@ public function setUnzer(Unzer $unzer): ResourceServiceInterface */ public function send( AbstractUnzerResource $resource, - $httpMethod = HttpAdapterInterface::REQUEST_GET + string $httpMethod = HttpAdapterInterface::REQUEST_GET, + string $apiVersion = Unzer::API_VERSION ): stdClass { $appendId = $httpMethod !== HttpAdapterInterface::REQUEST_POST; $uri = $resource->getUri($appendId, $httpMethod); - $responseJson = $resource->getUnzerObject()->getHttpService()->send($uri, $resource, $httpMethod); + $responseJson = $resource->getUnzerObject()->getHttpService()->send($uri, $resource, $httpMethod, $apiVersion); return json_decode($responseJson, false); } @@ -160,6 +152,10 @@ public function fetchResourceByUrl($url) $unzer = $this->unzer; $resourceId = IdService::getLastResourceIdFromUrlString($url); + if (empty($resourceId)) { + return null; + } + $resourceType = IdService::getResourceTypeFromIdString($resourceId); switch (true) { case $resourceType === IdStrings::AUTHORIZE: @@ -180,6 +176,15 @@ public function fetchResourceByUrl($url) case $resourceType === IdStrings::CANCEL: $paymentId = IdService::getResourceIdFromUrl($url, IdStrings::PAYMENT); $chargeId = IdService::getResourceIdOrNullFromUrl($url, IdStrings::CHARGE); + if (IdService::isPaymentCancellation($url)) { + $isRefund = preg_match('/charge/', $url) === 1; + if ($isRefund) { + $resource = $unzer->fetchPaymentRefund($paymentId, $resourceId); + break; + } + $resource = $unzer->fetchPaymentReversal($paymentId, $resourceId); + break; + } if ($chargeId !== null) { $resource = $unzer->fetchRefundById($paymentId, $chargeId, $resourceId); break; @@ -211,10 +216,6 @@ public function fetchResourceByUrl($url) return $resource; } - // - - // - /** * Create the resource on the api. * @@ -228,7 +229,7 @@ public function fetchResourceByUrl($url) public function createResource(AbstractUnzerResource $resource): AbstractUnzerResource { $method = HttpAdapterInterface::REQUEST_POST; - $response = $this->send($resource, $method); + $response = $this->send($resource, $method, $resource->getApiVersion()); $isError = isset($response->isError) && $response->isError; if ($isError) { @@ -257,7 +258,32 @@ public function createResource(AbstractUnzerResource $resource): AbstractUnzerRe public function updateResource(AbstractUnzerResource $resource): AbstractUnzerResource { $method = HttpAdapterInterface::REQUEST_PUT; - $response = $this->send($resource, $method); + $response = $this->send($resource, $method, $resource->getApiVersion()); + + $isError = isset($response->isError) && $response->isError; + if ($isError) { + return $resource; + } + + $resource->handleResponse($response, $method); + return $resource; + } + + /** + * Update the resource on the api with PATCH method. + * + * @param AbstractUnzerResource $resource + * + * @return AbstractUnzerResource + * + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * @throws Exception + */ + public function patchResource(AbstractUnzerResource $resource): AbstractUnzerResource + { + $method = HttpAdapterInterface::REQUEST_PATCH; + $response = $this->send($resource, $method, $resource->getApiVersion()); $isError = isset($response->isError) && $response->isError; if ($isError) { @@ -278,7 +304,7 @@ public function updateResource(AbstractUnzerResource $resource): AbstractUnzerRe */ public function deleteResource(AbstractUnzerResource &$resource): ?AbstractUnzerResource { - $response = $this->send($resource, HttpAdapterInterface::REQUEST_DELETE); + $response = $this->send($resource, HttpAdapterInterface::REQUEST_DELETE, $resource->getApiVersion()); $isError = isset($response->isError) && $response->isError; if ($isError) { @@ -294,7 +320,8 @@ public function deleteResource(AbstractUnzerResource &$resource): ?AbstractUnzer /** * Updates the given local resource object (id must be set) * - * @param AbstractUnzerResource $resource The local resource object to update. + * @param AbstractUnzerResource $resource The local resource object to update. + * @param string $apiVersion * * @return AbstractUnzerResource The updated resource object. * @@ -302,19 +329,15 @@ public function deleteResource(AbstractUnzerResource &$resource): ?AbstractUnzer * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. * @throws Exception */ - public function fetchResource(AbstractUnzerResource $resource): AbstractUnzerResource + public function fetchResource(AbstractUnzerResource $resource, string $apiVersion = Unzer::API_VERSION): AbstractUnzerResource { $method = HttpAdapterInterface::REQUEST_GET; - $response = $this->send($resource, $method); + $response = $this->send($resource, $method, $apiVersion); $resource->setFetchedAt(new DateTime('now')); $resource->handleResponse($response, $method); return $resource; } - // - - // - /** * Fetch an Payout object by its paymentId. * Payout Ids are not global but specific to the payment. @@ -336,14 +359,10 @@ public function fetchPayout($payment): Payout return $payout; } - // - - // - /** * {@inheritDoc} */ - public function activateRecurringPayment($paymentType, $returnUrl, string $recurrenceType = null): Recurring + public function activateRecurringPayment($paymentType, string $returnUrl, string $recurrenceType = null): Recurring { $paymentTypeObject = $paymentType; if (is_string($paymentType)) { @@ -364,10 +383,6 @@ public function activateRecurringPayment($paymentType, $returnUrl, string $recur throw new RuntimeException('Recurring is not available for the given payment type.'); } - // - - // - /** * Fetches the payment object if the id is given. * Else it just returns the given payment argument as-is. @@ -389,6 +404,21 @@ public function getPaymentResource($payment): Payment return $paymentObject; } + /** + * @inheritDoc + */ + public function fetchPayPage($payPage): Paypage + { + $payPageObject = $payPage; + if (is_string($payPage)) { + $payPageObject = new payPage(0, '', ''); + $payPageObject->setId($payPage); + } + + $this->fetchResource($payPageObject->setParentResource($this->unzer)); + return $payPageObject; + } + /** * {@inheritDoc} */ @@ -407,31 +437,23 @@ public function fetchPayment($payment): Payment /** * {@inheritDoc} */ - public function fetchPaymentByOrderId($orderId): Payment + public function fetchPaymentByOrderId(string $orderId): Payment { $paymentObject = (new Payment($this->unzer))->setOrderId($orderId); $this->fetchResource($paymentObject); return $paymentObject; } - // - - // - /** * {@inheritDoc} */ - public function fetchKeypair($detailed = false): Keypair + public function fetchKeypair(bool $detailed = false): Keypair { $keyPair = (new Keypair())->setParentResource($this->unzer)->setDetailed($detailed); $this->fetchResource($keyPair); return $keyPair; } - // - - // - /** * {@inheritDoc} */ @@ -456,10 +478,6 @@ public function fetchMetadata($metadata): Metadata return $metadataObject; } - // - - // - /** * {@inheritDoc} */ @@ -481,7 +499,14 @@ public function fetchBasket($basket): Basket } $basketObj->setParentResource($this->unzer); - $this->fetchResource($basketObj); + try { + $this->fetchResource($basketObj, 'v2'); + } catch (UnzerApiException $exception) { + if ($exception->getCode() !== ApiResponseCodes::API_ERROR_BASKET_NOT_FOUND) { + throw $exception; + } + $this->fetchResource($basketObj); + } return $basketObj; } @@ -495,10 +520,6 @@ public function updateBasket(Basket $basket): Basket return $basket; } - // - - // - /** * {@inheritDoc} */ @@ -512,72 +533,9 @@ public function createPaymentType(BasePaymentType $paymentType): BasePaymentType /** * {@inheritDoc} */ - public function fetchPaymentType($typeId): BasePaymentType + public function fetchPaymentType(string $typeId): BasePaymentType { - $resourceType = IdService::getResourceTypeFromIdString($typeId); - switch ($resourceType) { - case IdStrings::ALIPAY: - $paymentType = new Alipay(); - break; - case IdStrings::APPLEPAY: - $paymentType = new Applepay(null, null, null, null); - break; - case IdStrings::BANCONTACT: - $paymentType = new Bancontact(); - break; - case IdStrings::CARD: - $paymentType = new Card(null, null); - break; - case IdStrings::EPS: - $paymentType = new EPS(); - break; - case IdStrings::GIROPAY: - $paymentType = new Giropay(); - break; - case IdStrings::HIRE_PURCHASE_DIRECT_DEBIT: - case IdStrings::INSTALLMENT_SECURED: - $paymentType = new InstallmentSecured(); - break; - case IdStrings::IDEAL: - $paymentType = new Ideal(); - break; - case IdStrings::INVOICE: - $paymentType = new Invoice(); - break; - case IdStrings::INVOICE_FACTORING: - case IdStrings::INVOICE_GUARANTEED: - case IdStrings::INVOICE_SECURED: - $paymentType = new InvoiceSecured(); - break; - case IdStrings::PAYPAL: - $paymentType = new Paypal(); - break; - case IdStrings::PIS: - $paymentType = new PIS(); - break; - case IdStrings::PREPAYMENT: - $paymentType = new Prepayment(); - break; - case IdStrings::PRZELEWY24: - $paymentType = new Przelewy24(); - break; - case IdStrings::SEPA_DIRECT_DEBIT: - $paymentType = new SepaDirectDebit(null); - break; - case IdStrings::SEPA_DIRECT_DEBIT_GUARANTEED: - case IdStrings::SEPA_DIRECT_DEBIT_SECURED: - $paymentType = new SepaDirectDebitSecured(null); - break; - case IdStrings::SOFORT: - $paymentType = new Sofort(); - break; - case IdStrings::WECHATPAY: - $paymentType = new Wechatpay(); - break; - default: - throw new RuntimeException('Invalid payment type!'); - break; - } + $paymentType = self::getTypeInstanceFromIdString($typeId); /** @var BasePaymentType $paymentType */ $paymentType = $paymentType->setParentResource($this->unzer)->setId($typeId); @@ -595,10 +553,6 @@ public function updatePaymentType(BasePaymentType $paymentType): BasePaymentType return $returnPaymentType; } - // - - // - /** * {@inheritDoc} */ @@ -649,7 +603,7 @@ public function fetchCustomer($customer): Customer /** * {@inheritDoc} */ - public function fetchCustomerByExtCustomerId($customerId): Customer + public function fetchCustomerByExtCustomerId(string $customerId): Customer { $customerObject = (new Customer())->setCustomerId($customerId); $this->fetchResource($customerObject->setParentResource($this->unzer)); @@ -679,10 +633,6 @@ public function deleteCustomer($customer): void $this->deleteResource($customerObject); } - // - - // - /** * {@inheritDoc} */ @@ -700,9 +650,6 @@ public function fetchAuthorization($payment): Authorization return $authorize; } - // - - // public function fetchCharge(Charge $charge): Charge { $this->fetchResource($charge); @@ -712,7 +659,7 @@ public function fetchCharge(Charge $charge): Charge /** * {@inheritDoc} */ - public function fetchChargeById($payment, $chargeId): Charge + public function fetchChargeById($payment, string $chargeId): Charge { $paymentObject = $this->fetchPayment($payment); $charge = $paymentObject->getCharge($chargeId, true); @@ -725,14 +672,35 @@ public function fetchChargeById($payment, $chargeId): Charge return $charge; } - // + /** + * {@inheritDoc} + */ + public function fetchChargeback(Chargeback $chargeback): Chargeback + { + $this->fetchResource($chargeback); + return $chargeback; + } + + /** + * {@inheritDoc} + */ + public function fetchChargebackById(string $paymentId, string $chargebackId, ?string $chargeId): Chargeback + { + $paymentObject = $this->fetchPayment($paymentId); + $chargeback = $paymentObject->getChargeback($chargebackId, $chargeId, true); + + if (!$chargeback instanceof Chargeback) { + throw new RuntimeException('The chargeback object could not be found.'); + } - // + $this->fetchResource($chargeback); + return $chargeback; + } /** * {@inheritDoc} */ - public function fetchReversalByAuthorization($authorization, $cancellationId): Cancellation + public function fetchReversalByAuthorization(Authorization $authorization, string $cancellationId): Cancellation { $this->fetchResource($authorization); return $authorization->getCancellation($cancellationId); @@ -741,7 +709,7 @@ public function fetchReversalByAuthorization($authorization, $cancellationId): C /** * {@inheritDoc} */ - public function fetchReversal($payment, $cancellationId): Cancellation + public function fetchReversal($payment, string $cancellationId): Cancellation { /** @var Authorization $authorization */ $authorization = $this->fetchPayment($payment)->getAuthorization(); @@ -751,7 +719,7 @@ public function fetchReversal($payment, $cancellationId): Cancellation /** * {@inheritDoc} */ - public function fetchRefundById($payment, $chargeId, $cancellationId): Cancellation + public function fetchRefundById($payment, string $chargeId, string $cancellationId): Cancellation { /** @var Charge $charge */ $charge = $this->fetchChargeById($payment, $chargeId); @@ -761,25 +729,166 @@ public function fetchRefundById($payment, $chargeId, $cancellationId): Cancellat /** * {@inheritDoc} */ - public function fetchRefund(Charge $charge, $cancellationId): Cancellation + public function fetchRefund(Charge $charge, string $cancellationId): Cancellation { /** @var Cancellation $cancel */ $cancel = $this->fetchResource($charge->getCancellation($cancellationId, true)); return $cancel; } - // + /** + * {@inheritDoc} + */ + public function fetchPaymentRefund($payment, string $cancellationId): Cancellation + { + $charge = new Charge(); + $paymentResource = $this->getPaymentResource($payment); + + $charge->setParentResource($paymentResource); + $cancel = (new Cancellation()) + ->setId($cancellationId) + ->setPayment($paymentResource) + ->setParentResource($charge); + return $this->fetchResource($cancel); + } + + /** + * {@inheritDoc} + */ + public function fetchPaymentReversal($payment, string $cancellationId): Cancellation + { + $authorization = new Authorization(); + $paymentResource = $this->getPaymentResource($payment); - // + $authorization->setParentResource($paymentResource); + $cancel = (new Cancellation()) + ->setId($cancellationId) + ->setPayment($paymentResource) + ->setParentResource($authorization); + return $this->fetchResource($cancel); + } /** * {@inheritDoc} */ - public function fetchShipment($payment, $shipmentId): Shipment + public function fetchShipment($payment, string $shipmentId): Shipment { $paymentObject = $this->fetchPayment($payment); return $paymentObject->getShipment($shipmentId); } - // + /** + * {@inheritDoc} + * + * @param Config|null $config + */ + public function fetchConfig(BasePaymentType $paymentType, ?Config $config = null): Config + { + $paymentType->setParentResource($this->unzer); + + $configObject = $config ?? new Config(); + $configObject->setParentResource($paymentType); + + return $this->fetchResource($configObject); + } + + /** + * Creates a payment type instance from a typeId string. + * + * @param $typeId + * + * @return BasePaymentType + */ + public static function getTypeInstanceFromIdString($typeId): BasePaymentType + { + $resourceType = IdService::getResourceTypeFromIdString($typeId); + switch ($resourceType) { + case IdStrings::ALIPAY: + $paymentType = new Alipay(); + break; + case IdStrings::APPLEPAY: + $paymentType = new Applepay(null, null, null, null); + break; + case IdStrings::BANCONTACT: + $paymentType = new Bancontact(); + break; + case IdStrings::CARD: + $paymentType = new Card(null, null); + break; + case IdStrings::EPS: + $paymentType = new EPS(); + break; + case IdStrings::GIROPAY: + $paymentType = new Giropay(); + break; + case IdStrings::GOOGLE_PAY: + $paymentType = new Googlepay(); + break; + case IdStrings::HIRE_PURCHASE_DIRECT_DEBIT: + case IdStrings::INSTALLMENT_SECURED: + $paymentType = new InstallmentSecured(); + break; + case IdStrings::IDEAL: + $paymentType = new Ideal(); + break; + case IdStrings::INVOICE: + $paymentType = new Invoice(); + break; + case IdStrings::INVOICE_FACTORING: + case IdStrings::INVOICE_GUARANTEED: + case IdStrings::INVOICE_SECURED: + $paymentType = new InvoiceSecured(); + break; + case IdStrings::KLARNA: + $paymentType = new Klarna(); + break; + case IdStrings::PAYPAL: + $paymentType = new Paypal(); + break; + case IdStrings::PAYLATER_DIRECT_DEBIT: + $paymentType = new PaylaterDirectDebit(); + break; + case IdStrings::PAYLATER_INSTALLMENT: + $paymentType = new PaylaterInstallment(); + break; + case IdStrings::PAYLATER_INVOICE: + $paymentType = new PaylaterInvoice(); + break; + case IdStrings::PAYU: + $paymentType = new PayU(); + break; + case IdStrings::PIS: + $paymentType = new PIS(); + break; + case IdStrings::POST_FINANCE_CARD: + $paymentType = new PostFinanceCard(); + break; + case IdStrings::POST_FINANCE_EFINANCE: + $paymentType = new PostFinanceEfinance(); + break; + case IdStrings::PREPAYMENT: + $paymentType = new Prepayment(); + break; + case IdStrings::PRZELEWY24: + $paymentType = new Przelewy24(); + break; + case IdStrings::SEPA_DIRECT_DEBIT: + $paymentType = new SepaDirectDebit(null); + break; + case IdStrings::SEPA_DIRECT_DEBIT_GUARANTEED: + case IdStrings::SEPA_DIRECT_DEBIT_SECURED: + $paymentType = new SepaDirectDebitSecured(null); + break; + case IdStrings::SOFORT: + $paymentType = new Sofort(); + break; + case IdStrings::WECHATPAY: + $paymentType = new Wechatpay(); + break; + default: + throw new RuntimeException('Invalid payment type!'); + break; + } + return $paymentType; + } } diff --git a/vendor/unzerdev/php-sdk/src/Services/ValueService.php b/vendor/unzerdev/php-sdk/src/Services/ValueService.php index 539b0aa..0535279 100644 --- a/vendor/unzerdev/php-sdk/src/Services/ValueService.php +++ b/vendor/unzerdev/php-sdk/src/Services/ValueService.php @@ -1,32 +1,16 @@ - * - * @package UnzerSDK\Services */ -namespace UnzerSDK\Services; - -use function is_float; -use function strlen; - class ValueService { /** @@ -45,12 +29,12 @@ public static function limitFloats($value) /** * Mask a value. * - * @param $value + * @param $value * @param string $maskSymbol * * @return string */ - public static function maskValue($value, $maskSymbol = '*'): string + public static function maskValue($value, string $maskSymbol = '*'): string { return substr($value, 0, 6) . str_repeat($maskSymbol, strlen($value) - 10) . substr($value, -4); } diff --git a/vendor/unzerdev/php-sdk/src/Services/WebhookService.php b/vendor/unzerdev/php-sdk/src/Services/WebhookService.php index 16e3745..c8117d1 100644 --- a/vendor/unzerdev/php-sdk/src/Services/WebhookService.php +++ b/vendor/unzerdev/php-sdk/src/Services/WebhookService.php @@ -1,27 +1,5 @@ - * - * @package UnzerSDK\Services - */ + namespace UnzerSDK\Services; use UnzerSDK\Unzer; @@ -30,9 +8,16 @@ use UnzerSDK\Resources\AbstractUnzerResource; use UnzerSDK\Resources\Webhook; use UnzerSDK\Resources\Webhooks; -use function is_string; use RuntimeException; +use function is_string; + +/** + * This service provides methods to manage webhooks/events. + * + * @link https://docs.unzer.com/ + * + */ class WebhookService implements WebhookServiceInterface { /** @var Unzer $unzer */ @@ -52,8 +37,6 @@ public function __construct(Unzer $unzer) $this->resourceService = $unzer->getResourceService(); } - // - /** * @return Unzer */ @@ -92,10 +75,6 @@ public function setResourceService(ResourceServiceInterface $resourceService): W return $this; } - // - - // - /** * {@inheritDoc} */ @@ -126,7 +105,7 @@ public function fetchWebhook($webhook): Webhook /** * {@inheritDoc} */ - public function updateWebhook($webhook): Webhook + public function updateWebhook(Webhook $webhook): Webhook { $webhook->setParentResource($this->unzer); $this->resourceService->updateResource($webhook); @@ -147,10 +126,6 @@ public function deleteWebhook($webhook) return $this->resourceService->deleteResource($webhookObject); } - // - - // - /** * {@inheritDoc} */ @@ -187,14 +162,10 @@ public function registerMultipleWebhooks(string $url, array $events): array return $webhooks->getWebhookList(); } - // - - // - /** * {@inheritDoc} */ - public function fetchResourceFromEvent($eventJson = null): AbstractUnzerResource + public function fetchResourceFromEvent(string $eventJson = null): AbstractUnzerResource { $resourceObject = null; $eventData = json_decode($eventJson ?? $this->readInputStream(), false); @@ -221,6 +192,4 @@ public function readInputStream() { return file_get_contents('php://input'); } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/CanAuthorize.php b/vendor/unzerdev/php-sdk/src/Traits/CanAuthorize.php index aaf3327..c037f19 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/CanAuthorize.php +++ b/vendor/unzerdev/php-sdk/src/Traits/CanAuthorize.php @@ -2,26 +2,10 @@ /** * This trait makes a payment type authorizable. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -36,7 +20,7 @@ trait CanAuthorize { /** * Authorize an amount with the given currency. - * Throws UnzerApiException if the transaction could not be performed (e. g. increased risk etc.). + * Throws UnzerApiException if the transaction could not be performed (e.g. increased risk etc.). * * @param float $amount * @param string $currency diff --git a/vendor/unzerdev/php-sdk/src/Traits/CanAuthorizeWithCustomer.php b/vendor/unzerdev/php-sdk/src/Traits/CanAuthorizeWithCustomer.php index 3fc9e25..7f88965 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/CanAuthorizeWithCustomer.php +++ b/vendor/unzerdev/php-sdk/src/Traits/CanAuthorizeWithCustomer.php @@ -2,26 +2,10 @@ /** * This trait makes a payment type authorizable with mandatory customer. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -36,11 +20,11 @@ trait CanAuthorizeWithCustomer { /** * Authorize an amount with the given currency. - * Throws UnzerApiException if the transaction could not be performed (e. g. increased risk etc.). + * Throws UnzerApiException if the transaction could not be performed (e.g. increased risk etc.). * - * @param $amount - * @param $currency - * @param $returnUrl + * @param $amount + * @param $currency + * @param $returnUrl * @param Customer|string $customer * @param string|null $orderId * @param Metadata|null $metadata diff --git a/vendor/unzerdev/php-sdk/src/Traits/CanDirectCharge.php b/vendor/unzerdev/php-sdk/src/Traits/CanDirectCharge.php index 77bb1cb..cffaefa 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/CanDirectCharge.php +++ b/vendor/unzerdev/php-sdk/src/Traits/CanDirectCharge.php @@ -2,26 +2,10 @@ /** * This trait makes a payment type chargeable. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -36,11 +20,11 @@ trait CanDirectCharge { /** * Charge an amount with the given currency. - * Throws UnzerApiException if the transaction could not be performed (e. g. increased risk etc.). + * Throws UnzerApiException if the transaction could not be performed (e.g. increased risk etc.). * - * @param $amount - * @param $currency - * @param $returnUrl + * @param $amount + * @param $currency + * @param $returnUrl * @param Customer|string|null $customer * @param string|null $orderId * @param Metadata|string|null $metadata diff --git a/vendor/unzerdev/php-sdk/src/Traits/CanDirectChargeWithCustomer.php b/vendor/unzerdev/php-sdk/src/Traits/CanDirectChargeWithCustomer.php index 1c7325b..d2314ef 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/CanDirectChargeWithCustomer.php +++ b/vendor/unzerdev/php-sdk/src/Traits/CanDirectChargeWithCustomer.php @@ -2,26 +2,10 @@ /** * This trait makes a payment type chargeable with mandatory customer. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -36,7 +20,7 @@ trait CanDirectChargeWithCustomer { /** * Charge an amount with the given currency. - * Throws UnzerApiException if the transaction could not be performed (e. g. increased risk etc.). + * Throws UnzerApiException if the transaction could not be performed (e.g. increased risk etc.). * * @param float $amount * @param string $currency diff --git a/vendor/unzerdev/php-sdk/src/Traits/CanPayout.php b/vendor/unzerdev/php-sdk/src/Traits/CanPayout.php index 8d49618..4458e68 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/CanPayout.php +++ b/vendor/unzerdev/php-sdk/src/Traits/CanPayout.php @@ -2,26 +2,10 @@ /** * Adds payout capability to payment types. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -36,7 +20,7 @@ trait CanPayout { /** * Credit the given amount with the given currency to this payment type. - * Throws UnzerApiException if the transaction could not be performed (e. g. increased risk etc.). + * Throws UnzerApiException if the transaction could not be performed (e.g. increased risk etc.). * * @param float $amount * @param string $currency @@ -56,15 +40,15 @@ trait CanPayout * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function payout( - $amount, - $currency, - $returnUrl, + float $amount, + string $currency, + string $returnUrl, $customer = null, - $orderId = null, + string $orderId = null, $metadata = null, - $basket = null, - $invoiceId = null, - $paymentReference = null + Basket $basket = null, + string $invoiceId = null, + string $paymentReference = null ): Payout { if ($this instanceof UnzerParentInterface) { return $this->getUnzerObject()->payout( diff --git a/vendor/unzerdev/php-sdk/src/Traits/CanPayoutWithCustomer.php b/vendor/unzerdev/php-sdk/src/Traits/CanPayoutWithCustomer.php index 4f6c516..389a4bf 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/CanPayoutWithCustomer.php +++ b/vendor/unzerdev/php-sdk/src/Traits/CanPayoutWithCustomer.php @@ -2,26 +2,10 @@ /** * Adds payout capability to payment types. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -36,7 +20,7 @@ trait CanPayoutWithCustomer { /** * Credit the given amount with the given currency to this payment type. - * Throws UnzerApiException if the transaction could not be performed (e. g. increased risk etc.). + * Throws UnzerApiException if the transaction could not be performed (e.g. increased risk etc.). * * @param float $amount * @param string $currency @@ -54,13 +38,13 @@ trait CanPayoutWithCustomer * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. */ public function payout( - $amount, - $currency, - $returnUrl, + float $amount, + string $currency, + string $returnUrl, $customer, - $orderId = null, + string $orderId = null, $metadata = null, - $basket = null + Basket $basket = null ): Payout { if ($this instanceof UnzerParentInterface) { return $this->getUnzerObject()->payout( diff --git a/vendor/unzerdev/php-sdk/src/Traits/CanRecur.php b/vendor/unzerdev/php-sdk/src/Traits/CanRecur.php index a2ba1f1..23e05fb 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/CanRecur.php +++ b/vendor/unzerdev/php-sdk/src/Traits/CanRecur.php @@ -2,26 +2,10 @@ /** * This trait allows a payment type to activate recurring payments. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -44,6 +28,10 @@ trait CanRecur * * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * + * @deprecated since 1.3.0.0 Please set the recurrence type in your Charge/Authorize object using `setRecurrenceType` + * before performing the transaction request. + * */ public function activateRecurring($returnUrl, $recurrenceType = null): Recurring { @@ -53,8 +41,6 @@ public function activateRecurring($returnUrl, $recurrenceType = null): Recurring throw new RuntimeException('Error: Recurring can not be enabled on this type.'); } - // - /** * @return bool */ @@ -73,6 +59,4 @@ protected function setRecurring(bool $active): self $this->recurring = $active; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasAccountInformation.php b/vendor/unzerdev/php-sdk/src/Traits/HasAccountInformation.php new file mode 100644 index 0000000..536daa4 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Traits/HasAccountInformation.php @@ -0,0 +1,86 @@ +iban; + } + + /** + * @param string|null $iban + * + * @return self + */ + protected function setIban(?string $iban): self + { + $this->iban = $iban; + return $this; + } + + /** + * Returns the BIC of the account the customer needs to transfer the amount to. + * E.g. invoice, prepayment, etc. + * + * @return string|null + */ + public function getBic(): ?string + { + return $this->bic; + } + + /** + * @param string|null $bic + * + * @return self + */ + protected function setBic(?string $bic): self + { + $this->bic = $bic; + return $this; + } + + /** + * Returns the holder of the account the customer needs to transfer the amount to. + * E.g. invoice, prepayment, etc. + * + * @return string|null + */ + public function getHolder(): ?string + { + return $this->holder; + } + + /** + * @param string|null $holder + * + * @return self + */ + protected function setHolder(?string $holder): self + { + $this->holder = $holder; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasAdditionalTransactionData.php b/vendor/unzerdev/php-sdk/src/Traits/HasAdditionalTransactionData.php index 659c473..3dcd4b2 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasAdditionalTransactionData.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasAdditionalTransactionData.php @@ -1,36 +1,25 @@ + * @link https://docs.unzer.com/ * - * @package UnzerSDK\Traits */ namespace UnzerSDK\Traits; use stdClass; +use UnzerSDK\Constants\AdditionalTransactionDataKeys; +use UnzerSDK\Resources\EmbeddedResources\CardTransactionData; +use UnzerSDK\Resources\EmbeddedResources\RiskData; +use UnzerSDK\Resources\EmbeddedResources\ShippingData; +use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\TransactionTypes\AbstractTransactionType; +use UnzerSDK\Services\ResourceService; trait HasAdditionalTransactionData { - /** @var stdClass $additionalTransactionData */ protected $additionalTransactionData; @@ -69,4 +58,167 @@ public function addAdditionalTransactionData($name, $value): self $this->additionalTransactionData->$name = $value; return $this; } + + /** + * Sets the shipping value inside the additional transaction Data array. + * + * @param ShippingData|null $shippingData + * + * @return $this + */ + public function setShipping(?ShippingData $shippingData): self + { + $this->addAdditionalTransactionData('shipping', $shippingData); + return $this; + } + + /** + * Gets the shipping value from the additional transaction Data array. + * + * @return ShippingData|null Returns null if shipping is empty or does not contain a ShippingObject. + */ + public function getShipping(): ?ShippingData + { + $shipping = $this->getAdditionalTransactionData()->shipping ?? null; + return $shipping instanceof ShippingData ? $shipping : null; + } + + /** + * Sets the riskData value inside the additional transaction Data array. + * + * @param RiskData|null $riskData + * + * @return $this + */ + public function setRiskData(?RiskData $riskData): self + { + $this->addAdditionalTransactionData('riskData', $riskData); + return $this; + } + + /** + * Gets the riskData value from the additional transaction Data array. + * + * @return RiskData|null + */ + public function getRiskData(): ?RiskData + { + $riskData = $this->getAdditionalTransactionData()->riskData ?? null; + return $riskData instanceof RiskData ? $riskData : null; + } + + /** + * Sets the privacyPolicyUrl value inside the additional transaction Data array. + * + * @param string|null $privacyPolicyUrl + * + * @return $this + */ + public function setPrivacyPolicyUrl(?string $privacyPolicyUrl): self + { + $this->addAdditionalTransactionData(AdditionalTransactionDataKeys::PRIVACY_POLICY_URL, $privacyPolicyUrl); + return $this; + } + + /** + * Gets the privacyPolicyUrl value from the additional transaction Data array. + * + * @return string|null + */ + public function getPrivacyPolicyUrl(): ?string + { + $propertyKey = AdditionalTransactionDataKeys::PRIVACY_POLICY_URL; + return $this->getAdditionalTransactionData()->$propertyKey ?? null; + } + + /** + * Sets the termsAndConditionUrl value inside the additional transaction Data array. + * + * @param string|null $termsAndConditionUrl + * + * @return $this + */ + public function setTermsAndConditionUrl(?string $termsAndConditionUrl): self + { + $this->addAdditionalTransactionData(AdditionalTransactionDataKeys::TERMS_AND_CONDITION_URL, $termsAndConditionUrl); + return $this; + } + + /** + * Gets the termsAndConditionUrl value from the additional transaction Data array. + * + * @return string|null + */ + public function getTermsAndConditionUrl(): ?string + { + $propertyKey = AdditionalTransactionDataKeys::TERMS_AND_CONDITION_URL; + return $this->getAdditionalTransactionData()->$propertyKey ?? null; + } + + /** + * Set checkout type based on the given payment Type. + * + * @param string $checkoutType + * @param BasePaymentType | string $paymentType This is needed to set the correct key in additionalTransactionData array. + * + * @return self + */ + public function setCheckoutType(string $checkoutType, $paymentType): self + { + if (is_string($paymentType)) { + $paymentType = ResourceService::getTypeInstanceFromIdString($paymentType); + } + + $typeName = $paymentType::getResourceName(); + if (empty($this->getAdditionalTransactionData()->$typeName)) { + $this->addAdditionalTransactionData($typeName, new StdClass()); + } + + $checkoutTypekey = AdditionalTransactionDataKeys::CHECKOUTTYPE; + $this->getAdditionalTransactionData()->$typeName->$checkoutTypekey = $checkoutType; + return $this; + } + + /** + * @return string|null + */ + public function getCheckoutType(): ?string + { + $additionalTransactionData = $this->getAdditionalTransactionData(); + if ($additionalTransactionData !== null) { + $key = AdditionalTransactionDataKeys::CHECKOUTTYPE; + foreach ($additionalTransactionData as $data) { + if ($data instanceof stdClass && property_exists($data, $key)) { + return $data->$key ?? null; + } + } + } + + return null; + } + + /** + * Get the card field from additional transaction Data. + * + * @return CardTransactionData|null "card" object of additionalTransaction data. + */ + public function getCardTransactionData(): ?CardTransactionData + { + $key = AdditionalTransactionDataKeys::CARD; + $card = $this->getAdditionalTransactionData()->$key ?? null; + return $card instanceof CardTransactionData ? $card : null; + } + + /** + * Sets CardTransactionData object as "card" field of additionalTransactionData. + * + * @param CardTransactionData|null $cardTransactionData + * + * @return self + */ + public function setCardTransactionData(?CardTransactionData $cardTransactionData): self + { + $this->addAdditionalTransactionData(AdditionalTransactionDataKeys::CARD, $cardTransactionData); + return $this; + } } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasCancellations.php b/vendor/unzerdev/php-sdk/src/Traits/HasCancellations.php index 85d2278..989499d 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasCancellations.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasCancellations.php @@ -2,26 +2,10 @@ /** * This trait adds the cancellation property to a class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Exceptions\UnzerApiException; @@ -35,8 +19,6 @@ trait HasCancellations /** @var array $cancellations */ private $cancellations = []; - // - /** * @return array */ @@ -81,7 +63,7 @@ public function addCancellation(Cancellation $cancellation): self * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. */ - public function getCancellation($cancellationId, $lazy = false): ?Cancellation + public function getCancellation(string $cancellationId, bool $lazy = false): ?Cancellation { /** @var Cancellation $cancellation */ foreach ($this->cancellations as $cancellation) { @@ -95,6 +77,4 @@ public function getCancellation($cancellationId, $lazy = false): ?Cancellation } return null; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasChargebacks.php b/vendor/unzerdev/php-sdk/src/Traits/HasChargebacks.php new file mode 100644 index 0000000..6918afa --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Traits/HasChargebacks.php @@ -0,0 +1,80 @@ +chargebacks; + } + + /** + * @param array $chargebacks + * + * @return self + */ + public function setChargebacks(array $chargebacks): self + { + $this->chargebacks = $chargebacks; + return $this; + } + + /** + * @param Chargeback $chargeback + * + * @return self + */ + public function addChargeback(Chargeback $chargeback): self + { + if ($this instanceof UnzerParentInterface) { + $chargeback->setParentResource($this); + } + $this->chargebacks[] = $chargeback; + return $this; + } + + /** + * Return specific Chargeback object or null if it does not exist. + * + * @param string $chargebackId The id of the chargeback object + * @param boolean $lazy + * + * @return Chargeback|null The chargeback or null if none could be found. + * + * @throws RuntimeException A RuntimeException is thrown when there is an error while using the SDK. + * @throws UnzerApiException An UnzerApiException is thrown if there is an error returned on API-request. + */ + public function getChargeback(string $chargebackId, bool $lazy = false): ?Chargeback + { + /** @var Chargeback $chargeback */ + foreach ($this->chargebacks as $chargeback) { + if ($chargeback->getId() === $chargebackId) { + if (!$lazy && $this instanceof UnzerParentInterface) { + /** @var AbstractUnzerResource $this*/ + $this->getResource($chargeback); + } + return $chargeback; + } + } + return null; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasCustomerMessage.php b/vendor/unzerdev/php-sdk/src/Traits/HasCustomerMessage.php index e4551c4..af3cdd8 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasCustomerMessage.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasCustomerMessage.php @@ -2,26 +2,10 @@ /** * This trait adds the message properties to a resource class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Resources\EmbeddedResources\Message; @@ -31,8 +15,6 @@ trait HasCustomerMessage /** @var Message $message */ private $message; - // - /** * @return Message */ @@ -44,6 +26,4 @@ public function getMessage(): Message return $this->message; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasDate.php b/vendor/unzerdev/php-sdk/src/Traits/HasDate.php index 1b3ec42..77d7807 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasDate.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasDate.php @@ -2,26 +2,10 @@ /** * This trait adds the date property to a resource class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use DateTime; @@ -32,8 +16,6 @@ trait HasDate /** @var DateTime $date */ private $date; - // - /** * This returns the date of the Transaction as string. * @@ -57,6 +39,4 @@ public function setDate(string $date): self $this->date = new DateTime($date); return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasDescriptor.php b/vendor/unzerdev/php-sdk/src/Traits/HasDescriptor.php new file mode 100644 index 0000000..5ddab85 --- /dev/null +++ b/vendor/unzerdev/php-sdk/src/Traits/HasDescriptor.php @@ -0,0 +1,36 @@ +descriptor; + } + + /** + * @param string|null $descriptor + * + * @return self + */ + protected function setDescriptor(?string $descriptor): self + { + $this->descriptor = $descriptor; + return $this; + } +} diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasGeoLocation.php b/vendor/unzerdev/php-sdk/src/Traits/HasGeoLocation.php index 3a4b026..6869a0c 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasGeoLocation.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasGeoLocation.php @@ -2,26 +2,10 @@ /** * This trait adds geolocation to class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Resources\EmbeddedResources\GeoLocation; @@ -31,8 +15,6 @@ trait HasGeoLocation /** @var GeoLocation $geoLocation */ private $geoLocation; - // - /** * @return GeoLocation */ @@ -54,6 +36,4 @@ public function setGeoLocation(GeoLocation $geoLocation): self $this->geoLocation = $geoLocation; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasInvoiceId.php b/vendor/unzerdev/php-sdk/src/Traits/HasInvoiceId.php index aa2f143..a41d972 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasInvoiceId.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasInvoiceId.php @@ -2,26 +2,10 @@ /** * This trait adds the invoiceId property to a class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; trait HasInvoiceId @@ -29,8 +13,6 @@ trait HasInvoiceId /** @var string $invoiceId */ protected $invoiceId; - // - /** * @return string|null */ @@ -44,11 +26,9 @@ public function getInvoiceId(): ?string * * @return self */ - public function setInvoiceId($invoiceId): self + public function setInvoiceId(?string $invoiceId): self { $this->invoiceId = $invoiceId; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasOrderId.php b/vendor/unzerdev/php-sdk/src/Traits/HasOrderId.php index 6bc652a..3f0d2a3 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasOrderId.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasOrderId.php @@ -2,26 +2,10 @@ /** * This trait adds the orderId property to a class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; trait HasOrderId @@ -29,8 +13,6 @@ trait HasOrderId /** @var string $orderId */ protected $orderId; - // - /** * @return string|null */ @@ -44,11 +26,9 @@ public function getOrderId(): ?string * * @return $this */ - public function setOrderId($orderId): self + public function setOrderId(?string $orderId): self { $this->orderId = $orderId; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasPaymentState.php b/vendor/unzerdev/php-sdk/src/Traits/HasPaymentState.php index 4c60f49..f24e08d 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasPaymentState.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasPaymentState.php @@ -2,26 +2,10 @@ /** * This trait adds the state property to a class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; use UnzerSDK\Constants\PaymentState; @@ -32,8 +16,6 @@ trait HasPaymentState /** @var int */ private $state = 0; - // - /** * Return true if the state is pending. * @@ -94,9 +76,15 @@ public function isChargeBack(): bool return $this->getState() === PaymentState::STATE_CHARGEBACK; } - // - - // + /** + * Return true if the state is create. + * + * @return bool + */ + public function isCreate(): bool + { + return $this->getState() === PaymentState::STATE_CREATE; + } /** * Returns the current state code (ref. Constants/PaymentState). @@ -132,6 +120,4 @@ protected function setState(int $state): self $this->state = $state; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasRecurrenceType.php b/vendor/unzerdev/php-sdk/src/Traits/HasRecurrenceType.php index a88d33a..15c04ec 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasRecurrenceType.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasRecurrenceType.php @@ -3,77 +3,40 @@ /** * This trait adds the short id and unique id property to a class. * - * Copyright (C) 2021 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author David Owusu - * - * @package UnzerSDK\Traits */ namespace UnzerSDK\Traits; -use RuntimeException; -use UnzerSDK\Resources\PaymentTypes\BasePaymentType; -use UnzerSDK\Resources\TransactionTypes\AbstractTransactionType; +use UnzerSDK\Resources\EmbeddedResources\CardTransactionData; trait HasRecurrenceType { - // - /** * @return string|null */ public function getRecurrenceType(): ?string { - $additionalTransactionData = $this->getAdditionalTransactionData(); - if ($additionalTransactionData !== null) { - foreach ($additionalTransactionData as $data) { - if (property_exists($data, 'recurrenceType')) { - return $data->recurrenceType ?? null; - } - } + $cardTransactionData = $this->getCardTransactionData(); + if ($cardTransactionData instanceof CardTransactionData) { + return $cardTransactionData->getRecurrenceType(); } - return null; + return $this->getAdditionalTransactionData()->card['recurrenceType'] ?? null; } /** - * @param string $recurrenceType Recurrence type used for recurring payment. - * @param BasePaymentType|null $paymentType If provided recurrenceType is set based on this payment type. - * This is required for recurring transaction, since the type can not be - * determined automatically. + * @param string $recurrenceType Recurrence type used for recurring payment. * * @return $this */ - public function setRecurrenceType(string $recurrenceType, BasePaymentType $paymentType = null): self + public function setRecurrenceType(string $recurrenceType): self { - if ($paymentType === null && $this instanceof AbstractTransactionType) { - $payment = $this->getPayment(); - $paymentType = $payment ? $payment->getPaymentType() : null; - } - - if ($paymentType === null) { - throw new RuntimeException('Payment type can not be determined. Set it first or provide it via parameter $paymentType.'); - } - $recurrenceTypeObject = (object)['recurrenceType' => $recurrenceType]; - $this->addAdditionalTransactionData($paymentType::getResourceName(), $recurrenceTypeObject); + $card = $this->getCardTransactionData() ?? new CardTransactionData(); + $card->setRecurrenceType($recurrenceType); + $this->addAdditionalTransactionData('card', $card); return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasStates.php b/vendor/unzerdev/php-sdk/src/Traits/HasStates.php index 5f019f1..7224874 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasStates.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasStates.php @@ -2,28 +2,15 @@ /** * This trait adds the state properties to a resource class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; +use RuntimeException; +use UnzerSDK\Constants\TransactionStatus; + trait HasStates { /** @var bool $isError */ @@ -35,7 +22,8 @@ trait HasStates /** @var bool $isPending */ private $isPending = false; - // + /** @var bool $isResumed */ + private $isResumed = false; /** * @return bool @@ -94,5 +82,79 @@ protected function setIsPending(bool $isPending): self return $this; } - // + /** + * @return bool + */ + public function isResumed(): bool + { + return $this->isResumed; + } + + /** + * @param bool $isResumed + * + * @return self + */ + public function setIsResumed(bool $isResumed): self + { + $this->isResumed = $isResumed; + return $this; + } + + /** + * Map the 'status' that is used for transactions in the transaction list of a payment resource. + * The actual transaction resource only has the isSuccess, isPending and isError property. + * + * @param string $status + * + * @throws RuntimeException + * + * @return self + */ + protected function setStatus(string $status): self + { + $this->validateTransactionStatus($status); + + $this->setIsSuccess(false); + $this->setIsPending(false); + $this->setIsError(false); + + switch ($status) { + case (TransactionStatus::STATUS_ERROR): + $this->setIsError(true); + break; + case (TransactionStatus::STATUS_PENDING): + $this->setIsPending(true); + break; + case (TransactionStatus::STATUS_SUCCESS): + $this->setIsSuccess(true); + break; + case (TransactionStatus::STATUS_RESUMED): + $this->setIsResumed(true); + break; + } + + return $this; + } + + /** + * Check if transaction status is valid. If status is invalid a RuntimeException is thrown + * + * @param string $status + * + * @throws RuntimeException + */ + public function validateTransactionStatus(string $status): void + { + $validStatusArray = [ + TransactionStatus::STATUS_ERROR, + TransactionStatus::STATUS_PENDING, + TransactionStatus::STATUS_SUCCESS, + TransactionStatus::STATUS_RESUMED, + ]; + + if (!in_array($status, $validStatusArray, true)) { + throw new RuntimeException('Transaction status can not be set. Status is invalid for transaction.'); + } + } } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasTraceId.php b/vendor/unzerdev/php-sdk/src/Traits/HasTraceId.php index 8f9ed8d..e8b223c 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasTraceId.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasTraceId.php @@ -3,26 +3,10 @@ * This trait adds the trace id to a class. * It can be sent to the support when a problem occurs. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; trait HasTraceId @@ -30,8 +14,6 @@ trait HasTraceId /** @var string $traceId */ private $traceId; - // - /** * @return string|null */ @@ -50,6 +32,4 @@ protected function setTraceId(string $traceId): self $this->traceId = $traceId; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/HasUniqueAndShortId.php b/vendor/unzerdev/php-sdk/src/Traits/HasUniqueAndShortId.php index ad18256..5c58971 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/HasUniqueAndShortId.php +++ b/vendor/unzerdev/php-sdk/src/Traits/HasUniqueAndShortId.php @@ -2,26 +2,10 @@ /** * This trait adds the short id and unique id property to a class. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; trait HasUniqueAndShortId @@ -32,8 +16,6 @@ trait HasUniqueAndShortId /** @var string $shortId */ private $shortId; - // - /** * @return string|null */ @@ -71,6 +53,4 @@ protected function setShortId(string $shortId): self $this->shortId = $shortId; return $this; } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Traits/IsInvoiceType.php b/vendor/unzerdev/php-sdk/src/Traits/IsInvoiceType.php index a240b8f..c0c6311 100644 --- a/vendor/unzerdev/php-sdk/src/Traits/IsInvoiceType.php +++ b/vendor/unzerdev/php-sdk/src/Traits/IsInvoiceType.php @@ -2,26 +2,10 @@ /** * This trait adds means to determine whether the payment type is an invoice type. * - * Copyright (C) 2020 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author Simon Gabriel - * - * @package UnzerSDK\Traits */ + namespace UnzerSDK\Traits; trait IsInvoiceType diff --git a/vendor/unzerdev/php-sdk/src/Unzer.php b/vendor/unzerdev/php-sdk/src/Unzer.php index 7fbe2b0..87240ff 100644 --- a/vendor/unzerdev/php-sdk/src/Unzer.php +++ b/vendor/unzerdev/php-sdk/src/Unzer.php @@ -1,45 +1,26 @@ - * - * @package UnzerSDK - */ + namespace UnzerSDK; use DateTime; +use RuntimeException; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Constants\CancelReasonCodes; use UnzerSDK\Interfaces\CancelServiceInterface; use UnzerSDK\Interfaces\DebugHandlerInterface; -use UnzerSDK\Interfaces\UnzerParentInterface; use UnzerSDK\Interfaces\PaymentServiceInterface; use UnzerSDK\Interfaces\ResourceServiceInterface; +use UnzerSDK\Interfaces\UnzerParentInterface; use UnzerSDK\Interfaces\WebhookServiceInterface; use UnzerSDK\Resources\AbstractUnzerResource; use UnzerSDK\Resources\Basket; +use UnzerSDK\Resources\Config; use UnzerSDK\Resources\Customer; +use UnzerSDK\Resources\EmbeddedResources\Paylater\InstallmentPlansQuery; use UnzerSDK\Resources\InstalmentPlans; use UnzerSDK\Resources\Keypair; use UnzerSDK\Resources\Metadata; +use UnzerSDK\Resources\PaylaterInstallmentPlans; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Paypage; @@ -47,6 +28,7 @@ use UnzerSDK\Resources\TransactionTypes\Authorization; use UnzerSDK\Resources\TransactionTypes\Cancellation; use UnzerSDK\Resources\TransactionTypes\Charge; +use UnzerSDK\Resources\TransactionTypes\Chargeback; use UnzerSDK\Resources\TransactionTypes\Payout; use UnzerSDK\Resources\TransactionTypes\Shipment; use UnzerSDK\Resources\Webhook; @@ -56,21 +38,32 @@ use UnzerSDK\Services\ResourceService; use UnzerSDK\Services\WebhookService; use UnzerSDK\Validators\PrivateKeyValidator; -use RuntimeException; -class Unzer implements UnzerParentInterface, PaymentServiceInterface, ResourceServiceInterface, WebhookServiceInterface, CancelServiceInterface +/** + * This is the Unzer object which is the base object providing all functionalities needed to + * access the api. + */ +class Unzer implements + UnzerParentInterface, + PaymentServiceInterface, + ResourceServiceInterface, + WebhookServiceInterface, + CancelServiceInterface { public const BASE_URL = 'api.unzer.com'; public const API_VERSION = 'v1'; public const SDK_TYPE = 'UnzerPHP'; - public const SDK_VERSION = '1.1.4.0'; + public const SDK_VERSION = '3.5.0'; /** @var string $key */ private $key; - /** @var string $locale */ + /** @var string|null $locale */ private $locale; + /** @var string|null $clientIp */ + private $clientIp; + /** @var ResourceServiceInterface $resourceService */ private $resourceService; @@ -95,14 +88,15 @@ class Unzer implements UnzerParentInterface, PaymentServiceInterface, ResourceSe /** * Construct a new Unzer object. * - * @param string $key The private key your received from your Unzer contact person. - * @param string $locale The locale of the customer defining defining the translation (e.g. 'en-GB' or 'de-DE'). - * - * @link https://docs.unzer.com/integrate/web-integration/#section-localization-and-languages + * @param string $key The private key your received from your Unzer contact person. + * @param ?string $locale The locale of the customer defining defining the translation (e.g. 'en-GB' or 'de-DE'). * * @throws RuntimeException A RuntimeException will be thrown if the key is not of type private. + * + *@link https://docs.unzer.com/integrate/web-integration/#section-localization-and-languages + * */ - public function __construct($key, $locale = null) + public function __construct(string $key, ?string $locale = '') { $this->setKey($key); $this->setLocale($locale); @@ -114,8 +108,6 @@ public function __construct($key, $locale = null) $this->httpService = new HttpService(); } - // - /** * Returns the set private key used to connect to the API. * @@ -134,8 +126,10 @@ public function getKey(): string * @return Unzer This Unzer object. * * @throws RuntimeException Throws a RuntimeException when the key is invalid. + * + * @deprecated public access will be removed. Please create a new instance with a different keypair instead. */ - public function setKey($key): Unzer + public function setKey(string $key): Unzer { if (!PrivateKeyValidator::validate($key)) { throw new RuntimeException('Illegal key: Use a valid private key with this SDK!'); @@ -146,7 +140,7 @@ public function setKey($key): Unzer } /** - * Returns the set customer locale. + * Returns the set customer locale. This will be set as a request header field. * * @return string|null The locale of the customer. * Refer to the documentation under https://docs.unzer.com for a list of supported values. @@ -164,12 +158,37 @@ public function getLocale(): ?string * * @return Unzer This Unzer object. */ - public function setLocale($locale): Unzer + public function setLocale(?string $locale): Unzer { + if ($locale === null) { + return $this; + } + $this->locale = str_replace('_', '-', $locale); return $this; } + /** + * @return string|null + */ + public function getClientIp(): ?string + { + return $this->clientIp; + } + + /** + * Sets the clientIp. This will be set as a request header field. + * + * @param string|null $clientIp + * + * @return Unzer + */ + public function setClientIp(?string $clientIp): Unzer + { + $this->clientIp = $clientIp; + return $this; + } + /** * @param ResourceService $resourceService * @@ -312,10 +331,6 @@ public function setHttpService(HttpService $httpService): Unzer return $this; } - // - - // - /** * Returns this Unzer instance. * @@ -329,28 +344,26 @@ public function getUnzerObject(): Unzer /** * {@inheritDoc} */ - public function getUri($appendId = true, $httpMethod = HttpAdapterInterface::REQUEST_GET): string + public function getUri(bool $appendId = true, string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return ''; } - // - - // - - // - /** * {@inheritDoc} */ - public function activateRecurringPayment($paymentType, $returnUrl, string $recurrenceType = null): Recurring + public function activateRecurringPayment($paymentType, string $returnUrl, string $recurrenceType = null): Recurring { return $this->resourceService->activateRecurringPayment($paymentType, $returnUrl, $recurrenceType); } - // - - // + /** + * {@inheritDoc} + */ + public function fetchPayPage($payPage): Paypage + { + return $this->resourceService->fetchPayPage($payPage); + } /** * {@inheritDoc} @@ -363,27 +376,19 @@ public function fetchPayment($payment): Payment /** * {@inheritDoc} */ - public function fetchPaymentByOrderId($orderId): Payment + public function fetchPaymentByOrderId(string $orderId): Payment { return $this->resourceService->fetchPaymentByOrderId($orderId); } - // - - // - /** * {@inheritDoc} */ - public function fetchKeypair($detailed = false): Keypair + public function fetchKeypair(bool $detailed = false): Keypair { return $this->resourceService->fetchKeypair($detailed); } - // - - // - /** * {@inheritDoc} */ @@ -400,10 +405,6 @@ public function fetchMetadata($metadata): Metadata return $this->resourceService->fetchMetadata($metadata); } - // - - // - /** * {@inheritDoc} */ @@ -428,10 +429,6 @@ public function updateBasket(Basket $basket): Basket return $this->resourceService->updateBasket($basket); } - // - - // - /** * {@inheritDoc} */ @@ -451,15 +448,11 @@ public function updatePaymentType(BasePaymentType $paymentType): BasePaymentType /** * {@inheritDoc} */ - public function fetchPaymentType($typeId): BasePaymentType + public function fetchPaymentType(string $typeId): BasePaymentType { return $this->resourceService->fetchPaymentType($typeId); } - // - - // - /** * {@inheritDoc} */ @@ -487,7 +480,7 @@ public function fetchCustomer($customer): Customer /** * {@inheritDoc} */ - public function fetchCustomerByExtCustomerId($customerId): Customer + public function fetchCustomerByExtCustomerId(string $customerId): Customer { return $this->resourceService->fetchCustomerByExtCustomerId($customerId); } @@ -508,10 +501,6 @@ public function deleteCustomer($customer): void $this->resourceService->deleteCustomer($customer); } - // - - // - /** * {@inheritDoc} */ @@ -520,16 +509,12 @@ public function fetchAuthorization($payment): Authorization return $this->resourceService->fetchAuthorization($payment); } - // - - // - /** * {@inheritDoc} */ - public function fetchChargeById($paymentId, $chargeId): Charge + public function fetchChargeById($payment, string $chargeId): Charge { - return $this->resourceService->fetchChargeById($paymentId, $chargeId); + return $this->resourceService->fetchChargeById($payment, $chargeId); } /** @@ -540,14 +525,23 @@ public function fetchCharge(Charge $charge): Charge return $this->resourceService->fetchCharge($charge); } - // + /** + * {@inheritDoc} + */ + public function fetchChargebackById(string $paymentId, string $charebackId, ?string $chargeId): Chargeback + { + return $this->resourceService->fetchChargebackById($paymentId, $charebackId, $chargeId); + } - // + public function fetchChargeback(Chargeback $chargeback): Chargeback + { + return $this->resourceService->fetchResource($chargeback); + } /** * {@inheritDoc} */ - public function fetchReversalByAuthorization($authorization, $cancellationId): Cancellation + public function fetchReversalByAuthorization(Authorization $authorization, string $cancellationId): Cancellation { return $this->resourceService->fetchReversalByAuthorization($authorization, $cancellationId); } @@ -555,7 +549,7 @@ public function fetchReversalByAuthorization($authorization, $cancellationId): C /** * {@inheritDoc} */ - public function fetchReversal($payment, $cancellationId): Cancellation + public function fetchReversal($payment, string $cancellationId): Cancellation { return $this->resourceService->fetchReversal($payment, $cancellationId); } @@ -563,7 +557,7 @@ public function fetchReversal($payment, $cancellationId): Cancellation /** * {@inheritDoc} */ - public function fetchRefundById($payment, $chargeId, $cancellationId): Cancellation + public function fetchRefundById($payment, string $chargeId, string $cancellationId): Cancellation { return $this->resourceService->fetchRefundById($payment, $chargeId, $cancellationId); } @@ -571,27 +565,35 @@ public function fetchRefundById($payment, $chargeId, $cancellationId): Cancellat /** * {@inheritDoc} */ - public function fetchRefund(Charge $charge, $cancellationId): Cancellation + public function fetchRefund(Charge $charge, string $cancellationId): Cancellation { return $this->resourceService->fetchRefund($charge, $cancellationId); } - // + /** + * {@inheritDoc} + */ + public function fetchPaymentRefund($payment, string $cancellationId): Cancellation + { + return $this->resourceService->fetchPaymentRefund($payment, $cancellationId); + } - // + /** + * {@inheritDoc} + */ + public function fetchPaymentReversal($payment, string $cancellationId): Cancellation + { + return $this->resourceService->fetchPaymentReversal($payment, $cancellationId); + } /** * {@inheritDoc} */ - public function fetchShipment($payment, $shipmentId): Shipment + public function fetchShipment($payment, string $shipmentId): Shipment { return $this->resourceService->fetchShipment($payment, $shipmentId); } - // - - // - /** * {@inheritDoc} */ @@ -600,10 +602,6 @@ public function fetchPayout($payment): Payout return $this->resourceService->fetchPayout($payment); } - // - - // - /** * {@inheritDoc} */ @@ -623,7 +621,7 @@ public function fetchWebhook($webhook): Webhook /** * {@inheritDoc} */ - public function updateWebhook($webhook): Webhook + public function updateWebhook(Webhook $webhook): Webhook { return $this->webhookService->updateWebhook($webhook); } @@ -663,18 +661,28 @@ public function registerMultipleWebhooks(string $url, array $events): array /** * {@inheritDoc} */ - public function fetchResourceFromEvent($eventJson = null): AbstractUnzerResource + public function fetchResourceFromEvent(string $eventJson = null): AbstractUnzerResource { return $this->webhookService->fetchResourceFromEvent($eventJson); } - // - - // - - // + /** + * {@inheritDoc} + */ + public function performAuthorization( + Authorization $authorization, + $paymentType, + $customer = null, + Metadata $metadata = null, + Basket $basket = null + ): Authorization { + return $this->paymentService->performAuthorization($authorization, $paymentType, $customer, $metadata, $basket); + } - // + public function updateAuthorization($payment, Authorization $authorization): Authorization + { + return $this->paymentService->updateAuthorization($payment, $authorization); + } /** * {@inheritDoc} @@ -709,9 +717,23 @@ public function authorize( ); } - // + /** + * {@inheritDoc} + */ + public function performCharge( + Charge $charge, + $paymentType, + $customer = null, + Metadata $metadata = null, + Basket $basket = null + ): Charge { + return $this->paymentService->performCharge($charge, $paymentType, $customer, $metadata, $basket); + } - // + public function updateCharge($payment, Charge $charge): Charge + { + return $this->paymentService->updateCharge($payment, $charge); + } /** * {@inheritDoc} @@ -764,17 +786,16 @@ public function chargeAuthorization( public function chargePayment( $payment, float $amount = null, - string $currency = null, string $orderId = null, string $invoiceId = null ): Charge { - $paymentObject = $this->resourceService->getPaymentResource($payment); - return $this->paymentService->chargePayment($paymentObject, $amount, $currency, $orderId, $invoiceId); + return $this->paymentService->chargePayment($payment, $amount, $orderId, $invoiceId); } - // - - // + public function performChargeOnPayment($payment, Charge $charge): Charge + { + return $this->paymentService->performChargeOnPayment($payment, $charge); + } /** * {@inheritDoc} @@ -792,17 +813,13 @@ public function cancelAuthorizationByPayment($payment, float $amount = null): Ca return $this->cancelService->cancelAuthorizationByPayment($payment, $amount); } - // - - // - /** * {@inheritDoc} */ public function cancelPayment( $payment, float $amount = null, - $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, + ?string $reasonCode = CancelReasonCodes::REASON_CODE_CANCEL, string $referenceText = null, float $amountNet = null, float $amountVat = null @@ -819,10 +836,6 @@ public function cancelPaymentAuthorization($payment, float $amount = null): ?Can return $this->cancelService->cancelPaymentAuthorization($payment, $amount); } - // - - // - /** * {@inheritDoc} */ @@ -854,9 +867,23 @@ public function cancelCharge( ->cancelCharge($charge, $amount, $reasonCode, $referenceText, $amountNet, $amountVat); } - // + /** + * {@inheritDoc} + */ + public function cancelAuthorizedPayment($payment, ?Cancellation $cancellation = null): Cancellation + { + return $this->cancelService + ->cancelAuthorizedPayment($payment, $cancellation); + } - // + /** + * {@inheritDoc} + */ + public function cancelChargedPayment($payment, ?Cancellation $cancellation = null): Cancellation + { + return $this->cancelService + ->cancelChargedPayment($payment, $cancellation); + } /** * {@inheritDoc} @@ -866,24 +893,20 @@ public function ship($payment, string $invoiceId = null, string $orderId = null) return $this->paymentService->ship($payment, $invoiceId, $orderId); } - // - - // - /** * {@inheritDoc} */ public function payout( - $amount, - $currency, + float $amount, + string $currency, $paymentType, - $returnUrl, + string $returnUrl, $customer = null, - $orderId = null, - $metadata = null, - $basket = null, - $invoiceId = null, - $referenceText = null + string $orderId = null, + Metadata $metadata = null, + Basket $basket = null, + string $invoiceId = null, + string $referenceText = null ): Payout { return $this->paymentService->payout( $amount, @@ -899,10 +922,6 @@ public function payout( ); } - // - - // - /** * {@inheritDoc} */ @@ -927,28 +946,33 @@ public function initPayPageAuthorize( return $this->paymentService->initPayPageAuthorize($paypage, $customer, $basket, $metadata); } - // - - // - /** * {@inheritDoc} */ public function fetchInstallmentPlans( - $amount, - $currency, - $effectiveInterest, + float $amount, + string $currency, + float $effectiveInterest, DateTime $orderDate = null ): InstalmentPlans { return $this->paymentService ->fetchInstallmentPlans($amount, $currency, $effectiveInterest, $orderDate); } - // - - // + public function fetchPaylaterInstallmentPlans(InstallmentPlansQuery $plansRequest): PaylaterInstallmentPlans + { + return $this->getPaymentService()->fetchPaylaterInstallmentPlans($plansRequest); + } - // + /** + * {@inheritDoc} + * + * @param Config|null $config + */ + public function fetchConfig(BasePaymentType $paymentType, ?Config $config = null): Config + { + return $this->getResourceService()->fetchConfig($paymentType, $config); + } /** * Writes the given string to the registered debug handler if debug mode is enabled. @@ -964,6 +988,4 @@ public function debugLog($message): void } } } - - // } diff --git a/vendor/unzerdev/php-sdk/src/Validators/ExpiryDateValidator.php b/vendor/unzerdev/php-sdk/src/Validators/ExpiryDateValidator.php index 67defba..50c2b53 100644 --- a/vendor/unzerdev/php-sdk/src/Validators/ExpiryDateValidator.php +++ b/vendor/unzerdev/php-sdk/src/Validators/ExpiryDateValidator.php @@ -1,29 +1,13 @@ - * - * @package UnzerSDK\Validators */ -namespace UnzerSDK\Validators; - class ExpiryDateValidator { /** @@ -33,7 +17,7 @@ class ExpiryDateValidator * * @return bool */ - public static function validate($expiryDate): bool + public static function validate(string $expiryDate): bool { return preg_match('/^(0[\d]|1[0-2]|[1-9])\/(\d{2}|\d{4})$/', $expiryDate); } diff --git a/vendor/unzerdev/php-sdk/src/Validators/PrivateKeyValidator.php b/vendor/unzerdev/php-sdk/src/Validators/PrivateKeyValidator.php index 092fb97..727a3bf 100644 --- a/vendor/unzerdev/php-sdk/src/Validators/PrivateKeyValidator.php +++ b/vendor/unzerdev/php-sdk/src/Validators/PrivateKeyValidator.php @@ -1,43 +1,30 @@ - * - * @package UnzerSDK\Validators */ -namespace UnzerSDK\Validators; - -use function count; - class PrivateKeyValidator { /** * Returns true if the given private key has a valid format. * - * @param string $key + * @param string|null $key * * @return bool */ - public static function validate($key): bool + public static function validate(?string $key): bool { $match = []; + if ($key === null) { + return false; + } preg_match('/^[sp]-priv-[a-zA-Z0-9]+/', $key, $match); return count($match) > 0; } diff --git a/vendor/unzerdev/php-sdk/src/Validators/PublicKeyValidator.php b/vendor/unzerdev/php-sdk/src/Validators/PublicKeyValidator.php index 35d8b57..1d4a89c 100644 --- a/vendor/unzerdev/php-sdk/src/Validators/PublicKeyValidator.php +++ b/vendor/unzerdev/php-sdk/src/Validators/PublicKeyValidator.php @@ -1,43 +1,30 @@ - * - * @package UnzerSDK\Validators */ -namespace UnzerSDK\Validators; - -use function count; - class PublicKeyValidator { /** * Returns true if the given public key has a valid format. * - * @param string $key + * @param string|null $key * * @return bool */ - public static function validate($key): bool + public static function validate(?string $key): bool { $match = []; + if ($key === null) { + return false; + } preg_match('/^[sp]-pub-[a-zA-Z0-9]+/', $key, $match); return count($match) > 0; } diff --git a/vendor/unzerdev/php-sdk/test/BaseIntegrationTest.php b/vendor/unzerdev/php-sdk/test/BaseIntegrationTest.php index aa16f4c..b9d2263 100644 --- a/vendor/unzerdev/php-sdk/test/BaseIntegrationTest.php +++ b/vendor/unzerdev/php-sdk/test/BaseIntegrationTest.php @@ -1,32 +1,19 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test; -use UnzerSDK\Services\EnvironmentService; +use UnzerSDK\Resources\PaymentTypes\PaylaterInvoice; +use UnzerSDK\Resources\TransactionTypes\Authorization; +use UnzerSDK\test\Helper\TestEnvironmentService; use PHPUnit\Runner\BaseTestRunner; class BaseIntegrationTest extends BasePaymentTest @@ -36,7 +23,7 @@ class BaseIntegrationTest extends BasePaymentTest */ protected function setUp(): void { - $this->getUnzerObject(EnvironmentService::getTestPrivateKey()); + $this->getUnzerObject(TestEnvironmentService::getTestPrivateKey()); } /** @@ -56,4 +43,40 @@ protected function tearDown(): void echo "\n"; } } + + /** Creates a Paylater Invoice authorization transaction with an amount of 99.99€. + * + * @return Authorization + * + * @throws \UnzerSDK\Exceptions\UnzerApiException + */ + protected function createPaylaterInvoiceAuthorization(): Authorization + { + $paylaterInvoice = $this->unzer->createPaymentType(new PaylaterInvoice()); + + $authorization = new Authorization(99.99, 'EUR', 'https://unzer.com'); + $authorization->setInvoiceId('202205021237'); + + $customer = $this->getMaximumCustomerInclShippingAddress(); + $basket = $this->createV2Basket(); + + $authorization = $this->unzer->performAuthorization($authorization, $paylaterInvoice, $customer, null, $basket); + return $authorization; + } + + /** + * @return void + */ + protected function useNon3dsKey(): void + { + $this->getUnzerObject()->setKey(TestEnvironmentService::getTestPrivateKey(true)); + } + + /** + * @return void + */ + protected function useLegacyKey(): void + { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); + } } diff --git a/vendor/unzerdev/php-sdk/test/BasePaymentTest.php b/vendor/unzerdev/php-sdk/test/BasePaymentTest.php index b6402a0..54da6b6 100644 --- a/vendor/unzerdev/php-sdk/test/BasePaymentTest.php +++ b/vendor/unzerdev/php-sdk/test/BasePaymentTest.php @@ -1,34 +1,20 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test; use DateInterval; use DateTime; -use UnzerSDK\Unzer; +use PHPUnit\Framework\TestCase; +use RuntimeException; use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\EmbeddedResources\BasketItem; use UnzerSDK\Resources\Payment; @@ -40,14 +26,13 @@ use UnzerSDK\Resources\TransactionTypes\Authorization; use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\Fixtures\CustomerFixtureTrait; -use PHPUnit\Framework\TestCase; -use RuntimeException; +use UnzerSDK\Unzer; class BasePaymentTest extends TestCase { - protected const RETURN_URL = 'https://dev.unzer.com'; - use CustomerFixtureTrait; + protected const RETURN_URL = 'https://dev.unzer.com'; + public const API_VERSION_2 = 'v2'; /** @var Unzer $unzer */ protected $unzer; @@ -199,6 +184,28 @@ public function createBasket(): Basket return $basket; } + /** + * Creates a v2 Basket resource and returns it. + * + * @return Basket + */ + public function createV2Basket(): Basket + { + $orderId = 'b' . self::generateRandomId(); + $basket = new Basket($orderId); + $basket->setTotalValueGross(99.99) + ->setCurrencyCode('EUR'); + + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross(99.99) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('title'); + $basket->addBasketItem($basketItem); + $this->unzer->createBasket($basket); + return $basket; + } + /** * Creates a Card object for tests. * @@ -206,7 +213,7 @@ public function createBasket(): Basket * * @return Card */ - protected function createCardObject(string $cardNumber = '5453010000059543'): Card + protected function createCardObject(string $cardNumber = '4711100000000000'): Card { $expiryDate = $this->getNextYearsTimestamp()->format('m/Y'); $card = new Card($cardNumber, $expiryDate); diff --git a/vendor/unzerdev/php-sdk/test/Fixtures/CustomerFixtureTrait.php b/vendor/unzerdev/php-sdk/test/Fixtures/CustomerFixtureTrait.php index feef91d..6055e81 100644 --- a/vendor/unzerdev/php-sdk/test/Fixtures/CustomerFixtureTrait.php +++ b/vendor/unzerdev/php-sdk/test/Fixtures/CustomerFixtureTrait.php @@ -1,36 +1,24 @@ - * - * @package UnzerSDK\test\Fixtures */ + namespace UnzerSDK\test\Fixtures; use UnzerSDK\Constants\CompanyCommercialSectorItems; +use UnzerSDK\Constants\CompanyTypes; use UnzerSDK\Constants\Salutations; +use UnzerSDK\Constants\ShippingTypes; use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\CustomerFactory; use UnzerSDK\Resources\EmbeddedResources\Address; +use UnzerSDK\Resources\EmbeddedResources\CompanyOwner; trait CustomerFixtureTrait { @@ -97,12 +85,23 @@ public function getMinimalNotRegisteredB2bCustomer(): Customer */ public function getMaximalNotRegisteredB2bCustomer(): Customer { - return $this->getMinimalNotRegisteredB2bCustomer() + $customer = $this->getMinimalNotRegisteredB2bCustomer() ->setShippingAddress($this->getShippingAddress()) ->setSalutation(Salutations::MR) ->setMobile('+49172123456') ->setPhone('+4962216471100') ->setBillingAddress($this->getBillingAddress()); + + $owner = (new CompanyOwner()) + ->setFirstname('firstname') + ->setLastname('lastname') + ->setBirthdate('1999-01-01'); + + $customer->getCompanyInfo() + ->setOwner($owner) + ->setCompanyType(CompanyTypes::COMPANY); + + return $customer; } /** @@ -122,12 +121,23 @@ public function getMinimalRegisteredB2bCustomer(): Customer */ public function getMaximalRegisteredB2bCustomer(): Customer { - return $this->getMinimalRegisteredB2bCustomer() + $customer = $this->getMinimalRegisteredB2bCustomer() ->setShippingAddress($this->getShippingAddress()) ->setSalutation(Salutations::MR) ->setMobile('+49172123456') ->setPhone('+4962216471100') ->setBillingAddress($this->getBillingAddress()); + + $owner = (new CompanyOwner()) + ->setFirstname('firstname') + ->setLastname('lastname') + ->setBirthdate('1999-01-01'); + + $customer->getCompanyInfo() + ->setOwner($owner) + ->setCompanyType(CompanyTypes::COMPANY); + + return $customer; } /** @@ -159,6 +169,7 @@ public function getShippingAddress(): Address ->setZip('60386') ->setCity('Frankfurt am Main') ->setCountry('DE') - ->setState('DE-BO'); + ->setState('DE-BO') + ->setShippingType(ShippingTypes::EQUALS_BILLING); } } diff --git a/vendor/unzerdev/php-sdk/test/Fixtures/JsonProvider.php b/vendor/unzerdev/php-sdk/test/Fixtures/JsonProvider.php new file mode 100644 index 0000000..e360d77 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/Fixtures/JsonProvider.php @@ -0,0 +1,29 @@ + - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test; use UnzerSDK\Interfaces\DebugHandlerInterface; -use UnzerSDK\Services\EnvironmentService; class TestDebugHandler implements DebugHandlerInterface { @@ -41,7 +25,7 @@ public function log(string $message): void { $logMessage = 'Unzer debug message: ' . $message . "\n"; - if (EnvironmentService::isTestLoggingActive()) { + if (Helper\TestEnvironmentService::isTestLoggingActive()) { // Echo log messages directly. echo $logMessage; } else { diff --git a/vendor/unzerdev/php-sdk/test/bootstrap.php b/vendor/unzerdev/php-sdk/test/bootstrap.php index 284db20..fe98846 100644 --- a/vendor/unzerdev/php-sdk/test/bootstrap.php +++ b/vendor/unzerdev/php-sdk/test/bootstrap.php @@ -1,27 +1,11 @@ - * - * @package UnzerSDK\tests */ require_once __DIR__ . '/../vendor/autoload.php'; diff --git a/vendor/unzerdev/php-sdk/test/integration/ApplepayAdapterTest.php b/vendor/unzerdev/php-sdk/test/integration/ApplepayAdapterTest.php index 323f3ba..f241704 100644 --- a/vendor/unzerdev/php-sdk/test/integration/ApplepayAdapterTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/ApplepayAdapterTest.php @@ -2,26 +2,8 @@ /* * Test class for applepay adapter * - * Copyright (C) 2021 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author David Owusu - * - * @package UnzerSDK - * */ namespace UnzerSDK\test\integration; @@ -29,8 +11,8 @@ use UnzerSDK\Adapter\ApplepayAdapter; use UnzerSDK\Exceptions\ApplepayMerchantValidationException; use UnzerSDK\Resources\ExternalResources\ApplepaySession; -use UnzerSDK\Services\EnvironmentService; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class ApplepayAdapterTest extends BaseIntegrationTest { @@ -52,11 +34,12 @@ protected function setUp(): void { $this->merchantValidationUrl = 'https://apple-pay-gateway-cert.apple.com/paymentservices/startSession'; - $appleMerchantIdPath = EnvironmentService::getAppleMerchantIdPath(); - $this->applepayCertPath = $appleMerchantIdPath . 'merchant_id.pem'; - $this->applepayKeyPath = $appleMerchantIdPath . 'merchant_id.key'; - $this->applepayCombinedCertPath = $appleMerchantIdPath . 'apple-pay-cert.pem'; - $this->appleCaCertificatePath = EnvironmentService::getAppleCaCertificatePath(); + $appleMerchantIdPath = TestEnvironmentService::getAppleMerchantIdPath(); + + $this->applepayCertPath = $this->createFilePath($appleMerchantIdPath, 'merchant_id.pem'); + $this->applepayKeyPath = $this->createFilePath($appleMerchantIdPath, 'merchant_id.key'); + $this->applepayCombinedCertPath = $this->createFilePath($appleMerchantIdPath, 'apple-pay-cert.pem'); + $this->appleCaCertificatePath = TestEnvironmentService::getAppleCaCertificatePath(); } /** @@ -196,6 +179,7 @@ public function merchantValidationThrowsErrorForInvalidDomain(): void * test merchant validation request without ca certificate. * * @dataProvider domainShouldBeValidatedCorrectlyDP + * * @test * * @param mixed $validationUrl @@ -224,4 +208,16 @@ public function domainShouldBeValidatedCorrectlyDP(): array 'invalid: (empty)' => ['', false], ]; } + + /** + * @param string $appleMerchantIdPath + * @param string $merchantIdFile + * + * @return string + */ + protected function createFilePath(string $appleMerchantIdPath, string $merchantIdFile): string + { + $separator = DIRECTORY_SEPARATOR; + return rtrim($appleMerchantIdPath, $separator) . $separator . $merchantIdFile; + } } diff --git a/vendor/unzerdev/php-sdk/test/integration/BasketTest.php b/vendor/unzerdev/php-sdk/test/integration/BasketTest.php index b9ed4cb..b1d7103 100644 --- a/vendor/unzerdev/php-sdk/test/integration/BasketTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/BasketTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\ApiResponseCodes; @@ -36,6 +21,8 @@ class BasketTest extends BaseIntegrationTest { + // + /** * Verify basket can be created and fetched. * @@ -65,17 +52,17 @@ public function minBasketShouldBeCreatableAndFetchable(): void * * @test */ - public function maxBasketShouldBeCreatableAndFetchableWorkAround(): void + public function maxBasketShouldBeCreatableAndFetchable(): void { $basket = new Basket('b' . self::generateRandomId(), 123.4, 'EUR', []); $basket->setNote('This basket is creatable!'); $basketItem = (new BasketItem('myItem', 1234, 2345, 12)) ->setBasketItemReferenceId('refId') ->setAmountVat(1.24) - ->setVat(19) + ->setVat(19.5) ->setUnit('ert') ->setAmountDiscount(1234.9) - ->setImageUrl('https://dev.unzer.com/wp-content/uploads/2020/09/Unzer__PrimaryLogo_Raspberry_RGB.png') + ->setImageUrl('https://docs.unzer.com/card/card.png') ->setSubTitle('This is some subtitle for this item') ->setType('this is some type'); $basket->addBasketItem($basketItem); @@ -99,8 +86,8 @@ public function maxBasketShouldBeCreatableAndFetchableWorkAround(): void * * @dataProvider basketItemWithInvalidUrlWillThrowAnErrorDP * - * @param $expectException - * @param $imageUrl + * @param $expectException + * @param $imageUrl * @param null $exceptionCode */ public function basketItemWithInvalidUrlWillThrowAnError($expectException, $imageUrl, $exceptionCode = null): void @@ -158,10 +145,12 @@ public function basketShouldBeUpdateable(): void */ public function authorizeTransactionsShouldPassAlongTheBasketIdIfSet(): void { + $this->useLegacyKey(); + $orderId = 'o'. self::generateRandomId(); $basket = new Basket($orderId, 123.4, 'EUR', []); $basket->setNote('This basket is creatable!'); - $basketItem = (new BasketItem('myItem', 123.4, 234.5, 12))->setBasketItemReferenceId('refId'); + $basketItem = (new BasketItem('myItem', 123.4, 123.4, 12))->setBasketItemReferenceId('refId'); $basket->addBasketItem($basketItem); $this->unzer->createBasket($basket); $this->assertNotEmpty($basket->getId()); @@ -181,6 +170,7 @@ public function authorizeTransactionsShouldPassAlongTheBasketIdIfSet(): void */ public function chargeTransactionsShouldPassAlongTheBasketIdIfSet(): void { + $this->useLegacyKey(); $basket = $this->createBasket(); $this->assertNotEmpty($basket->getId()); @@ -201,6 +191,8 @@ public function chargeTransactionsShouldPassAlongTheBasketIdIfSet(): void */ public function authorizeTransactionsShouldCreateBasketIfItDoesNotExistYet(): void { + $this->useLegacyKey(); + $orderId = 'o'. self::generateRandomId(); $basket = new Basket($orderId, 123.4, 'EUR', []); $basket->setNote('This basket is creatable!'); @@ -224,6 +216,8 @@ public function authorizeTransactionsShouldCreateBasketIfItDoesNotExistYet(): vo */ public function chargeTransactionsShouldCreateBasketIfItDoesNotExistYet(): void { + $this->useLegacyKey(); + $orderId = 'o'. self::generateRandomId(); $basket = new Basket($orderId, 123.4, 'EUR', []); $basket->setNote('This basket is creatable!'); @@ -241,6 +235,8 @@ public function chargeTransactionsShouldCreateBasketIfItDoesNotExistYet(): void $this->assertEquals($basket->expose(), $fetchedPayment->getBasket()->expose()); } + // + // /** @@ -249,7 +245,7 @@ public function chargeTransactionsShouldCreateBasketIfItDoesNotExistYet(): void public function basketItemWithInvalidUrlWillThrowAnErrorDP(): array { return [ - 'valid ' => [false, 'https://dev.unzer.com/wp-content/uploads/2020/09/Unzer__PrimaryLogo_Raspberry_RGB.png'], + 'valid ' => [false, 'https://docs.unzer.com/card/card.png'], 'valid null' => [false, null], 'valid empty' => [false, ''], 'invalid not available' => [true, 'https://files.readme.io/does-not-exist.jpg', ApiResponseCodes::API_ERROR_BASKET_ITEM_IMAGE_INVALID_URL] diff --git a/vendor/unzerdev/php-sdk/test/integration/BasketV2Test.php b/vendor/unzerdev/php-sdk/test/integration/BasketV2Test.php new file mode 100644 index 0000000..71428ab --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/BasketV2Test.php @@ -0,0 +1,320 @@ + + + /** + * Verify basket can be created and fetched. + * + * @test + */ + public function minV2BasketShouldBeCreatableAndFetchable(): void + { + $basket = new Basket(); + $basket->setTotalValueGross(100) + ->setCurrencyCode('EUR'); + $basketItem = new BasketItem(); + $basketItem->setBasketItemReferenceId('item1') + ->setQuantity(1) + ->setAmountPerUnitGross(100) + ->setTitle('title'); + $basket->addBasketItem($basketItem); + $this->assertEmpty($basket->getId()); + + $this->unzer->createBasket($basket); + $this->assertNotEmpty($basket->getId()); + + $fetchedBasket = $this->unzer->fetchBasket($basket->getId())->setOrderId(''); + $this->assertEquals($basket->expose(), $fetchedBasket->expose()); + } + + /** + * Verify basket can be created and fetched. + * + * @test + */ + public function BasketShouldBeCreatableAndFetchable(): void + { + $orderId = microtime(true); + $basket = new Basket(); + $basket->setTotalValueGross(100) + ->setOrderId('testOrderId') + ->setCurrencyCode('EUR'); + $basketItem = new BasketItem(); + $basketItem->setBasketItemReferenceId('item1') + ->setQuantity(1) + ->setAmountPerUnitGross(100) + ->setTitle('title'); + $basket->addBasketItem($basketItem); + $this->assertEmpty($basket->getId()); + + $this->unzer->createBasket($basket); + $this->assertNotEmpty($basket->getId()); + + $fetchedBasket = $this->unzer->fetchBasket($basket->getId()); + $this->assertEquals($basket->expose(), $fetchedBasket->expose()); + } + + /** + * Verify basket can be created and fetched. + * + * @test + */ + public function maxBasketShouldBeCreatableAndFetchable(): void + { + $orderId = 'o'. self::generateRandomId(); + $basket = new Basket(); + $basket->setOrderId($orderId) + ->setCurrencyCode('EUR') + ->setNote('note this!') + ->setTotalValueGross(133.33); + + $basketItem = (new BasketItem()) + ->setBasketItemReferenceId('refIdOne') + ->setQuantity(10) + ->setAmountPerUnitGross(10.11) + ->setVat(19) + ->setTitle('Item Title 1') + ->setUnit('ert') + ->setAmountDiscountPerUnitGross(0.11) + ->setSubTitle('This is some subtitle for this item') + ->setImageUrl('https://docs.unzer.com/card/card.png') + ->setType('this is some type'); + $basket->addBasketItem($basketItem); + + $basketItem = (new BasketItem()) + ->setBasketItemReferenceId('refIdtwo') + ->setQuantity(1) + ->setAmountPerUnitGross(33.33) + ->setVat(19.5) + ->setTitle('Item Title 1') + ->setUnit('ert') + ->setAmountDiscountPerUnitGross(0.0) + ->setSubTitle('This is some subtitle for this item') + ->setImageUrl('https://docs.unzer.com/card/card.png') + ->setType('this is some type'); + $basket->addBasketItem($basketItem); + + $this->assertEmpty($basket->getId()); + + $this->unzer->createBasket($basket); + $this->assertNotEmpty($basket->getId()); + + $fetchedBasket = $this->unzer->fetchBasket($basket->getId()); + $exposedBasket = $basket->expose(); + unset($exposedBasket['note']); + $this->assertEquals($exposedBasket, $fetchedBasket->expose()); + $this->assertEquals( + $basket->getBasketItemByIndex(0)->expose(), + $fetchedBasket->getBasketItemByIndex(0)->expose() + ); + } + + /** + * Verify basketItem with invalid imageUrl will return an error. + * + * @test + * + * @dataProvider basketItemWithInvalidUrlWillThrowAnErrorDP + * + * @param $expectException + * @param $imageUrl + * @param null $exceptionCode + */ + public function basketItemWithInvalidUrlWillThrowAnError($expectException, $imageUrl, $exceptionCode = null): void + { + $basket = new Basket('b' . self::generateRandomId()); + $basket->setTotalValueGross(100) + ->setCurrencyCode('EUR'); + + $basketItem = (new BasketItem()) + ->setImageUrl($imageUrl) + ->setAmountPerUnitGross(100) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('title'); + $basket->addBasketItem($basketItem); + + try { + $this->unzer->createBasket($basket); + $this->assertFalse( + $expectException, + 'Failed asserting that exception of type "UnzerSDK\Exceptions\UnzerApiException" is thrown.' + ); + } catch (UnzerApiException $e) { + $this->assertTrue($expectException); + $this->assertEquals($exceptionCode, $e->getCode()); + $this->assertNotNull($e->getErrorId()); + } + } + + /** + * Verify the Basket can be updated. + * + * @test + */ + public function basketShouldBeUpdateable(): void + { + $orderId = 'b' . self::generateRandomId(); + $basket = new Basket($orderId); + $basket->setTotalValueGross(99.99) + ->setCurrencyCode('EUR'); + + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross(99.99) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('title'); + + $basket->addBasketItem($basketItem); + $this->unzer->createBasket($basket); + + $updateBasket = $this->unzer->fetchBasket($basket->getId()); + $updateBasket->setTotalValueGross(123.45) + ->getBasketItemByIndex(0) + ->setAmountPerUnitGross(123.45) + ->setTitle('This item can also be updated!'); + $this->unzer->updateBasket($updateBasket); + + $this->unzer->fetchBasket($basket); + $this->assertEquals($orderId, $basket->getOrderId()); + $this->assertEquals(123.45, $basket->getTotalValueGross()); + $this->assertNotEquals($basket->getBasketItemByIndex(0)->expose(), $basketItem->expose()); + } + + /** + * Verify basket can be passed to the payment on authorize. + * + * @test + */ + public function authorizeTransactionsShouldPassAlongTheBasketIdIfSet(): void + { + $basket = $this->createV2Basket(); + $this->assertNotEmpty($basket->getId()); + + /** @var Paypal $paypal */ + $paypal = $this->unzer->createPaymentType(new Paypal()); + $authorize = $paypal->authorize(123.4, 'EUR', 'https://unzer.com', null, null, null, $basket); + + $fetchedPayment = $this->unzer->fetchPayment($authorize->getPaymentId()); + $this->assertEquals($basket->expose(), $fetchedPayment->getBasket()->expose()); + } + + /** + * Verify basket can be passed to the payment on charge. + * + * @test + */ + public function chargeTransactionsShouldPassAlongTheBasketIdIfSet(): void + { + $this->useLegacyKey(); + $basket = $this->createV2Basket(); + $this->assertNotEmpty($basket->getId()); + + $sdd = (new SepaDirectDebit('DE89370400440532013000'))->setBic('COBADEFFXXX'); + $this->unzer->createPaymentType($sdd); + + $customer = $this->getMaximumCustomerInclShippingAddress()->setShippingAddress($this->getBillingAddress()); + $charge = $sdd->charge(119.0, 'EUR', self::RETURN_URL, $customer, null, null, $basket); + + $fetchedPayment = $this->unzer->fetchPayment($charge->getPaymentId()); + $this->assertEquals($basket->expose(), $fetchedPayment->getBasket()->expose()); + } + + /** + * Verify basket will be created and passed to the payment on authorize if it does not exist yet. + * + * @test + */ + public function authorizeTransactionsShouldCreateBasketIfItDoesNotExistYet(): void + { + $orderId = 'b' . self::generateRandomId(); + $basket = new Basket($orderId); + $basket->setTotalValueGross(99.99) + ->setCurrencyCode('EUR'); + + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross(99.99) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('title'); + $basket->addBasketItem($basketItem); + $this->assertEmpty($basket->getId()); + + /** @var Paypal $paypal */ + $paypal = $this->unzer->createPaymentType(new Paypal()); + $authorize = $paypal->authorize(123.4, 'EUR', 'https://unzer.com', null, null, null, $basket); + $this->assertNotEmpty($basket->getId()); + + $fetchedPayment = $this->unzer->fetchPayment($authorize->getPaymentId()); + $this->assertEquals($basket->expose(), $fetchedPayment->getBasket()->expose()); + } + + /** + * Verify basket will be created and passed to the payment on charge if it does not exist yet. + * + * @test + */ + public function chargeTransactionsShouldCreateBasketIfItDoesNotExistYet(): void + { + $orderId = 'b' . self::generateRandomId(); + $basket = new Basket($orderId); + $basket->setTotalValueGross(99.99) + ->setCurrencyCode('EUR'); + + $basketItem = (new BasketItem()) + ->setAmountPerUnitGross(99.99) + ->setQuantity(1) + ->setBasketItemReferenceId('item1') + ->setTitle('title'); + $basket->addBasketItem($basketItem); + $this->assertEmpty($basket->getId()); + + /** @var Paypal $paypal */ + $paypal = $this->unzer->createPaymentType(new Paypal()); + $charge = $paypal->charge(123.4, 'EUR', 'https://unzer.com', null, null, null, $basket); + $this->assertNotEmpty($basket->getId()); + + $fetchedPayment = $this->unzer->fetchPayment($charge->getPaymentId()); + $this->assertEquals($basket->expose(), $fetchedPayment->getBasket()->expose()); + } + + // + + // + + /** + * @return array + */ + public function basketItemWithInvalidUrlWillThrowAnErrorDP(): array + { + return [ + 'valid ' => [false, 'https://docs.unzer.com/card/card.png'], + 'valid null' => [false, null], + 'valid empty' => [false, ''], + 'invalid not available' => [true, 'https://files.readme.io/does-not-exist.jpg', ApiResponseCodes::API_ERROR_BASKET_ITEM_IMAGE_INVALID_URL] + ]; + } + + // +} diff --git a/vendor/unzerdev/php-sdk/test/integration/ConfigTest.php b/vendor/unzerdev/php-sdk/test/integration/ConfigTest.php new file mode 100644 index 0000000..ca522f7 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/ConfigTest.php @@ -0,0 +1,80 @@ +setCustomerType(CustomerTypes::B2C) + ->setCountry('DE'); + + $this->assertNull($config->getDataPrivacyConsent()); + $this->assertNull($config->getDataPrivacyDeclaration()); + $this->assertNull($config->getTermsAndConditions()); + + $this->getUnzerObject()->fetchConfig(new PaylaterInvoice(), $config); + + $this->assertNotNull($config->getDataPrivacyConsent()); + $this->assertNotNull($config->getDataPrivacyDeclaration()); + $this->assertNotNull($config->getTermsAndConditions()); + } + + /** + * Payment types that do not support config throw exception . + * + * @dataProvider verifyPaymentTypesWithNoConfigThrowExeptionDp + * + * @test + * + * @param mixed $paymentType + */ + public function verifyPaymentTypesWithNoConfigThrowExeption($paymentType) + { + $this->expectException(UnzerApiException::class); + $this->expectExceptionMessage('The given payment method config is not found.'); + $this->getUnzerObject()->fetchConfig($paymentType); + } + + /** Provide Payment types that have no config to test error case. + * @return array + */ + public function verifyPaymentTypesWithNoConfigThrowExeptionDp(): array + { + return [ + 'sofort' => [new Sofort()], + 'paypal' => [new Paypal()], + 'card' => [new Card(null, null, null)], + 'directDebit' => [new SepaDirectDebit(null)], + 'directDebitSecured' => [new SepaDirectDebitSecured(null)], + 'instalment' => [new InstallmentSecured(null)], + ]; + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/CustomerTest.php b/vendor/unzerdev/php-sdk/test/integration/CustomerTest.php index c75c619..139b7b4 100644 --- a/vendor/unzerdev/php-sdk/test/integration/CustomerTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/CustomerTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\ApiResponseCodes; @@ -33,6 +18,7 @@ use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\PaymentTypes\Paypal; use UnzerSDK\test\BaseIntegrationTest; + use function microtime; class CustomerTest extends BaseIntegrationTest @@ -89,9 +75,26 @@ public function maxCustomerCanBeCreatedAndFetched(): Customer return $customer; } + /** + * Verify shipping type can be set for shipping address of customer resource. + * + * @test + */ + public function customerWithShippingTypeCanBeCreatedAndFetched() + { + $customer = $this->getMaximumCustomerInclShippingAddress(); + $customer->getShippingAddress()->setShippingType('shippingType'); + + $this->unzer->createCustomer($customer); + $fetchedCustomer = $this->unzer->fetchCustomer($customer->getId()); + $this->assertEquals('shippingType', $fetchedCustomer->getShippingAddress()->getShippingType()); + } + /** * @param Customer $customer + * * @depends maxCustomerCanBeCreatedAndFetched + * * @test */ public function customerCanBeFetchedById(Customer $customer): void @@ -102,6 +105,7 @@ public function customerCanBeFetchedById(Customer $customer): void /** * @depends maxCustomerCanBeCreatedAndFetched + * * @test */ public function customerCanBeFetchedByCustomerId(): void @@ -116,7 +120,9 @@ public function customerCanBeFetchedByCustomerId(): void /** * @param Customer $customer + * * @depends maxCustomerCanBeCreatedAndFetched + * * @test */ public function customerCanBeFetchedByObject(Customer $customer): void @@ -128,7 +134,9 @@ public function customerCanBeFetchedByObject(Customer $customer): void /** * @param Customer $customer + * * @depends maxCustomerCanBeCreatedAndFetched + * * @test */ public function customerCanBeFetchedByObjectWithData(Customer $customer): void @@ -210,6 +218,7 @@ public function transactionShouldReferenceCustomerIfItExistAndItsIdHasBeenPassed * Customer can be updated. * * @depends maxCustomerCanBeCreatedAndFetched + * * @test * * @param Customer $customer @@ -230,6 +239,7 @@ public function customerShouldBeUpdateable(Customer $customer): void * Customer can be deleted. * * @depends maxCustomerCanBeCreatedAndFetched + * * @test * * @param Customer $customer @@ -423,5 +433,21 @@ public function maxRegisteredB2bCustomerCanBeCreatedAndFetched(): void $this->assertEquals($customer->expose(), $fetchedCustomer->expose()); } + /** + * Customer should contain clientIp set via header. + * + * @test + */ + public function customerShouldContainClientIpSetViaHeader() + { + $customer = $this->getMinimalCustomer(); + $clientIp = '123.123.123.123'; + $this->unzer->setClientIp($clientIp); + $this->unzer->createCustomer($customer); + + $fetchedCustomer = $this->unzer->fetchCustomer($customer->getId()); + $this->assertEquals($clientIp, $fetchedCustomer->getGeoLocation()->getClientIp()); + } + // } diff --git a/vendor/unzerdev/php-sdk/test/integration/DummyResource.php b/vendor/unzerdev/php-sdk/test/integration/DummyResource.php index c2fe9d0..dcbe1e6 100644 --- a/vendor/unzerdev/php-sdk/test/integration/DummyResource.php +++ b/vendor/unzerdev/php-sdk/test/integration/DummyResource.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Traits\CanRecur; diff --git a/vendor/unzerdev/php-sdk/test/integration/ExceptionTest.php b/vendor/unzerdev/php-sdk/test/integration/ExceptionTest.php index ad15e29..062a47a 100644 --- a/vendor/unzerdev/php-sdk/test/integration/ExceptionTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/ExceptionTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\ApiResponseCodes; diff --git a/vendor/unzerdev/php-sdk/test/integration/KeypairTest.php b/vendor/unzerdev/php-sdk/test/integration/KeypairTest.php index 16a69c3..6527211 100644 --- a/vendor/unzerdev/php-sdk/test/integration/KeypairTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/KeypairTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Unzer; @@ -36,6 +21,7 @@ class KeypairTest extends BaseIntegrationTest * Validate valid keys are accepted. * * @test + * * @dataProvider validKeysDataProvider * * @param string $key @@ -50,6 +36,7 @@ public function validKeysShouldBeExcepted($key): void * Validate invalid keys are revoked. * * @test + * * @dataProvider invalidKeysDataProvider * * @param string $key diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentCancelTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentCancelTest.php index 528768b..b889c0a 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentCancelTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentCancelTest.php @@ -1,34 +1,21 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\CancelReasonCodes; use UnzerSDK\Resources\PaymentTypes\Invoice; +use UnzerSDK\Resources\PaymentTypes\InvoiceSecured; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class PaymentCancelTest extends BaseIntegrationTest { @@ -65,6 +52,7 @@ public function doubleCancelOnAuthorizeShouldReturnEmptyArray(): void */ public function cancelOnChargeAndDoubleCancel(): void { + $this->useLegacyKey(); $charge = $this->createCharge(123.44); $payment = $this->unzer->fetchPayment($charge->getPaymentId()); $this->assertTrue($payment->isCompleted()); @@ -123,6 +111,7 @@ public function fullCancelOnPaymentWithAuthorizeAndMultipleChargesShouldBePossib */ public function partialCancelAndFullCancelOnSingleCharge(): void { + $this->useLegacyKey(); $charge = $this->createCharge(222.33); $payment = $this->unzer->fetchPayment($charge->getPaymentId()); $this->assertTrue($payment->isCompleted()); @@ -143,6 +132,7 @@ public function partialCancelAndFullCancelOnSingleCharge(): void * PHPLIB-228 - Case 4 + 5 * * @test + * * @dataProvider partCancelDataProvider * * @param float $amount @@ -174,6 +164,7 @@ public function partialCancelOnMultipleChargedAuthorization($amount, $numberCanc * PHPLIB-228 - Case 6 * * @test + * * @dataProvider fullCancelDataProvider * * @param float $amount @@ -223,6 +214,7 @@ public function fullCancelOnPartCanceledAuthorize(): void * PHPLIB-228 - Case 8 * * @test + * * @dataProvider fullCancelDataProvider * * @param float $amount The amount to be cancelled. @@ -249,6 +241,7 @@ public function fullCancelOnFullyChargedAuthorize($amount): void * PHPLIB-228 - Case 9 * * @test + * * @dataProvider fullCancelDataProvider * * @param $amount @@ -339,12 +332,14 @@ public function partCancelOnPartlyChargedAuthorizeWithAmountGtCharged(): void * PHPLIB-228 - Case 13 * * @test + * * @dataProvider fullCancelDataProvider * * @param float $amount */ public function fullCancelOnInitialInvoiceCharge($amount): void { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); /** @var Invoice $invoice */ $invoice = $this->unzer->createPaymentType(new Invoice()); $charge = $invoice->charge(100.0, 'EUR', self::RETURN_URL); @@ -365,6 +360,7 @@ public function fullCancelOnInitialInvoiceCharge($amount): void */ public function partCancelOnInitialInvoiceChargeShouldBePossible(): void { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); /** @var Invoice $invoice */ $invoice = $this->unzer->createPaymentType(new Invoice()); $charge = $invoice->charge(100.0, 'EUR', self::RETURN_URL); @@ -377,6 +373,81 @@ public function partCancelOnInitialInvoiceChargeShouldBePossible(): void $this->assertAmounts($payment, 50.0, 0.0, 50.0, 0.0); } + /** + * Verify part cancel on initial ivs charge (reversal) + * + * @test + */ + public function partCancelOnInitialInvoiceSecuredChargeShouldCancelMaxUnpaidAmount(): void + { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); + /** @var InvoiceSecured $invoiceSecured */ + $invoiceSecured = $this->unzer->createPaymentType(new InvoiceSecured()); + + $customer = $this->getMaximumCustomer(); + $customer->setShippingAddress($customer->getBillingAddress()); + + $basket = $this->createBasket(); + $invoiceId = 'i' . self::generateRandomId(); + $charge = $invoiceSecured->charge(100.0, 'EUR', self::RETURN_URL, $customer, $basket->getOrderId(), null, $basket, null, $invoiceId); + $charge->getPayment()->ship(); + $paymentId = $charge->getPaymentId(); + + $this->assertTrue($charge->isPending()); // Set your break point here. + $payment = $this->unzer->fetchPayment($charge->getPaymentId()); + if (count($payment->getCharges()) !== 2) { + $testDescription = 'This test needs assistance: + To perform this test properly, first set a breakpoint after charge, before the payment gets fetched. + Then perform a receipt manually over 60€ on the "reservation". + After that this test can be continued'; + $this->markTestSkipped($testDescription); + } + $this->assertTrue($payment->isCompleted()); + $this->assertAmounts($payment, 0, 100, 100.0, 0); + + $this->assertCount(2, $payment->cancelAmount(50.0)); + $this->assertTrue($payment->isCompleted()); + $this->assertAmounts($payment, 0, 50.0, 100.0, 50.0); + } + + /** + * Verify skip cancel on initial ivs charge + * + * @test + */ + public function fullCancelOnPaidInvoiceSecuredPaymentShouldBePossible(): void + { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); + /** @var InvoiceSecured $invoiceSecured */ + $invoiceSecured = $this->unzer->createPaymentType(new InvoiceSecured()); + + $customer = $this->getMaximumCustomer(); + $customer->setShippingAddress($customer->getBillingAddress()); + + $basket = $this->createBasket(); + $invoiceId = 'i' . self::generateRandomId(); + $charge = $invoiceSecured->charge(100.0, 'EUR', self::RETURN_URL, $customer, $basket->getOrderId(), null, $basket, null, $invoiceId); + $charge->getPayment()->ship(); + $paymentId = $charge->getPaymentId(); + + $this->assertTrue($charge->isPending()); // Set your break point here. + $payment = $this->unzer->fetchPayment($charge->getPaymentId()); + if (count($payment->getCharges()) !== 2) { + $testDescription = 'This test needs assistance: + To perform this test properly, first set a breakpoint after charge, before the payment gets fetched. + Then perform a receipt manually over 100€ on the "reservation". + After that this test can be continued'; + $this->markTestSkipped($testDescription); + } + $this->assertTrue($payment->isCompleted()); + $this->assertAmounts($payment, 0, 100.0, 100.0, 0); + + $cancellations = $payment->cancelAmount(); + $this->assertCount(1, $cancellations); + $this->assertTrue($payment->isCompleted()); + $this->assertAmounts($payment, 0, 0, 100.0, 100.0); + } + /** * Verify cancelling more than was charged. * PHPLIB-228 - Case 15 @@ -385,6 +456,7 @@ public function partCancelOnInitialInvoiceChargeShouldBePossible(): void */ public function cancelMoreThanWasCharged(): void { + $this->useLegacyKey(); $charge = $this->createCharge(50.0); $payment = $this->unzer->fetchPayment($charge->getPaymentId()); $this->assertTrue($payment->isCompleted()); diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTest.php index ccf24ff..b21ef76 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\ApiResponseCodes; @@ -159,7 +144,7 @@ public function paymentChargeOnAuthorizeShouldTakeResourceIds(): void { $card = $this->unzer->createPaymentType($this->createCardObject()); $authorization = $this->unzer->authorize(100.00, 'EUR', $card, 'http://unzer.com', null, null, null, null, false); - $charge = $this->unzer->chargePayment($authorization->getPaymentId(), null, 'EUR', 'o' . self::generateRandomId(), 'i' . self::generateRandomId()); + $charge = $this->unzer->chargePayment($authorization->getPaymentId(), null, 'o' . self::generateRandomId(), 'i' . self::generateRandomId()); $this->assertNotEmpty($charge->getId()); } diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/AlipayTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/AlipayTest.php index ff4147f..5f4ec9c 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/AlipayTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/AlipayTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -64,6 +49,7 @@ public function alipayShouldBeCreatableAndFetchable(): Alipay * @param Alipay $alipay * * @return Charge + * * @depends alipayShouldBeCreatableAndFetchable */ public function alipayShouldBeAbleToCharge(Alipay $alipay): Charge @@ -82,6 +68,7 @@ public function alipayShouldBeAbleToCharge(Alipay $alipay): Charge * @test * * @param Alipay $alipay + * * @depends alipayShouldBeCreatableAndFetchable */ public function alipayShouldNotBeAuthorizable(Alipay $alipay): void diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/ApplepayTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/ApplepayTest.php index aaf3d53..5a7a613 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/ApplepayTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/ApplepayTest.php @@ -3,26 +3,8 @@ * This class defines integration tests to verify interface and * functionality of the payment method Applepay. * - * Copyright (C) 2021 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author David Owusu - * - * @package UnzerSDK - * */ namespace UnzerSDK\test\integration\PaymentTypes; @@ -34,6 +16,11 @@ class ApplepayTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->markTestSkipped('Testdata need to be updated.'); + } + /** * Verify applepay can be created and fetched. * @@ -407,14 +394,14 @@ public function applepayChargeCanBeCanceled(): void private function createApplepayObject(): Applepay { $applepayAutorization = '{ - "version": "EC_v1", - "data": "TwQBBorcg6aEb5eidSJm5fNG5sih+R+xgeJbvAX8oMQ7EXhIWOE+ACnvBFHOkZOjI+ump/zVrBXTMRYSw32WMWXPuiRDlYu8DMNuV3qKrbC+G5Du5qfxsm8BxJCXkc/DqtGqc70o8TJCn9lM5ePQjS3io4HDonkN4b4L20GfyEVW1QyvozaMa1u7/gaS6OhhXNk65Z70+xCZlOGmgDtgcdZK+TQIYgRLzyP+1+mpqd61pQ3vJELB8ngMoleCGd1DHx2kVWsudZQ5q97sUjpZV2ySfPXLMhWHYYfvcvSx3dKDAywUoR8clUeDKtoZ4LsBO/B8XM/T4JKnFmWfr7Z25E88vfMWIs8JpxIC5OKAPZfVZoDSNs+4LR+twVxlD5B2xkvG6ln6j4cQ+CFmiq9FPSDgQJsn8O7K9Ag0odXiK6mZczOWt2HCHaw0thF/WpudObVlmw5NN1r54/Jxoichp+DJ2Hl1NJqDHKS1fNyXQcR5jqID7QOcpQi0gE332bOTIz/xe+u328GMCl6Rms3JJxFnnskfEA7nicIH8DLFeSbG8jloLyKBBLk=", - "signature": "MIAGCSqGSIb3DQEHAqCAMIACAQExDzANBglghkgBZQMEAgEFADCABgkqhkiG9w0BBwEAAKCAMIID5jCCA4ugAwIBAgIIaGD2mdnMpw8wCgYIKoZIzj0EAwIwejEuMCwGA1UEAwwlQXBwbGUgQXBwbGljYXRpb24gSW50ZWdyYXRpb24gQ0EgLSBHMzEmMCQGA1UECwwdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTMB4XDTE2MDYwMzE4MTY0MFoXDTIxMDYwMjE4MTY0MFowYjEoMCYGA1UEAwwfZWNjLXNtcC1icm9rZXItc2lnbl9VQzQtU0FOREJPWDEUMBIGA1UECwwLaU9TIFN5c3RlbXMxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEgjD9q8Oc914gLFDZm0US5jfiqQHdbLPgsc1LUmeY+M9OvegaJajCHkwz3c6OKpbC9q+hkwNFxOh6RCbOlRsSlaOCAhEwggINMEUGCCsGAQUFBwEBBDkwNzA1BggrBgEFBQcwAYYpaHR0cDovL29jc3AuYXBwbGUuY29tL29jc3AwNC1hcHBsZWFpY2EzMDIwHQYDVR0OBBYEFAIkMAua7u1GMZekplopnkJxghxFMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUI/JJxE+T5O8n5sT2KGw/orv9LkswggEdBgNVHSAEggEUMIIBEDCCAQwGCSqGSIb3Y2QFATCB/jCBwwYIKwYBBQUHAgIwgbYMgbNSZWxpYW5jZSBvbiB0aGlzIGNlcnRpZmljYXRlIGJ5IGFueSBwYXJ0eSBhc3N1bWVzIGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJsZSBzdGFuZGFyZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRlIHBvbGljeSBhbmQgY2VydGlmaWNhdGlvbiBwcmFjdGljZSBzdGF0ZW1lbnRzLjA2BggrBgEFBQcCARYqaHR0cDovL3d3dy5hcHBsZS5jb20vY2VydGlmaWNhdGVhdXRob3JpdHkvMDQGA1UdHwQtMCswKaAnoCWGI2h0dHA6Ly9jcmwuYXBwbGUuY29tL2FwcGxlYWljYTMuY3JsMA4GA1UdDwEB/wQEAwIHgDAPBgkqhkiG92NkBh0EAgUAMAoGCCqGSM49BAMCA0kAMEYCIQDaHGOui+X2T44R6GVpN7m2nEcr6T6sMjOhZ5NuSo1egwIhAL1a+/hp88DKJ0sv3eT3FxWcs71xmbLKD/QJ3mWagrJNMIIC7jCCAnWgAwIBAgIISW0vvzqY2pcwCgYIKoZIzj0EAwIwZzEbMBkGA1UEAwwSQXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcNMTQwNTA2MjM0NjMwWhcNMjkwNTA2MjM0NjMwWjB6MS4wLAYDVQQDDCVBcHBsZSBBcHBsaWNhdGlvbiBJbnRlZ3JhdGlvbiBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATwFxGEGddkhdUaXiWBB3bogKLv3nuuTeCN/EuT4TNW1WZbNa4i0Jd2DSJOe7oI/XYXzojLdrtmcL7I6CmE/1RFo4H3MIH0MEYGCCsGAQUFBwEBBDowODA2BggrBgEFBQcwAYYqaHR0cDovL29jc3AuYXBwbGUuY29tL29jc3AwNC1hcHBsZXJvb3RjYWczMB0GA1UdDgQWBBQj8knET5Pk7yfmxPYobD+iu/0uSzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFLuw3qFYM4iapIqZ3r6966/ayySrMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly9jcmwuYXBwbGUuY29tL2FwcGxlcm9vdGNhZzMuY3JsMA4GA1UdDwEB/wQEAwIBBjAQBgoqhkiG92NkBgIOBAIFADAKBggqhkjOPQQDAgNnADBkAjA6z3KDURaZsYb7NcNWymK/9Bft2Q91TaKOvvGcgV5Ct4n4mPebWZ+Y1UENj53pwv4CMDIt1UQhsKMFd2xd8zg7kGf9F3wsIW2WT8ZyaYISb1T4en0bmcubCYkhYQaZDwmSHQAAMYIBjDCCAYgCAQEwgYYwejEuMCwGA1UEAwwlQXBwbGUgQXBwbGljYXRpb24gSW50ZWdyYXRpb24gQ0EgLSBHMzEmMCQGA1UECwwdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTAghoYPaZ2cynDzANBglghkgBZQMEAgEFAKCBlTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgxNjA4MTFaMCoGCSqGSIb3DQEJNDEdMBswDQYJYIZIAWUDBAIBBQChCgYIKoZIzj0EAwIwLwYJKoZIhvcNAQkEMSIEIOkz+k59f4rvza+A8zqMCZevZJgynnkAoaVcIBhzE7uxMAoGCCqGSM49BAMCBEcwRQIgTpDgEPz4evB42QV7YrUsjg+n/6ObYCPO8w3zEbswOM8CIQDjvo3vluxulxHB+mTrtr7Gnyoc8ccN6rzuXvFG2wKnbAAAAAAAAA==", - "header": { - "ephemeralPublicKey": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEW7hYAxjCeE/r9SSRX/hJsfO+VxLvUqIzyeGn6lZ1v/pYYS66Bz0dsSzoMMZg8G32TAPXUr97AD4zCXfcQoZaOA==", - "publicKeyHash": "zqO5Y3ldWWm4NnIkfGCvJILw30rp3y46Jsf21gE8CNg=", - "transactionId": "94f6b37149ae2098efb287ed0ade704284cff3f672ef7f0dc17614b31e926b9d" - } + "version": "EC_v1", + "data": "EGOe1iZx081t+D0FLES+Ubyr2a3RfDQptIm0ocT223JLk9dxBLZDAMIwnCInsxN6YLGXQzB8Hn1CSeD2VsMr9E3gvl89bcolrP0nvmvgyQPvN5dt3jmF9G7m0OQoiRdOPVS1fA1cJB7dq3Xg0paMPfimdEepCs3GAGvrmF8nEZEq+F5qcouEX0F6AAcyIf5RETrJGZM+V8fG+9FxYh4H4yu8s6N3z5JpAjLx+rl2/fOCMqBBhaHkjhBsCHLpuJL6YMgYHh++AtooBAMOuctnomKdYX+OuxTY1k2S3DF7vvErI/1Daq4e8bbbC/fk8OqYxiDLSNXTzerPPKCjucGDkUlw+ZUIif2BVPDg1a7QsfS0JNNFP4eBWVezZrLt6ce/0cApLaRsimoSOCPYmw==", + "signature": "MIAGCSqGSIb3DQEHAqCAMIACAQExDzANBglghkgBZQMEAgEFADCABgkqhkiG9w0BBwEAAKCAMIID5DCCA4ugAwIBAgIIWdihvKr0480wCgYIKoZIzj0EAwIwejEuMCwGA1UEAwwlQXBwbGUgQXBwbGljYXRpb24gSW50ZWdyYXRpb24gQ0EgLSBHMzEmMCQGA1UECwwdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTMB4XDTIxMDQyMDE5MzcwMFoXDTI2MDQxOTE5MzY1OVowYjEoMCYGA1UEAwwfZWNjLXNtcC1icm9rZXItc2lnbl9VQzQtU0FOREJPWDEUMBIGA1UECwwLaU9TIFN5c3RlbXMxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEgjD9q8Oc914gLFDZm0US5jfiqQHdbLPgsc1LUmeY+M9OvegaJajCHkwz3c6OKpbC9q+hkwNFxOh6RCbOlRsSlaOCAhEwggINMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUI/JJxE+T5O8n5sT2KGw/orv9LkswRQYIKwYBBQUHAQEEOTA3MDUGCCsGAQUFBzABhilodHRwOi8vb2NzcC5hcHBsZS5jb20vb2NzcDA0LWFwcGxlYWljYTMwMjCCAR0GA1UdIASCARQwggEQMIIBDAYJKoZIhvdjZAUBMIH+MIHDBggrBgEFBQcCAjCBtgyBs1JlbGlhbmNlIG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBjb25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZpY2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMDYGCCsGAQUFBwIBFipodHRwOi8vd3d3LmFwcGxlLmNvbS9jZXJ0aWZpY2F0ZWF1dGhvcml0eS8wNAYDVR0fBC0wKzApoCegJYYjaHR0cDovL2NybC5hcHBsZS5jb20vYXBwbGVhaWNhMy5jcmwwHQYDVR0OBBYEFAIkMAua7u1GMZekplopnkJxghxFMA4GA1UdDwEB/wQEAwIHgDAPBgkqhkiG92NkBh0EAgUAMAoGCCqGSM49BAMCA0cAMEQCIHShsyTbQklDDdMnTFB0xICNmh9IDjqFxcE2JWYyX7yjAiBpNpBTq/ULWlL59gBNxYqtbFCn1ghoN5DgpzrQHkrZgTCCAu4wggJ1oAMCAQICCEltL786mNqXMAoGCCqGSM49BAMCMGcxGzAZBgNVBAMMEkFwcGxlIFJvb3QgQ0EgLSBHMzEmMCQGA1UECwwdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTMB4XDTE0MDUwNjIzNDYzMFoXDTI5MDUwNjIzNDYzMFowejEuMCwGA1UEAwwlQXBwbGUgQXBwbGljYXRpb24gSW50ZWdyYXRpb24gQ0EgLSBHMzEmMCQGA1UECwwdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxEzARBgNVBAoMCkFwcGxlIEluYy4xCzAJBgNVBAYTAlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8BcRhBnXZIXVGl4lgQd26ICi7957rk3gjfxLk+EzVtVmWzWuItCXdg0iTnu6CP12F86Iy3a7ZnC+yOgphP9URaOB9zCB9DBGBggrBgEFBQcBAQQ6MDgwNgYIKwYBBQUHMAGGKmh0dHA6Ly9vY3NwLmFwcGxlLmNvbS9vY3NwMDQtYXBwbGVyb290Y2FnMzAdBgNVHQ4EFgQUI/JJxE+T5O8n5sT2KGw/orv9LkswDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS7sN6hWDOImqSKmd6+veuv2sskqzA3BgNVHR8EMDAuMCygKqAohiZodHRwOi8vY3JsLmFwcGxlLmNvbS9hcHBsZXJvb3RjYWczLmNybDAOBgNVHQ8BAf8EBAMCAQYwEAYKKoZIhvdjZAYCDgQCBQAwCgYIKoZIzj0EAwIDZwAwZAIwOs9yg1EWmbGG+zXDVspiv/QX7dkPdU2ijr7xnIFeQreJ+Jj3m1mfmNVBDY+d6cL+AjAyLdVEIbCjBXdsXfM4O5Bn/Rd8LCFtlk/GcmmCEm9U+Hp9G5nLmwmJIWEGmQ8Jkh0AADGCAYwwggGIAgEBMIGGMHoxLjAsBgNVBAMMJUFwcGxlIEFwcGxpY2F0aW9uIEludGVncmF0aW9uIENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUwIIWdihvKr0480wDQYJYIZIAWUDBAIBBQCggZUwGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMjExMTEwMTAxNTU4WjAqBgkqhkiG9w0BCTQxHTAbMA0GCWCGSAFlAwQCAQUAoQoGCCqGSM49BAMCMC8GCSqGSIb3DQEJBDEiBCBeyyDzab9pZ4dwoq6cLrl9Cbho/Eh88vKGYEa8C2p+5TAKBggqhkjOPQQDAgRHMEUCIHUpR3i72URhoyaOyqyoA26YxrY1RDf7NmamuUIuIHtzAiEAhtKcwlAg4wo+SCu+RTTngb7WWmCCdQ9zJ2wC3UKZzj4AAAAAAAA=", + "header": { + "ephemeralPublicKey": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECjiINGVdR1tbzHQ1jOpdn0+GgSsxRsFkp2uvd7XK+yXNvIj8fAA0JDWZ41VXdg3578qMOu1FMdGbaL7KS28/qw==", + "publicKeyHash": "zqO5Y3ldWWm4NnIkfGCvJILw30rp3y46Jsf21gE8CNg=", + "transactionId": "91ce5ad365a5bfaea7db143e407c8b2b183ddbc5f256143a9685c70fedd1ce75" + } }'; $applepay = new Applepay(null, null, null, null); diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/BancontactTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/BancontactTest.php index e7404c4..f5466c6 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/BancontactTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/BancontactTest.php @@ -1,31 +1,15 @@ - * @author Florian Evertz - * @author Simon Gabriel - * - * @package UnzerSDK\test\integration\PaymentTypes + @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -64,7 +48,7 @@ public function bancontactShouldThrowExceptionOnAuthorize(): void $bancontact = $this->unzer->createPaymentType(new Bancontact()); $this->unzer->authorize(100.0, 'EUR', $bancontact, self::RETURN_URL); } - + /** * Verify that Bancontact is chargeable * diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/CardTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/CardTest.php index c25bff7..7b585fe 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/CardTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/CardTest.php @@ -1,37 +1,25 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; +use UnzerSDK\Constants\ExemptionType; use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\Resources\EmbeddedResources\CardTransactionData; use UnzerSDK\Resources\EmbeddedResources\CardDetails; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Card; +use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\Services\ValueService; use UnzerSDK\test\BaseIntegrationTest; @@ -88,13 +76,14 @@ public function cardShouldBeCreatable(string $cardNumber, CardDetails $expectedC public function cardShouldUseEmail($email, $expected) { // when. - /** @var Card $card */ $card = $this->createCardObject('4711100000000000'); $this->assertNull($card->getId()); $this->assertNull($card->getEmail()); // default value is set. // then. $card->setEmail($email); // override email. + + /** @var Card $card */ $card = $this->unzer->createPaymentType($card); $this->assertNotNull($card->getId()); $this->assertEquals($email, $card->getEmail()); @@ -112,15 +101,19 @@ public function cardShouldUseEmail($email, $expected) * * @dataProvider supportedRecurrenceTypesDP * - * @param $recurrenceType + * @param $recurrenceType + * @param mixed $isrecurring * * @throws UnzerApiException */ - public function cardShouldBeChargeableWithRecurrenceType($recurrenceType): void + public function cardShouldBeChargeableWithRecurrenceType($recurrenceType, $isrecurring): void { + $this->useNon3dsKey(); $card = $this->createCardObject('4711100000000000'); /** @var Card $card */ $card = $this->unzer->createPaymentType($card); + $this->assertNotTrue($card->isRecurring()); + $chargeResponse = $card->charge('99.99', 'EUR', 'https://unzer.com', null, null, null, null, null, null, null, $recurrenceType); $this->assertEquals($recurrenceType, $chargeResponse->getRecurrenceType()); $fetchedCharge = $this->unzer->fetchChargeById($chargeResponse->getPaymentId(), $chargeResponse->getId()); @@ -129,6 +122,9 @@ public function cardShouldBeChargeableWithRecurrenceType($recurrenceType): void $this->assertNotNull($fetchedCharge->getAdditionalTransactionData()); } $this->assertEquals($recurrenceType, $fetchedCharge->getRecurrenceType()); + + $fetchedCard = $this->getUnzerObject()->fetchPaymentType($card->getId()); + $this->assertTrue($fetchedCard->isRecurring()); } /** @@ -151,6 +147,21 @@ public function invalidRecurrenceTypeShouldThrowApiException($recurrenceType): v $card->charge('99.99', 'EUR', 'https://unzer.com', null, null, null, null, null, null, null, $recurrenceType); } + /** + * Invalid expiry date should throw API exception. + * + * @test + */ + public function invalidExpiryDateShouldThrowApiException(): void + { + $card = $this->createCardObject('4711100000000000'); + $card->setExpiryDate('01/2001'); + + /** @var Card $card */ + $this->expectException(UnzerApiException::class); + $this->unzer->createPaymentType($card); + } + /** * Card should be chargeable with recurrence type. * @@ -176,7 +187,7 @@ public function cardCanBeAuthorizedWithRecurrenceType($recurrenceType): void } $this->assertEquals($recurrenceType, $fetchedCharge->getRecurrenceType()); } - + /** * Verify that an invalid email cause an UnzerApiException. * @@ -224,7 +235,7 @@ public function cardCanBeUpdatedWithEmail() // then /** @var Card $updatedCard */ $updatedCard = $this->unzer->fetchPaymentType($fetchedCard->getId()); - $this->assertRegExp('/0000$/', $updatedCard->getNumber()); + $this->assertMatchesRegularExpression('/0000$/', $updatedCard->getNumber()); $this->assertEquals('test2@test.com', $updatedCard->getEmail()); } @@ -244,6 +255,57 @@ public function cardWith3dsFlagShouldSetItAlsoInTransactions(): void $this->assertFalse($charge->isCard3ds()); } + /** + * Verfify card transaction can be used with exemptionType + * + * @test + */ + public function cardTransactionAcceptsExemptionType(): void + { + $card = $this->createCardObject(); + /** @var Card $card */ + $card = $this->unzer->createPaymentType($card); + $charge = new Charge(12.34, 'EUR', 'https://docs.unzer.com'); + $cardTransactionData = (new CardTransactionData()) + ->setExemptionType(ExemptionType::LOW_VALUE_PAYMENT); + + $charge->setCardTransactionData($cardTransactionData); + $this->getUnzerObject()->performCharge($charge, $card); + + // Verify lvp value gets mapped from response + $fetchedCharge = $this->unzer->fetchChargeById($charge->getPaymentId(), $charge->getId()); + $this->assertEquals(ExemptionType::LOW_VALUE_PAYMENT, $fetchedCharge->getCardTransactionData()->getExemptionType()); + } + + /** + * Verify card transaction returns Liability Shift Indicator. + * + * @test + * + * @dataProvider cardTransactionReturnsLiabilityIndicatorDP() + * + * @param mixed $pan + */ + public function cardTransactionReturnsLiabilityIndicator($pan): void + { + $this->markTestSkipped('Requires a special config for card.'); + $card = $this->createCardObject()->setNumber($pan)->set3ds(false); + /** @var Card $card */ + $card = $this->unzer->createPaymentType($card); + $charge = $card->charge(12.34, 'EUR', 'https://docs.unzer.com'); + + // Verify Liability Indicator in response. + $this->assertNotNull($charge->getAdditionalTransactionData()); + $this->assertNotNull($charge->getAdditionalTransactionData()->card->liability); + + // Verify Liability Indicator In payment response. + $fetchedPayment = $this->unzer->fetchPayment($charge->getPaymentId()); + $paymentCharge = $fetchedPayment->getCharge('s-chg-1', true); + $this->assertNotNull($paymentCharge->getAdditionalTransactionData()->card->liability); + + $this->getUnzerObject()->fetchCharge($charge); + } + /** * Verify that the card can perform an authorization with a card. * @@ -593,11 +655,11 @@ public function cardShouldBeCreatableDP(): array { $cardDetailsA = new CardDetails(); $cardDetailsAObj = (object)[ - 'cardType' => 'CLASSIC', - 'account' => 'CREDIT', - 'countryIsoA2' => 'RU', - 'countryName' => 'RUSSIAN FEDERATION', - 'issuerName' => '', + 'cardType' => 'STANDARD', + 'account' => 'DEBIT', + 'countryIsoA2' => 'BE', + 'countryName' => 'BELGIUM', + 'issuerName' => 'MASTERCARD EUROPE', 'issuerUrl' => '', 'issuerPhoneNumber' => '' ]; @@ -616,7 +678,7 @@ public function cardShouldBeCreatableDP(): array $cardDetailsB->handleResponse($cardDetailsBObj); return [ - 'card type set' => ['4012001037461114', $cardDetailsA], + 'card type set' => ['6799851000000032', $cardDetailsA], 'issuer data set' => ['5453010000059543', $cardDetailsB] ]; } @@ -634,19 +696,29 @@ public function cardShouldUseEmailDataProvider() public function supportedRecurrenceTypesDP(): array { return [ - 'null' => [null], - 'oneclick' => ['oneclick'], - 'scheduled' => ['scheduled'], - 'unscheduled' => ['unscheduled'] + 'null' => [null, false], + 'empty string' => ['', false], + 'oneclick' => ['oneclick', false], + 'scheduled' => ['scheduled', true], + 'unscheduled' => ['unscheduled', true] ]; } public function invalidRecurrenceTypesDP(): array { return [ - 'empty' => [''], 'invalid string' => ['invalid recurrence Type'], 'number' => [42], ]; } + + public function cardTransactionReturnsLiabilityIndicatorDP() + { + return [ + '6799851000000032' => ['6799851000000032'], + '5453010000059543' => ['5453010000059543'], + '4711100000000000' => ['4711100000000000'], + '4012001037461114' => ['4012001037461114'] + ]; + } } diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/EPSTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/EPSTest.php index c0bfabb..8faa874 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/EPSTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/EPSTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -65,6 +50,7 @@ public function epsShouldBeCreatable(): EPS * @test * * @param EPS $eps + * * @depends epsShouldBeCreatable */ public function epsShouldThrowExceptionOnAuthorize(EPS $eps): void @@ -79,6 +65,7 @@ public function epsShouldThrowExceptionOnAuthorize(EPS $eps): void * Verify that eps payment type is chargeable. * * @test + * * @depends epsShouldBeCreatable * * @param EPS $eps @@ -93,13 +80,14 @@ public function epsShouldBeChargeable(EPS $eps): void $this->assertTrue($charge->getPayment()->isPending()); $fetchCharge = $this->unzer->fetchChargeById($charge->getPayment()->getId(), $charge->getId()); - $this->assertEquals($charge->expose(), $fetchCharge->expose()); + $this->assertEquals($charge->setCard3ds(false)->expose(), $fetchCharge->expose()); } /** * Verify eps payment type can be fetched. * * @test + * * @depends epsShouldBeCreatable * * @param EPS $eps diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/GiropayTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/GiropayTest.php index 7b847e8..c6b5351 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/GiropayTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/GiropayTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -76,7 +61,7 @@ public function giroPayShouldBeChargeable(): void $this->assertNotEmpty($charge->getRedirectUrl()); $fetchCharge = $this->unzer->fetchChargeById($charge->getPayment()->getId(), $charge->getId()); - $this->assertEquals($charge->expose(), $fetchCharge->expose()); + $this->assertEquals($charge->setCard3ds(false)->expose(), $fetchCharge->expose()); } /** diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/GooglePayTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/GooglePayTest.php new file mode 100644 index 0000000..9f6a903 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/GooglePayTest.php @@ -0,0 +1,362 @@ +getTestToken())) { + $this->markTestSkipped('Skiped by default. To run test locally, overwrite a googlepay payment token + in `test/Fixtures/jsonData/googlePay/googlepayToken.json`.'); + } + parent::setUp(); + } + + /** + * Verify that googlepay payment type resource can be created. + * + * @test + * + * @return BasePaymentType + */ + public function googlePayShouldBeCreatable(): BasePaymentType + { + $googlePayToken = $this->getTestToken(); + $googlepay = $this->createGooglepayObjectFromToken($googlePayToken); + + $this->unzer->createPaymentType($googlepay); + + $this->assertInstanceOf(Googlepay::class, $googlepay); + $this->assertNotNull($googlepay->getId()); + $this->assertSame($this->unzer, $googlepay->getUnzerObject()); + + $geoLocation = $googlepay->getGeoLocation(); + $this->assertNotEmpty($geoLocation->getClientIp()); + $this->assertNotEmpty($geoLocation->getCountryCode()); + + return $googlepay; + } + + /** + * Verify that a googlepay resource can be fetched from the api using its id. + * + * @test + * + * @depends googlePayShouldBeCreatable + * + * @param mixed $type + */ + public function googlepayCanBeFetched($type): void + { + $this->assertNotNull($type->getId()); + + /** @var Googlepay $fetchedGooglepay */ + $fetchedGooglepay = $this->unzer->fetchPaymentType($type->getId()); + $this->assertNotNull($fetchedGooglepay->getId()); + $this->assertEquals($type->getNumber(), $fetchedGooglepay->getNumber()); + $this->assertEquals($type->getExpiryDate(), $fetchedGooglepay->getExpiryDate()); + } + + /** + * Verify that authorization can be performed with Google Pay. + * + * @test + * + * @depends googlePayShouldBeCreatable + * + * @param mixed $type + */ + public function googlepayCanPerformAuthorization($type): Authorization + { + $authorizationRequest = $this->getLvpAuthorizationObject(); + $authorization = $this->getUnzerObject() + ->performAuthorization( + $authorizationRequest, + $type + ); + + // verify authorization has been created + $this->assertNotNull($authorization->getId()); + + // verify payment object has been created + $payment = $authorization->getPayment(); + $this->assertNotNull($payment); + $this->assertNotNull($payment->getId()); + + // verify resources are linked properly + $this->assertSame($authorization, $payment->getAuthorization()); + $this->assertSame($type, $payment->getPaymentType()); + + // verify the payment object has been updated properly + $this->assertAmounts($payment, 2.99, 0.0, 2.99, 0.0); + $this->assertTrue($payment->isPending()); + $this->assertTrue($authorization->isSuccess()); + + return $authorization; + } + + /** + * Verify that authorization can be charged with Google Pay. + * + * @test + * + * @depends googlepayCanPerformAuthorization + * + * @param Authorization $authorization + */ + public function authorizationCanBeCharged(Authorization $authorization): Payment + { + $charge = $this->getUnzerObject() + ->performChargeOnPayment( + $authorization->getPayment(), + new Charge() + ); + + // verify charge has been created + $this->assertNotNull($charge->getId()); + + // verify payment object has been created + $payment = $charge->getPayment(); + $this->assertNotNull($payment); + $this->assertNotNull($payment->getId()); + + // verify resources are linked properly + $this->assertSame($charge, $payment->getCharge('s-chg-1')); + $this->assertSame($authorization->getPayment()->getPaymentType(), $payment->getPaymentType()); + + // verify the payment object has been updated properly + $this->assertAmounts($payment, 0, 2.99, 2.99, 0.0); + $this->assertTrue($payment->isCompleted()); + $this->assertTrue($charge->isSuccess()); + + return $payment; + } + + /** + * Verify the googlepay can perform charges and creates a payment object doing so. + * + * @test + * + * @depends googlePayShouldBeCreatable + * + * @param mixed $type + */ + public function canPerformCharge($type): void + { + $charge = $this->getUnzerObject() + ->performCharge( + $this->getLvpChargeObject(), + $type + ); + + $fetchedType = $this->unzer->fetchPaymentType($type->getId()); + + // verify charge has been created + $this->assertNotNull($charge->getId()); + + // verify payment object has been created + $payment = $charge->getPayment(); + $this->assertNotNull($payment); + $this->assertNotNull($payment->getId()); + + // verify resources are linked properly + $this->assertEquals($charge->expose(), $payment->getCharge($charge->getId())->expose()); + + // verify the payment object has been updated properly + $this->assertAmounts($payment, 0.0, 2.99, 2.99, 0.0); + $this->assertTrue($payment->isCompleted()); + } + + /** + * Verify the googlepay can charge part of the authorized amount and the payment state is updated accordingly. + * + * @test + */ + public function partialChargeAfterAuthorization(): void + { + $googlepay = $this->createGooglepayObjectFromToken($this->getTestToken()); + /** @var Googlepay $googlepay */ + $googlepay = $this->unzer->createPaymentType($googlepay); + $authorization = $this->getUnzerObject() + ->performAuthorization( + $this->getLvpAuthorizationObject(), + $googlepay + ); + + $payment = $authorization->getPayment(); + $this->assertAmounts($payment, 2.99, 0.0, 2.99, 0.0); + $this->assertTrue($payment->isPending()); + + $charge = $this->unzer->performChargeOnPayment($payment->getId(), new Charge(1)); + $payment1 = $charge->getPayment(); + $this->assertAmounts($payment1, 1.99, 1, 2.99, 0.0); + $this->assertTrue($payment1->isPartlyPaid()); + + $charge = $this->unzer->performChargeOnPayment($payment->getId(), new Charge(1)); + $payment2 = $charge->getPayment(); + $this->assertAmounts($payment2, 0.99, 2, 2.99, 0.0); + $this->assertTrue($payment2->isPartlyPaid()); + + $charge = $this->unzer->performChargeOnPayment($payment->getId(), new Charge(0.99)); + $payment3 = $charge->getPayment(); + $this->assertAmounts($payment3, 00.0, 2.99, 2.99, 0.0); + $this->assertTrue($payment3->isCompleted()); + } + + /** + * Verify that an exception is thrown when trying to charge more than authorized. + * + * @test + */ + public function exceptionShouldBeThrownWhenChargingMoreThenAuthorized(): void + { + $googlepay = $this->createGooglepayObjectFromToken($this->getTestToken()); + /** @var Googlepay $googlepay */ + $googlepay = $this->unzer->createPaymentType($googlepay); + $authorization = $this->getUnzerObject() + ->performAuthorization( + $this->getLvpAuthorizationObject(), + $googlepay + ); + $payment = $authorization->getPayment(); + $this->assertAmounts($payment, 2.99, 0.0, 2.99, 0.0); + $this->assertTrue($payment->isPending()); + + $charge = $this->unzer->performChargeOnPayment($payment->getId(), new Charge(1.99)); + $payment1 = $charge->getPayment(); + $this->assertAmounts($payment1, 1, 1.99, 2.99, 0.0); + $this->assertTrue($payment1->isPartlyPaid()); + + $this->expectException(UnzerApiException::class); + $this->expectExceptionCode(ApiResponseCodes::API_ERROR_CHARGED_AMOUNT_HIGHER_THAN_EXPECTED); + $this->unzer->performChargeOnPayment($payment->getId(), new Charge(2)); + } + + /** + * @test + */ + public function fullCancelAfterCharge(): void + { + $googlepay = $this->createGooglepayObjectFromToken($this->getTestToken()); + /** @var Googlepay $googlepay */ + $googlepay = $this->unzer->createPaymentType($googlepay); + $charge = $this->getUnzerObject() + ->performCharge( + $this->getLvpChargeObject(), + $googlepay + ); + $payment = $charge->getPayment(); + + $this->assertAmounts($payment, 0.0, 2.99, 2.99, 0.0); + $this->assertTrue($payment->isCompleted()); + + $this->unzer->cancelChargedPayment($payment); + $this->assertAmounts($payment, 0.0, 0.0, 2.99, 2.99); + $this->assertTrue($payment->isCanceled()); + } + + /** Creates an authorization request object with low value payment(lvp) set to avoid 3ds challenge. + * + * @return Authorization + */ + protected function getLvpAuthorizationObject() + { + return (new Authorization(2.99, 'EUR', self::RETURN_URL)) + ->setCardTransactionData( + (new CardTransactionData())->setExemptionType(ExemptionType::LOW_VALUE_PAYMENT) + ); + } + + /** Creates an charge request object with low value payment(lvp) set to avoid 3ds challenge. + * + * @return Charge + */ + protected function getLvpChargeObject() + { + return (new Charge(2.99, 'EUR', self::RETURN_URL)) + ->setCardTransactionData( + (new CardTransactionData())->setExemptionType(ExemptionType::LOW_VALUE_PAYMENT) + ); + } + + /** + * @param $googlePayToken + * + * @return Googlepay + */ + protected function createGooglepayObjectFromToken($googlePayToken): Googlepay + { + $googlepay = (new Googlepay()); + $this->assertNull($googlepay->getId()); + + $geoLocation = $googlepay->getGeoLocation(); + $this->assertNull($geoLocation->getClientIp()); + $this->assertNull($geoLocation->getCountryCode()); + + $signedKey = (new SignedKey()) + ->setKeyValue($googlePayToken->intermediateSigningKey->signedKey->keyValue) + ->setKeyExpiration($googlePayToken->intermediateSigningKey->signedKey->keyExpiration); + + $intermediateSigningKey = (new IntermediateSigningKey()) + ->setSignedKey($signedKey) + ->setSignatures($googlePayToken->intermediateSigningKey->signatures); + + $protocolVersion = $googlePayToken->protocolVersion; + $encryptedMessage = $googlePayToken->signedMessage->encryptedMessage; + $ephemeralPublicKey = $googlePayToken->signedMessage->ephemeralPublicKey; + $tag = $googlePayToken->signedMessage->tag; + + $signedMessage = (new SignedMessage()) + ->setEncryptedMessage($encryptedMessage) + ->setEphemeralPublicKey($ephemeralPublicKey) + ->setTag($tag); + + $googlepay->setSignature($googlePayToken->signature) + ->setIntermediateSigningKey($intermediateSigningKey) + ->setProtocolVersion($protocolVersion) + ->setSignedMessage($signedMessage); + + return $googlepay; + } + + /** + * @return mixed + * + * @throws \Exception + */ + protected function getTestToken() + { + $googlePayToken = json_decode(JsonProvider::getJsonFromFile('googlepay/googlepayToken.json'), false); + if (!empty($googlePayToken)) { + $googlePayToken->intermediateSigningKey->signedKey = json_decode($googlePayToken->intermediateSigningKey->signedKey); + $googlePayToken->signedMessage = json_decode($googlePayToken->signedMessage); + } + return $googlePayToken; + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/HirePurchaseTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/HirePurchaseTest.php new file mode 100644 index 0000000..5e6a87c --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/HirePurchaseTest.php @@ -0,0 +1,139 @@ +getUnzerObject(TestEnvironmentService::getLegacyTestPrivateKey()); + } + + /** + * Verify, backwards compatibility regarding fetching payment type and map it to invoice secured class. + * + * @test + */ + public function hddTypeShouldBeFetchable(): InstallmentSecured + { + // Mock a hdd Type + $date = $this->getTodaysDateString(); + $requestData = + [ + "iban" => "DE89370400440532013000", + "bic" => "COBADEFFXXX", + "accountHolder" => "Max Mustermann", + "invoiceDueDate" => $date, + "numberOfRates" => 3, + "invoiceDate" => $date, + "dayOfPurchase" => $date, + "orderDate" => $date, + "totalPurchaseAmount" => 119, + "totalInterestAmount" => 0.96, + "totalAmount" => 119.96, + "effectiveInterestRate" => 4.99, + "nominalInterestRate" => 4.92, + "feeFirstRate" => 0, + "feePerRate" => 0, + "monthlyRate" => 39.99, + "lastRate" => 39.98, + ]; + + $payload = json_encode($requestData); + $hddMock = $this->getMockBuilder(InstallmentSecured::class) + ->setMethods(['getUri', 'jsonSerialize']) + ->getMock(); + $hddMock->method('getUri')->willReturn('/types/hire-purchase-direct-debit'); + $hddMock->method('jsonSerialize')->willReturn($payload); + + // When + /** @var InstallmentSecured $hddMock */ + $this->unzer->createPaymentType($hddMock); + $this->assertMatchesRegularExpression('/^s-hdd-[.]*/', $hddMock->getId()); + + // Then + $fetchedType = $this->unzer->fetchPaymentType($hddMock->getId()); + $this->assertInstanceOf(InstallmentSecured::class, $fetchedType); + $this->assertMatchesRegularExpression('/^s-hdd-[.]*/', $fetchedType->getId()); + + return $fetchedType; + } + + /** + * Verify fetched hdd type can be authorized and charged + * + * @test + * + * @depends hddTypeShouldBeFetchable + * + * @param InstallmentSecured $hddType fetched hdd type. + * + * @return AbstractUnzerResource|Charge + * + * @throws UnzerApiException + */ + public function hddTypeAuthorizeAndCharge(InstallmentSecured $hddType) + { + $customer = $this->getMaximumCustomer(); + $basket = $this->createBasket(); + + $auth = $hddType->authorize(119.00, 'EUR', 'https://unzer.com', $customer, null, null, $basket); + $charge = $auth->getPayment()->charge(); + $this->assertNotNull($auth); + $this->assertNotEmpty($auth->getId()); + $this->assertTrue($auth->isSuccess()); + + return $charge; + } + + /** + * Verify fetched hdd payment can be shipped. + * + * @test + * + * @depends hddTypeAuthorizeAndCharge + */ + public function hddTypeShouldBeShippable(Charge $hddCharge) + { + $invoiceId = 'i' . self::generateRandomId(); + $ship = $this->unzer->ship($hddCharge->getPayment(), $invoiceId); + + $this->assertNotNull($ship); + return $hddCharge; + } + + /** + * Verify full cancel of charged HP after shipment. + * + * @test + * + * @depends hddTypeAuthorizeAndCharge + */ + public function hddChargeCanBePartiallyCancledBeforeShipment(Charge $hddCharge): void + { + $payment = $hddCharge->getPayment(); + + $cancel1 = $payment->cancelAmount(66, null, null, 60, 6); + $cancel2 = $payment->cancelAmount(43, null, null, 40, 3); + $this->assertGreaterThan(0, count($cancel1)); + $this->assertGreaterThan(0, count($cancel2)); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/IdealTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/IdealTest.php index 8770be0..f155904 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/IdealTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/IdealTest.php @@ -1,34 +1,20 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\PaymentTypes\Ideal; +use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BaseIntegrationTest; class IdealTest extends BaseIntegrationTest @@ -56,6 +42,7 @@ public function idealShouldBeCreatable(): Ideal * @test * * @param Ideal $ideal + * * @depends idealShouldBeCreatable */ public function idealShouldThrowExceptionOnAuthorize(Ideal $ideal): void @@ -70,25 +57,33 @@ public function idealShouldThrowExceptionOnAuthorize(Ideal $ideal): void * Verify that ideal payment type is chargeable. * * @test + * * @depends idealShouldBeCreatable * * @param Ideal $ideal */ public function idealShouldBeChargeable(Ideal $ideal): void { - $charge = $ideal->charge(1.0, 'EUR', self::RETURN_URL); + $charge = new Charge(1.0, 'EUR', self::RETURN_URL); + $maximumCustomer = $this->getMaximumCustomer(); + $maximumCustomer->getBillingAddress() + ->setCountry('NL'); + $maximumCustomer->getShippingAddress() + ->setCountry('NL'); + $this->getUnzerObject()->performCharge($charge, $ideal, $maximumCustomer); $this->assertNotNull($charge); $this->assertNotNull($charge->getId()); $this->assertNotEmpty($charge->getRedirectUrl()); $fetchCharge = $this->unzer->fetchChargeById($charge->getPayment()->getId(), $charge->getId()); - $this->assertEquals($charge->expose(), $fetchCharge->expose()); + $this->assertEquals($charge->setCard3ds(false)->expose(), $fetchCharge->expose()); } /** * Verify ideal payment type can be fetched. * * @test + * * @depends idealShouldBeCreatable * * @param Ideal $ideal diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InstallmentSecuredTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InstallmentSecuredTest.php index ddb6d4c..07ef3d0 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InstallmentSecuredTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InstallmentSecuredTest.php @@ -1,35 +1,19 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Exceptions\UnzerApiException; -use UnzerSDK\Resources\AbstractUnzerResource; use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\CustomerFactory; use UnzerSDK\Resources\EmbeddedResources\Address; @@ -37,17 +21,24 @@ use UnzerSDK\Resources\PaymentTypes\InstallmentSecured; use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; + use function count; class InstallmentSecuredTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->getUnzerObject(TestEnvironmentService::getLegacyTestPrivateKey()); + } + /** * Verify the following features: * 1. fetching instalment plans. * 2. selecting plan - * 3. create hp resource - * 4. fetch hp resource - * 5 test update hp resource + * 3. create ins resource + * 4. fetch ins resource + * 5 test update ins resource * * @test */ @@ -76,100 +67,11 @@ public function instalmentPlanShouldBeSelectable(): void $this->assertEquals($insClone->expose(), $ins->expose()); } - /** - * Verify, backwards compatibility regarding fetching payment type and map it to invoice secured class. - * - * @test - */ - public function hddTypeShouldBeFetchable(): InstallmentSecured - { - // Mock a hdd Type - $date = $this->getTodaysDateString(); - $requestData = - [ - "iban" =>"DE89370400440532013000", - "bic" => "COBADEFFXXX", - "accountHolder" => "Max Mustermann", - "invoiceDueDate" => $date, - "numberOfRates" => 3, - "invoiceDate" => $date, - "dayOfPurchase" => $date, - "orderDate" => $date, - "totalPurchaseAmount" => 119, - "totalInterestAmount" => 0.96, - "totalAmount" => 119.96, - "effectiveInterestRate" => 4.99, - "nominalInterestRate" => 4.92, - "feeFirstRate" => 0, - "feePerRate" => 0, - "monthlyRate" => 39.99, - "lastRate" => 39.98, - ]; - - $payload = json_encode($requestData); - $hddMock = $this->getMockBuilder(InstallmentSecured::class) - ->setMethods(['getUri', 'jsonSerialize']) - ->getMock(); - $hddMock->method('getUri')->willReturn('/types/hire-purchase-direct-debit'); - $hddMock->method('jsonSerialize')->willReturn($payload); - - // When - /** @var InstallmentSecured $insType */ - $this->unzer->createPaymentType($hddMock); - $this->assertRegExp('/^s-hdd-[.]*/', $hddMock->getId()); - - // Then - $fetchedType = $this->unzer->fetchPaymentType($hddMock->getId()); - $this->assertInstanceOf(InstallmentSecured::class, $fetchedType); - $this->assertRegExp('/^s-hdd-[.]*/', $fetchedType->getId()); - - return $fetchedType; - } - - /** - * Verify fetched hdd type can be authorized and charged - * - * @test - * @depends hddTypeShouldBeFetchable - * - * @param InstallmentSecured $hddType fetched ins type. - * - * @return AbstractUnzerResource|Charge - * - * @throws UnzerApiException - */ - public function hddTypeAuthorizeAndCharge(InstallmentSecured $hddType) - { - $customer = $this->getMaximumCustomer(); - $basket = $this->createBasket(); - - $auth = $hddType->authorize(119.00, 'EUR', 'https://unzer.com', $customer, null, null, $basket); - $charge = $auth->getPayment()->charge(); - $this->assertNotNull($auth); - $this->assertNotEmpty($auth->getId()); - $this->assertTrue($auth->isSuccess()); - - return $charge; - } - - /** - * Verify fetched hdd payment can be shipped. - * - * @test - * @depends hddTypeAuthorizeAndCharge - */ - public function insTypeShouldBeShippable(Charge $hddCharge) - { - $invoiceId = 'i' . self::generateRandomId(); - $ship = $this->unzer->ship($hddCharge->getPayment(), $invoiceId); - - $this->assertNotNull($ship); - } - /** * Verify Installment Secured authorization (positive and negative). * * @test + * * @dataProvider CustomerRankingDataProvider * * @param $firstname @@ -189,7 +91,7 @@ public function installmentSecuredAuthorize($firstname, $lastname, $errorCode): try { $authorize = $ins->authorize(119.0, 'EUR', self::RETURN_URL, $customer, null, null, $basket); - if ($errorCode!== null) { + if ($errorCode !== null) { $this->assertTrue(false, 'Expected error for negative ranking test.'); } $this->assertNotEmpty($authorize->getId()); @@ -275,8 +177,6 @@ public function verifyShippingAChargedInstallmentSecured(): void * Verify full cancel of charged HP. * * @test - * - * @depends verifyChargingAnInitializedInstallmentSecured */ public function verifyChargeAndFullCancelAnInitializedInstallmentSecured(): void { @@ -300,8 +200,6 @@ public function verifyChargeAndFullCancelAnInitializedInstallmentSecured(): void * Verify full cancel of charged HP. * * @test - * - * @depends verifyChargingAnInitializedInstallmentSecured */ public function verifyPartlyCancelChargedInstallmentSecured(): void { @@ -326,8 +224,6 @@ public function verifyPartlyCancelChargedInstallmentSecured(): void * Verify full cancel of charged HP after shipment. * * @test - * - * @depends verifyChargingAnInitializedInstallmentSecured */ public function verifyChargeAndFullCancelAnInitializedInstallmentSecuredAfterShipment(): void { @@ -343,9 +239,9 @@ public function verifyChargeAndFullCancelAnInitializedInstallmentSecuredAfterShi $authorize = $ins->authorize(119.0, 'EUR', self::RETURN_URL, $this->getCustomer(), null, null, $basket = $this->createBasket()); $payment = $authorize->getPayment(); - $hddCharge = $payment->charge(); + $charge = $payment->charge(); $invoiceId = 'i' . self::generateRandomId(); - $ship = $this->unzer->ship($hddCharge->getPayment(), $invoiceId); + $ship = $this->unzer->ship($charge->getPayment(), $invoiceId); $this->assertNotNull($ship); $cancel = $payment->cancelAmount(); @@ -356,8 +252,6 @@ public function verifyChargeAndFullCancelAnInitializedInstallmentSecuredAfterShi * Verify full cancel of charged HP after shipment. * * @test - * - * @depends verifyChargingAnInitializedInstallmentSecured */ public function verifyPartlyCancelChargedInstallmentSecuredAfterShipment(): void { @@ -373,9 +267,9 @@ public function verifyPartlyCancelChargedInstallmentSecuredAfterShipment(): void $authorize = $ins->authorize(119.0, 'EUR', self::RETURN_URL, $this->getCustomer(), null, null, $basket = $this->createBasket()); $payment = $authorize->getPayment(); - $hddCharge = $payment->charge(); + $charge = $payment->charge(); $invoiceId = 'i' . self::generateRandomId(); - $ship = $this->unzer->ship($hddCharge->getPayment(), $invoiceId); + $ship = $this->unzer->ship($charge->getPayment(), $invoiceId); $this->assertNotNull($ship); $cancel = $payment->cancelAmount(59.5, null, null, 50.0, 9.5); diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceGuaranteedTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceGuaranteedTest.php new file mode 100644 index 0000000..54b75d8 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceGuaranteedTest.php @@ -0,0 +1,91 @@ +getUnzerObject(TestEnvironmentService::getLegacyTestPrivateKey()); + } + + /** + * Verify, backwards compatibility regarding fetching payment type and map it to invoice secured class. + * + * @test + */ + public function ivgTypeShouldBeFetchable(): InvoiceSecured + { + $ivgMock = $this->getMockBuilder(InvoiceSecured::class)->setMethods(['getUri'])->getMock(); + $ivgMock->method('getUri')->willReturn('/types/invoice-guaranteed'); + + /** @var InvoiceSecured $ivgType */ + $ivgType = $this->unzer->createPaymentType($ivgMock); + $this->assertInstanceOf(InvoiceSecured::class, $ivgType); + $this->assertMatchesRegularExpression('/^s-ivg-[.]*/', $ivgType->getId()); + + $fetchedType = $this->unzer->fetchPaymentType($ivgType->getId()); + $this->assertInstanceOf(InvoiceSecured::class, $fetchedType); + $this->assertMatchesRegularExpression('/^s-ivg-[.]*/', $fetchedType->getId()); + + return $fetchedType; + } + + /** + * Verify fetched ivg type can be charged + * + * @test + * + * @depends ivgTypeShouldBeFetchable + * + * @param InvoiceSecured $ivgType fetched ivg type. + * + * @throws UnzerApiException + */ + public function ivgTypeShouldBeChargable(InvoiceSecured $ivgType) + { + $customer = $this->getMaximumCustomer(); + $charge = $ivgType->charge(100.00, 'EUR', 'https://unzer.com', $customer); + + $this->assertNotNull($charge); + $this->assertNotEmpty($charge->getId()); + $this->assertTrue($charge->isPending()); + + return $charge; + } + + /** + * Verify fetched ivg type can be shipped. + * + * @test + * + * @depends ivgTypeShouldBeChargable + */ + public function ivgTypeShouldBeShippable(Charge $ivgCharge) + { + $invoiceId = 'i' . self::generateRandomId(); + + $ship = $this->unzer->ship($ivgCharge->getPayment(), $invoiceId); + // expect Payment to be pending after shipment. + $this->assertTrue($ship->getPayment()->isPending()); + $this->assertNotNull($ship); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceSecuredTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceSecuredTest.php index 8926884..f76607e 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceSecuredTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceSecuredTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -32,9 +17,18 @@ use UnzerSDK\Resources\PaymentTypes\InvoiceSecured; use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; +/** + * @deprecated since 1.2.0.0 PaylaterInvoice should be used instead in the future. + */ class InvoiceSecuredTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->getUnzerObject(TestEnvironmentService::getLegacyTestPrivateKey()); + } + /** * Verifies Invoice Secured payment type can be created. * @@ -55,66 +49,6 @@ public function invoiceSecuredTypeShouldBeCreatableAndFetchable(): InvoiceSecure return $invoice; } - - /** - * Verify, backwards compatibility regarding fetching payment type and map it to invoice secured class. - * - * @test - */ - public function ivgTypeShouldBeFechable(): InvoiceSecured - { - $ivgMock = $this->getMockBuilder(InvoiceSecured::class)->setMethods(['getUri'])->getMock(); - $ivgMock->method('getUri')->willReturn('/types/invoice-guaranteed'); - - /** @var InvoiceSecured $ivgType */ - $ivgType = $this->unzer->createPaymentType($ivgMock); - $this->assertInstanceOf(InvoiceSecured::class, $ivgType); - $this->assertRegExp('/^s-ivg-[.]*/', $ivgType->getId()); - - $fetchedType = $this->unzer->fetchPaymentType($ivgType->getId()); - $this->assertInstanceOf(InvoiceSecured::class, $fetchedType); - $this->assertRegExp('/^s-ivg-[.]*/', $fetchedType->getId()); - - return $fetchedType; - } - - /** - * Verify fetched ivg type can be charged - * - * @test - * @depends ivgTypeShouldBeFechable - * - * @param InvoiceSecured $ivgType fetched ivg type. - * - * @throws UnzerApiException - */ - public function ivgTypeShouldBeChargable(InvoiceSecured $ivgType) - { - $customer = $this->getMaximumCustomer(); - $charge = $ivgType->charge(100.00, 'EUR', 'https://unzer.com', $customer); - - $this->assertNotNull($charge); - $this->assertNotEmpty($charge->getId()); - $this->assertTrue($charge->isPending()); - - return $charge; - } - - /** - * Verify fetched ivg type can be shipped. - * - * @test - * @depends ivgTypeShouldBeChargable - */ - public function ivgTypeShouldBeShippable(Charge $ivgCharge) - { - $invoiceId = 'i' . self::generateRandomId(); - - $ship = $this->unzer->ship($ivgCharge->getPayment(), $invoiceId); - // expect Payment to be pending after shipment. - $this->assertTrue($ship->getPayment()->isPending()); - $this->assertNotNull($ship); - } /** * Verify Invoice Secured is not authorizable. @@ -122,6 +56,7 @@ public function ivgTypeShouldBeShippable(Charge $ivgCharge) * @test * * @param InvoiceSecured $invoice + * * @depends invoiceSecuredTypeShouldBeCreatableAndFetchable */ public function verifyInvoiceIsNotAuthorizable(InvoiceSecured $invoice): void @@ -136,6 +71,7 @@ public function verifyInvoiceIsNotAuthorizable(InvoiceSecured $invoice): void * Verify Invoice Secured needs a customer object * * @test + * * @depends invoiceSecuredTypeShouldBeCreatableAndFetchable * * @param InvoiceSecured $invoiceSecured @@ -151,6 +87,7 @@ public function invoiceSecuredShouldRequiresCustomer(InvoiceSecured $invoiceSecu * Verify Invoice Secured is chargeable. * * @test + * * @depends invoiceSecuredTypeShouldBeCreatableAndFetchable * * @param InvoiceSecured $invoiceSecured @@ -166,10 +103,51 @@ public function invoiceSecuredRequiresBasket(InvoiceSecured $invoiceSecured): vo $invoiceSecured->charge(1.0, 'EUR', self::RETURN_URL, $customer); } + /** + * Verify charge with Invoice Secured throws an error when invalid ip is set. + * + * @test + */ + public function invoiceSecuredRequiresValidClientIpForCharge(): void + { + $clientIp = '123.456.789.123'; + $this->unzer->setClientIp($clientIp); + + /** @var InvoiceSecured $invoiceSecured */ + $invoiceSecured = $this->unzer->createPaymentType(new InvoiceSecured()); + $this->unzer->setClientIp(null); // Ensure that the invalid ip is only used for type creation. + $this->assertEquals($clientIp, $invoiceSecured->getGeoLocation()->getClientIp()); + + $customer = $this->getMaximumCustomer(); + $customer->setShippingAddress($customer->getBillingAddress()); + $basket = $this->createBasket(); + + $this->expectException(UnzerApiException::class); + $this->expectExceptionCode(ApiResponseCodes::CORE_INVALID_IP_NUMBER); + + $invoiceSecured->charge(119.0, 'EUR', self::RETURN_URL, $customer, $basket->getOrderId(), null, $basket); + } + + /** + * Verify creating a payment type with client ip header set, will overwrite the clientIp of the API resource. + * + * @test + */ + public function verifySettingClientIpViaHeaderWillOverwriteClientIpOfTypeResource(): void + { + $clientIp = 'xxx.xxx.xxx.xxx'; + $this->unzer->setClientIp($clientIp); + + /** @var InvoiceSecured $invoiceSecured */ + $invoiceSecured = $this->unzer->createPaymentType(new InvoiceSecured()); + $this->assertEquals($clientIp, $invoiceSecured->getGeoLocation()->getClientIp()); + } + /** * Verify Invoice Secured is chargeable. * * @test + * * @depends invoiceSecuredTypeShouldBeCreatableAndFetchable * * @param InvoiceSecured $invoiceSecured @@ -325,6 +303,7 @@ public function verifyInvoiceSecuredShipmentWithPreSetInvoiceId(): void * @test * * @param Charge $charge + * * @depends invoiceSecuredShouldBeChargeable */ public function verifyInvoiceChargeCanBeCanceled(Charge $charge): Charge @@ -341,6 +320,7 @@ public function verifyInvoiceChargeCanBeCanceled(Charge $charge): Charge * @test * * @param Charge $charge + * * @depends verifyInvoiceChargeCanBeCanceled */ public function verifyInvoiceChargeCanBeCancelledWoAmount(Charge $charge): void @@ -358,6 +338,7 @@ public function verifyInvoiceChargeCanBeCancelledWoAmount(Charge $charge): void * @test * * @param Charge $charge + * * @depends invoiceSecuredShouldBeChargeable */ public function verifyInvoiceChargeCanNotBeCancelledWoReasonCode(Charge $charge): void diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceTest.php index b023e12..443b833 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/InvoiceTest.php @@ -1,38 +1,29 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\PaymentTypes\Invoice; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class InvoiceTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->getUnzerObject(TestEnvironmentService::getLegacyTestPrivateKey()); + } + /** * Verifies invoice payment type can be created. * diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/KlarnaTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/KlarnaTest.php new file mode 100644 index 0000000..b704dea --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/KlarnaTest.php @@ -0,0 +1,93 @@ +unzer->createPaymentType(new Klarna()); + $this->assertInstanceOf(Klarna::class, $klarna); + $this->assertNotNull($klarna->getId()); + + /** @var Klarna $fetchedKlarna */ + $fetchedKlarna = $this->unzer->fetchPaymentType($klarna->getId()); + $this->assertInstanceOf(Klarna::class, $fetchedKlarna); + $this->assertEquals($klarna->expose(), $fetchedKlarna->expose()); + $this->assertNotEmpty($fetchedKlarna->getGeoLocation()->getClientIp()); + + return $fetchedKlarna; + } + + /** + * Verify klarna is not authorizable. + * + * @test + * + * @param Klarna $klarna + * + * @depends klarnaShouldBeCreatableAndFetchable + */ + public function klarnaShouldBeAuthorizable(Klarna $klarna): void + { + $authorizationInstance = (new Authorization(99.99, 'EUR', self::RETURN_URL)) + ->setTermsAndConditionUrl('https://www.unzer.com/de') + ->setPrivacyPolicyUrl('https://www.unzer.com/de'); + + $customer = $this->getMaximumCustomerInclShippingAddress(); + $customer->setLanguage('de'); + + $basket = $this->createV2Basket(); + $authorization = $this->unzer->performAuthorization($authorizationInstance, $klarna, $customer, null, $basket); + $this->assertNotNull($authorization); + $this->assertNotEmpty($authorization->getId()); + $this->assertNotEmpty($authorization->getRedirectUrl()); + } + + /** + * Verify klarna is not directly chargeable. + * + * @test + * + * @param Klarna $klarna + * + * @depends klarnaShouldBeCreatableAndFetchable + */ + public function klarnaShouldNotBeDirectlyChargable(Klarna $klarna) + { + $chargeInstance = (new Charge(99.99, 'EUR', self::RETURN_URL)) + ->setTermsAndConditionUrl('https://www.unzer.com/de') + ->setPrivacyPolicyUrl('https://www.unzer.com/de'); + + $customer = $this->getMaximumCustomerInclShippingAddress(); + $customer->setLanguage('de'); + + $basket = $this->createV2Basket(); + + $this->expectException(UnzerApiException::class); + $this->unzer->performCharge($chargeInstance, $klarna, $customer, null, $basket); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PISTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PISTest.php index 6d9324f..7646bd8 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PISTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PISTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\tests/integration/payment_types */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -64,6 +49,7 @@ public function pisShouldBeCreatableAndFetchable(): PIS * @param PIS $pis * * @return Charge + * * @depends pisShouldBeCreatableAndFetchable */ public function pisShouldBeAbleToCharge(PIS $pis): Charge @@ -82,6 +68,7 @@ public function pisShouldBeAbleToCharge(PIS $pis): Charge * @test * * @param PIS $pis + * * @depends pisShouldBeCreatableAndFetchable */ public function pisShouldNotBeAuthorizable(PIS $pis): void diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PayUTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PayUTest.php new file mode 100644 index 0000000..5665137 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PayUTest.php @@ -0,0 +1,99 @@ +unzer->createPaymentType(new PayU()); + $this->assertInstanceOf(PayU::class, $paymentType); + $this->assertNotNull($paymentType->getId()); + + /** @var PayU $fetchedType */ + $fetchedType = $this->unzer->fetchPaymentType($paymentType->getId()); + $this->assertInstanceOf(PayU::class, $fetchedType); + $this->assertEquals($paymentType->expose(), $fetchedType->expose()); + $this->assertNotEmpty($fetchedType->getGeoLocation()->getClientIp()); + + return $fetchedType; + } + + /** + * Verify PayU is chargeable. + * + * @test + * + * @param PayU $paymentType + * @param mixed $currency + * + * @return Charge + * + * @dataProvider supportedCurrencies + * + * @depends payUShouldBeCreatableAndFetchable + */ + public function payUShouldBeAbleToCharge($currency, PayU $paymentType): Charge + { + $charge = new Charge(100.0, $currency, self::RETURN_URL); + $this->getUnzerObject()->performCharge($charge, $paymentType); + + $this->assertNotNull($charge); + $this->assertNotEmpty($charge->getId()); + $this->assertNotEmpty($charge->getRedirectUrl()); + + return $charge; + } + + /** + * Verify payU is not authorizable. + * + * @test + * + * @param PayU $payU + * + * @depends payUShouldBeCreatableAndFetchable + */ + public function payUShouldNotBeAuthorizable(PayU $payU): void + { + $this->expectException(UnzerApiException::class); + $this->expectExceptionCode(ApiResponseCodes::API_ERROR_TRANSACTION_AUTHORIZE_NOT_ALLOWED); + + $authorization = new Authorization(100.0, 'CHF', self::RETURN_URL); + $this->unzer->performAuthorization($authorization, $payU); + } + + public function supportedCurrencies(): array + { + return [ + 'PLN' => ['PLN'], + 'CZK' => ['CZK'] + ]; + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterDirectDebitTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterDirectDebitTest.php new file mode 100644 index 0000000..6d21cd2 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterDirectDebitTest.php @@ -0,0 +1,198 @@ +unzer->createPaymentType($pdd); + $this->assertNotEmpty($pdd->getId()); + $fetchedIns = $this->unzer->fetchPaymentType($pdd->getId()); + $this->assertNotEmpty($fetchedIns->getId()); + } + + /** + * Verify Paylater Direct Debit authorization (positive and negative). + * + * @test + * + * @param $firstname + * @param $lastname + * @param $errorCode + */ + public function PaylaterDirectDebitAuthorize(): Authorization + { + $authorize = $this->createAuthorizeTransaction(); + $this->assertNotEmpty($authorize->getId()); + $this->assertTrue($authorize->isSuccess()); + + return $authorize; + } + + /** Performs a basic authorize transaction for Paylater invoice with amount 99.99 to set up test for follow-up transactions. + * + * @return Authorization + * + * @throws UnzerApiException + */ + protected function createAuthorizeTransaction(): Authorization + { + $pdd = new PaylaterDirectDebit('DE89370400440532013000', 'Peter Mustermann'); + + $this->unzer->createPaymentType($pdd); + $customer = $this->getCustomer()->setFirstname('Peter')->setLastname('Mustermann'); + $basket = $this->createBasket(); + + $authorization = new Authorization(99.99, 'EUR', self::RETURN_URL); + return $this->getUnzerObject()->performAuthorization($authorization, $pdd, $customer, null, $basket); + } + + /** + * @return Customer + */ + public function getCustomer(): Customer + { + $customer = CustomerFactory::createCustomer('Manuel', 'Weißmann'); + $address = (new Address()) + ->setStreet('Hugo-Junckers-Straße 3') + ->setState('DE-BO') + ->setZip('60386') + ->setCity('Frankfurt am Main') + ->setCountry('DE'); + $customer + ->setBillingAddress($address) + ->setBirthDate('2000-12-12') + ->setEmail('manuel-weissmann@unzer.com'); + + return $customer; + } + + /** + * Verify charge. + * + * @test + * + * @depends PaylaterDirectDebitAuthorize + * + * @param mixed $authorize + */ + public function verifyChargingAnInitializedPaylaterDirectDebit($authorize): Charge + { + $payment = $authorize->getPayment(); + $charge = $this->getUnzerObject()->performChargeOnPayment($payment, new Charge()); + $this->assertNotNull($charge->getId()); + $this->assertTrue($charge->isSuccess()); + + return $charge; + } + + /** + * Verify partial charge. + * + * @test + */ + public function verifyPartiallyChargingAnInitializedPaylaterDirectDebit(): Charge + { + $authorize = $this->createAuthorizeTransaction(); + $payment = $authorize->getPayment(); + + $charge = $this->getUnzerObject()->performChargeOnPayment($payment, new Charge(33.33)); + $this->assertNotNull($charge->getId()); + $this->assertTrue($charge->isSuccess()); + $this->unzer->fetchPaymentType($payment->getPaymentType()->getId()); + + return $charge; + } + + /** + * Verify full cancel of charged HP. + * + * @test + * + * @depends verifyChargingAnInitializedPaylaterDirectDebit + */ + public function verifyChargeAndFullCancelAnInitializedPaylaterDirectDebit(Charge $charge): void + { + $payment = $charge->getPayment(); + $cancel = $this->getUnzerObject()->cancelChargedPayment($payment); + + // then + $this->assertTrue($cancel->isSuccess()); + } + + /** + * Verify full cancel of charged HP. + * + * @test + */ + public function verifyPartlyCancelChargedPaylaterDirectDebit(): void + { + $authorize = $this->createAuthorizeTransaction(); + $payment = $authorize->getPayment(); + $this->getUnzerObject()->performChargeOnPayment($payment, new Charge()); + + // when + $cancel = $this->getUnzerObject()->cancelChargedPayment($payment, new Cancellation(66.66)); + $this->assertEmpty($cancel->getFetchedAt()); + + // then + $this->assertTrue($cancel->isSuccess()); + $this->assertTrue($payment->isCompleted()); + + $fetchedPayment = $this->getUnzerObject()->fetchPayment($authorize->getPaymentId()); + $fetchedCancel = $this->getUnzerObject()->fetchPaymentRefund($fetchedPayment->getId(), $cancel->getId()); + $this->assertNotEmpty($fetchedCancel->getFetchedAt()); + } + + /** + * Verify full cancel of charged HP. + * + * @test + */ + public function verifyFullCancelAuthorizedPaylaterDirectDebit(): void + { + $authorize = $this->createAuthorizeTransaction(); + $payment = $authorize->getPayment(); + + // when + $cancel = $this->getUnzerObject()->cancelAuthorizedPayment($payment); + $this->assertEmpty($cancel->getFetchedAt()); + + // then + $this->assertTrue($cancel->isSuccess()); + $this->assertTrue($payment->isCanceled()); + + $fetchedPayment = $this->getUnzerObject()->fetchPayment($authorize->getPaymentId()); + $fetchedCancel = $this->getUnzerObject()->fetchPaymentReversal($fetchedPayment->getId(), $cancel->getId()); + $this->assertNotEmpty($fetchedCancel->getFetchedAt()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterInstallmentTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterInstallmentTest.php new file mode 100644 index 0000000..3770a9a --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterInstallmentTest.php @@ -0,0 +1,262 @@ +unzer->fetchPaylaterInstallmentPlans($paylaterInstallmentPlans); + + $this->assertGreaterThan(0, count($plans->getPlans())); + $this->assertTrue($plans->isSuccess()); + } + + /** + * Verify that paylater installment type can be created and fetched. + * + * @test + */ + public function typeCanBeCreatedAndFetched(): void + { + // when + $paylaterInstallmentPlans = new InstallmentPlansQuery(99.99, 'EUR', 'DE', 'B2C'); + $plans = $this->unzer->fetchPaylaterInstallmentPlans($paylaterInstallmentPlans); + + /** @var InstallmentPlan $selectedPlan */ + $selectedPlan = $plans->getPlans()[1]; + $ins = new PaylaterInstallment($plans->getId(), $selectedPlan->getNumberOfRates(), 'DE89370400440532013000', 'DE', 'Peter Mustermann'); + + // then + $this->unzer->createPaymentType($ins); + $this->assertNotEmpty($ins->getId()); + $fetchedIns = $this->unzer->fetchPaymentType($ins->getId()); + $this->assertNotEmpty($fetchedIns->getId()); + } + + /** + * Verify that paylater installment plans can be fetched. + * + * @test + */ + public function fetchingPlansUsesB2CCustomerAsDefaultIfEmpty(): void + { + // when + $paylaterInstallmentPlans = new InstallmentPlansQuery(99.99, 'EUR', 'DE'); + + // then + $this->assertEquals(CustomerTypes::B2C, $paylaterInstallmentPlans->getCustomerType()); + $plans = $this->unzer->fetchPaylaterInstallmentPlans($paylaterInstallmentPlans); + $this->assertTrue($plans->isSuccess()); + } + + /** + * Verify Api error is handled as Exception. + * + * @test + */ + public function invalidInputThrowsUnzerApiException(): void + { + $this->expectException(UnzerApiException::class); + $paylaterInstallmentPlans = new InstallmentPlansQuery(-99.99, 'EUR', 'DE'); + + $this->assertEquals(CustomerTypes::B2C, $paylaterInstallmentPlans->getCustomerType()); + $this->unzer->fetchPaylaterInstallmentPlans($paylaterInstallmentPlans); + } + + /** + * Verify Installment Secured authorization (positive and negative). + * + * @test + * + * @param $firstname + * @param $lastname + * @param $errorCode + */ + public function paylaterInstallmentAuthorize(): Authorization + { + $authorize = $this->createAuthorizeTransaction(); + $this->assertNotEmpty($authorize->getId()); + $this->assertTrue($authorize->isSuccess()); + + return $authorize; + } + + // + + /** + * Verify charge. + * + * @test + * + * @depends paylaterInstallmentAuthorize + * + * @param mixed $authorize + */ + public function verifyChargingAnInitializedPaylaterInstallment($authorize): Charge + { + $payment = $authorize->getPayment(); + $charge = $this->getUnzerObject()->performChargeOnPayment($payment, new Charge()); + $this->assertNotNull($charge->getId()); + $this->assertTrue($charge->isSuccess()); + + return $charge; + } + + /** + * Verify partial charge. + * + * @test + */ + public function verifyPartiallyChargingAnInitializedPaylaterInstallment(): Charge + { + $authorize = $this->createAuthorizeTransaction(); + $payment = $authorize->getPayment(); + + $charge = $this->getUnzerObject()->performChargeOnPayment($payment, new Charge(33.33)); + $this->assertNotNull($charge->getId()); + $this->assertTrue($charge->isSuccess()); + + return $charge; + } + + /** + * Verify full cancel of charged HP. + * + * @test + * + * @depends verifyChargingAnInitializedPaylaterInstallment + */ + public function verifyChargeAndFullCancelAnInitializedPaylaterInstallment(Charge $charge): void + { + $payment = $charge->getPayment(); + $cancel = $this->getUnzerObject()->cancelChargedPayment($payment); + + // then + $this->assertTrue($cancel->isSuccess()); + } + + // + + /** + * Verify full cancel of charged HP. + * + * @test + */ + public function verifyPartlyCancelChargedPaylaterInstallment(): void + { + $authorize = $this->createAuthorizeTransaction(); + $payment = $authorize->getPayment(); + $this->getUnzerObject()->performChargeOnPayment($payment, new Charge()); + + // when + $cancel = $this->getUnzerObject()->cancelChargedPayment($payment, new Cancellation(66.66)); + $this->assertEmpty($cancel->getFetchedAt()); + + // then + $this->assertTrue($cancel->isSuccess()); + $this->assertTrue($payment->isCompleted()); + + $fetchedPayment = $this->getUnzerObject()->fetchPayment($authorize->getPaymentId()); + $fetchedCancel = $this->getUnzerObject()->fetchPaymentRefund($fetchedPayment->getId(), $cancel->getId()); + $this->assertNotEmpty($fetchedCancel->getFetchedAt()); + } + + /** + * Verify full cancel of charged HP. + * + * @test + */ + public function verifyFullCancelAuthorizedPaylaterInstallment(): void + { + $authorize = $this->createAuthorizeTransaction(); + $payment = $authorize->getPayment(); + + // when + $cancel = $this->getUnzerObject()->cancelAuthorizedPayment($payment); + $this->assertEmpty($cancel->getFetchedAt()); + + // then + $this->assertTrue($cancel->isSuccess()); + $this->assertTrue($payment->isCanceled()); + + $fetchedPayment = $this->getUnzerObject()->fetchPayment($authorize->getPaymentId()); + $fetchedCancel = $this->getUnzerObject()->fetchPaymentReversal($fetchedPayment->getId(), $cancel->getId()); + $this->assertNotEmpty($fetchedCancel->getFetchedAt()); + } + // + + /** Performs a basic authorize transaction for Paylater invoice with amount 99.99 to set up test for follow-up transactions. + * + * @return Authorization + * + * @throws UnzerApiException + */ + protected function createAuthorizeTransaction(): Authorization + { + $paylaterInstallmentPlans = new InstallmentPlansQuery(99.99, 'EUR', 'DE', 'B2C'); + $plans = $this->unzer->fetchPaylaterInstallmentPlans($paylaterInstallmentPlans); + + $selectedPlan = $plans->getPlans()[0]; + $ins = new PaylaterInstallment($plans->getId(), $selectedPlan->getNumberOfRates(), 'DE89370400440532013000', 'DE', 'Peter Mustermann'); + $this->unzer->createPaymentType($ins); + + $customer = $this->getCustomer()->setFirstname('Peter')->setLastname('Mustermann'); + $basket = $this->createBasket(); + + $authorization = new Authorization(99.99, 'EUR', self::RETURN_URL); + return $this->getUnzerObject()->performAuthorization($authorization, $ins, $customer, null, $basket); + } + + /** + * @return Customer + */ + public function getCustomer(): Customer + { + $customer = CustomerFactory::createCustomer('Manuel', 'Weißmann'); + $address = (new Address()) + ->setStreet('Hugo-Junckers-Straße 3') + ->setState('DE-BO') + ->setZip('60386') + ->setCity('Frankfurt am Main') + ->setCountry('DE'); + $customer + ->setBillingAddress($address) + ->setBirthDate('2000-12-12') + ->setEmail('manuel-weissmann@unzer.com'); + + return $customer; + } + // +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterInvoiceTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterInvoiceTest.php new file mode 100644 index 0000000..e631c0b --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaylaterInvoiceTest.php @@ -0,0 +1,195 @@ +unzer->createPaymentType(new PaylaterInvoice()); + $this->assertInstanceOf(PaylaterInvoice::class, $invoice); + $this->assertNotNull($invoice->getId()); + + $fetchedInvoice = $this->unzer->fetchPaymentType($invoice->getId()); + $this->assertInstanceOf(PaylaterInvoice::class, $fetchedInvoice); + $this->assertEquals($invoice->getId(), $fetchedInvoice->getId()); + $this->assertMatchesRegularExpression('/^s-piv-[.]*/', $fetchedInvoice->getId()); + + return $invoice; + } + + /** + * Customer should contain clientIp set via header. + * + * @test + */ + public function clientIpCanBeManuallySetForPaylaterInvoiceType() + { + $clientIp = '123.123.123.123'; + $this->unzer->setClientIp($clientIp); + + /** @var PaylaterInvoice $invoice */ + $invoice = $this->unzer->createPaymentType(new PaylaterInvoice()); + $fetchedInvoice = $this->unzer->fetchPaymentType($invoice->getId()); + + $this->assertEquals($clientIp, $fetchedInvoice->getGeoLocation()->getClientIp()); + } + + /** + * Verify that paylater Invoice type can be authorized. + * + * @test + * + * @depends paylaterInvoiceTestTypeShouldBeCreatableAndFetchable + * + * @param mixed $paylaterInvoice + */ + public function paylaterInvoiceCanbeAuthorized($paylaterInvoice): Authorization + { + $authorization = new Authorization(99.99, 'EUR', 'https://unzer.com'); + $authorization->setInvoiceId('202205021237'); + + $customer = $this->getMaximumCustomerInclShippingAddress(); + $basket = $this->createV2Basket(); + + $authorization = $this->unzer->performAuthorization($authorization, $paylaterInvoice, $customer, null, $basket); + $this->assertNotEmpty($authorization->getId()); + $this->assertTrue($authorization->isSuccess()); + + return $authorization; + } + + /** + * Verify that paylater Invoice type can be authorized with riskdata. + * + * @test + * + * @depends paylaterInvoiceTestTypeShouldBeCreatableAndFetchable + * + * @param mixed $paylaterInvoice + */ + public function paylaterInvoiceCanbeAuthorizedWithRiskData($paylaterInvoice): Authorization + { + $riskData = new RiskData(); + $riskData->setThreatMetrixId('f544if49wo4f74ef1x') + ->setCustomerGroup('TOP') + ->setCustomerId('C-122345') + ->setConfirmedAmount('1234') + ->setConfirmedOrders('42') + ->setRegistrationLevel('1') + ->setRegistrationDate('20160412'); + + $authorization = new Authorization(99.99, 'EUR', 'https://unzer.com'); + $authorization->setRiskData($riskData) + ->setInvoiceId('202205021237'); + + $customer = $this->getMaximumCustomerInclShippingAddress(); + $basket = $this->createV2Basket(); + + $transaction = $this->unzer->performAuthorization($authorization, $paylaterInvoice, $customer, null, $basket); + $this->assertNotEmpty($transaction->getId()); + $this->assertNotEmpty($transaction->getRiskData()); + $this->assertEquals($authorization->getAdditionalTransactionData(), $transaction->getAdditionalTransactionData()); + $this->assertTrue($transaction->isSuccess()); + + return $authorization; + } + + /** + * Verify that paylater Invoice type can be authorized with not registered B2B Customer. + * + * @test + * + * @depends paylaterInvoiceTestTypeShouldBeCreatableAndFetchable + * + * @param mixed $paylaterInvoice + */ + public function paylaterInvoiceCanbeAuthorizedWithB2BCustomer($paylaterInvoice) + { + $authorization = new Authorization(99.99, 'EUR', 'https://unzer.com'); + $authorization->setInvoiceId('202205021237'); + + $customer = $this->getMaximalNotRegisteredB2bCustomer(); + $basket = $this->createV2Basket(); + + $transaction = $this->unzer->performAuthorization($authorization, $paylaterInvoice, $customer, null, $basket); + $this->assertNotEmpty($transaction->getId()); + $this->assertNotEmpty($transaction->getDescriptor()); + $this->assertTrue($transaction->isSuccess()); + } + + /** + * Verify that paylater Invoice type can be charged. + * + * @test + * + * @depends paylaterInvoiceCanbeAuthorized + * + * @param mixed $paylaterInvoice + * @param mixed $authorization + */ + public function paylaterInvoiceCanbeCharged($authorization) + { + $charge = $this->unzer->performChargeOnPayment($authorization->getPayment(), new Charge(99.99)); + + $this->assertNotEmpty($charge->getId()); + $this->assertTrue($charge->isSuccess()); + } + + /** + * Verify that paylater Invoice type can be charged with shippingdata. + * + * @test + * + * @param mixed $paylaterInvoice + * @param mixed $authorization + */ + public function paylaterInvoiceCanbeChargedWithShippingData() + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $shippingData = (object)[ + "deliveryTrackingId" => "00340434286851877897", + "deliveryService" => "DHL", + "returnTrackingId" => "00340434286851877900" + ]; + $shipping = new ShippingData(); + $shipping->handleResponse($shippingData); + + $chargeInstance = new Charge(99.99); + $chargeInstance->setOrderId($this->generateRandomId()) + ->setInvoiceId($this->generateRandomId()) + ->setPaymentReference('reference') + ->setShipping($shipping); + + $chargeResponse = $this->unzer->performChargeOnPayment($authorization->getPayment(), $chargeInstance); + $this->assertNotEmpty($chargeResponse->getId()); + $this->assertTrue($chargeResponse->isSuccess()); + + $fetchedCharge = $this->unzer->fetchChargeById($authorization->getPaymentId(), $chargeResponse->getId()); + $this->assertEquals($shipping, $fetchedCharge->getShipping()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypageTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypageTest.php index 8a99cf3..3f8c09c 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypageTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypageTest.php @@ -1,39 +1,33 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; +use UnzerSDK\Constants\ExemptionType; +use UnzerSDK\Constants\RecurrenceTypes; +use UnzerSDK\Constants\TransactionTypes; +use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\CustomerFactory; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\PaymentTypes\Card; use UnzerSDK\Resources\PaymentTypes\Paypage; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\Constants\PaymentState; class PaypageTest extends BaseIntegrationTest { + // IDs for Expired payment page. IDs are testkeypair specific. + private const EXPIRED_PAYPAGE_ID = "s-ppg-57cf4528728391347941b610ae22efccc92fa331d22e425a16b4e85b97c73362"; + private const PAYMENT_WITH_EXPIRED_PAYMENT_PAGE = 's-pay-328749'; + /** * Verify the Paypage resource for charge can be created with the mandatory parameters only. * @@ -47,6 +41,44 @@ public function minimalPaypageChargeShouldBeCreatableAndFetchable(): void $this->assertNotEmpty($paypage->getId()); } + /** + * Verify fetching expired paypageId. + * + * @test + */ + public function verifyFetchingExpiredPaypageThrowsException() + { + $this->expectException(UnzerApiException::class); + $this->getUnzerObject()->fetchPayPage(self::EXPIRED_PAYPAGE_ID); + } + + /** + * Verify fetching payment that contains expired payment page is possible. + * + * @test + */ + public function verifyFetchingPaymentwithExpiredPaymentPageIspossible() + { + $payment = $this->getUnzerObject()->fetchPayment(self::PAYMENT_WITH_EXPIRED_PAYMENT_PAGE); + $this->assertEquals(self::EXPIRED_PAYPAGE_ID, $payment->getPayPage()->getId()); + $this->assertNotEmpty($payment->getFetchedAt()); + } + + /** + * Verify the Paypage resource creates payment in state "create". + * + * @test + */ + public function paymentShouldBeInStateCreateOnInitialization(): void + { + $paypage = new Paypage(100.0, 'EUR', self::RETURN_URL); + $paypage = $this->unzer->initPayPageCharge($paypage); + $payment = $paypage->getPayment(); + + $this->assertTrue($payment->isCreate()); + $this->assertEquals($payment->getState(), PaymentState::STATE_CREATE); + } + /** * Verify the Paypage resource for charge can be created with all parameters. * @@ -59,8 +91,8 @@ public function maximumPaypageChargeShouldBeCreatable(): void $customer = CustomerFactory::createCustomer('Max', 'Mustermann'); $invoiceId = 'i'. self::generateRandomId(); $paypage = (new Paypage(119.0, 'EUR', self::RETURN_URL)) - ->setLogoImage('https://dev.unzer.com/wp-content/uploads/2020/09/Unzer__PrimaryLogo_Raspberry_RGB.png') - ->setFullPageImage('https://dev.unzer.com/wp-content/uploads/2020/09/01_Unzer_Ambitious_RGB_LoRes.jpg') + ->setLogoImage('https://docs.unzer.com/card/card.png') + ->setFullPageImage('https://docs.unzer.com/card/card.png') ->setShopName('My Test Shop') ->setShopDescription('Best shop in the whole world!') ->setTagline('Try and stop us from being awesome!') @@ -100,6 +132,78 @@ public function minimalPaypageAuthorizeShouldBeCreatableAndFetchable(): void $this->assertEmpty($paypage->getId()); $paypage = $this->unzer->initPayPageAuthorize($paypage); $this->assertNotEmpty($paypage->getId()); + + $fetchedPaypage = $this->unzer->fetchPayPage($paypage->getId()); + $this->assertEquals($paypage->getRedirectUrl(), $fetchedPaypage->getRedirectUrl()); + $this->assertEquals($paypage->getAction(), TransactionTypes::AUTHORIZATION); + } + + /** + * Custom additional transaction data can be set. + * + * @test + */ + public function additionalAttributesCanBeSet(): void + { + $paypage = new Paypage(100.0, 'EUR', self::RETURN_URL); + $paypage->setAdditionalAttribute('customField', 'customValue') + ->setEffectiveInterestRate(4.99) + ->setExemptionType(ExemptionType::LOW_VALUE_PAYMENT) + ->setRecurrenceType(RecurrenceTypes::UNSCHEDULED); + + $paypage = $this->unzer->initPayPageAuthorize($paypage); + $this->assertNotEmpty($paypage->getId()); + + $fetchedPaypage = $this->unzer->fetchPayPage($paypage->getId()); + + $this->assertEquals('customValue', $fetchedPaypage->getAdditionalAttribute('customField')); + $this->assertEquals(4.99, $fetchedPaypage->getEffectiveInterestRate()); + $this->assertEquals(ExemptionType::LOW_VALUE_PAYMENT, $fetchedPaypage->getExemptionType()); + $this->assertEquals(RecurrenceTypes::UNSCHEDULED, $fetchedPaypage->getRecurrenceType()); + } + + /** + * Verify fetched payment contains paypage when fetched. + * + * @test + */ + public function fetchedPaymentShouldContainPayPageID(): void + { + $payPage = new Paypage(100.0, 'EUR', self::RETURN_URL); + $this->assertEmpty($payPage->getId()); + $payPage = $this->unzer->initPayPageAuthorize($payPage); + $payment = $payPage->getPayment(); + $this->assertNotEmpty($payPage->getId()); + + $fetchedPayment = $this->unzer->fetchPayment($payPage->getPaymentId()); + $fetchedPayPage = $fetchedPayment->getPayPage(); + + $this->assertNotEmpty($fetchedPayPage); + $this->assertEquals($payPage->getId(), $fetchedPayPage->getId()); + $this->assertEquals($payment->expose(), $fetchedPayment->expose()); + $this->assertEmpty($fetchedPayment->getRedirectUrl()); + } + + /** + * Verify the Paypage resource for authorize can be created with the mandatory parameters only. + * + * @test + */ + public function fetchingPayPageShouldHaveReferenceToPayment(): void + { + $payPage = new Paypage(100.0, 'EUR', self::RETURN_URL); + $this->assertEmpty($payPage->getId()); + + $payPage = $this->unzer->initPayPageAuthorize($payPage); + $payment = $payPage->getPayment(); + $this->assertNotEmpty($payPage->getId()); + + $fetchedPayPage = $this->unzer->fetchPayPage($payPage->getId()); + $this->assertNotNull($fetchedPayPage->getPayment()); + $this->assertNotNull($fetchedPayPage->getRedirectUrl()); + + $this->assertEquals($payment->getId(), $fetchedPayPage->getPayment()->getId()); + $this->assertNotNull($payment->getFetchedAt()); } /** @@ -114,8 +218,8 @@ public function maximumPaypageAuthorizeShouldBeCreatable(): void $customer = CustomerFactory::createCustomer('Max', 'Mustermann'); $invoiceId = 'i'. self::generateRandomId(); $paypage = (new Paypage(119.0, 'EUR', self::RETURN_URL)) - ->setLogoImage('https://dev.unzer.com/wp-content/uploads/2020/09/Unzer__PrimaryLogo_Raspberry_RGB.png') - ->setFullPageImage('https://dev.unzer.com/wp-content/uploads/2020/09/01_Unzer_Ambitious_RGB_LoRes.jpg') + ->setLogoImage('https://docs.unzer.com/card/card.png') + ->setFullPageImage('https://docs.unzer.com/card/card.png') ->setShopName('My Test Shop') ->setShopDescription('Best shop in the whole world!') ->setTagline('Try and stop us from being awesome!') diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypalTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypalTest.php index 8a5fb83..89509da 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypalTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PaypalTest.php @@ -1,33 +1,23 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; +use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\Resources\Basket; +use UnzerSDK\Resources\EmbeddedResources\BasketItem; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Paypal; +use UnzerSDK\Resources\TransactionTypes\Authorization; +use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BaseIntegrationTest; class PaypalTest extends BaseIntegrationTest @@ -78,6 +68,7 @@ public function paypalShouldBeCreatableAndFetchableWithEmail(): BasePaymentType * Verify paypal can authorize. * * @test + * * @depends paypalShouldBeCreatableAndFetchable * * @param Paypal $paypal @@ -98,6 +89,7 @@ public function paypalShouldBeAuthorizable(Paypal $paypal): void * Verify paypal can charge. * * @test + * * @depends paypalShouldBeCreatableAndFetchable * * @param Paypal $paypal @@ -108,4 +100,124 @@ public function paypalShouldBeChargeable(Paypal $paypal): void $this->assertNotNull($charge); $this->assertNotEmpty($charge->getId()); } + + /** + * Test PayPal Express checkout. + * + * @test + * + * @depends paypalShouldBeCreatableAndFetchable + * + * @param Paypal $paypal + * + * @return Charge + * + * @throws UnzerApiException + */ + public function paypalChargeWithExpressCheckout(Paypal $paypal): Charge + { + $initialAmount = 100.00; + $charge = new Charge($initialAmount, 'EUR', self::RETURN_URL); + $charge->setCheckoutType('express', $paypal); + + $basketItem = (new BasketItem()) + ->setTitle('ItemTitle') + ->setAmountPerUnitGross($initialAmount); + $basket = (new Basket())->setTotalValueGross($initialAmount); + $basket->addBasketItem($basketItem); + $this->getUnzerObject()->performCharge($charge, $paypal, null, null, $basket); + $this->assertNotEmpty($charge->getId()); + + $this->assertTrue($charge->isPending()); + + return $charge; + } + + /** + * Verify Charge can be updated + * + * @test + * + * @depends paypalChargeWithExpressCheckout + */ + public function updateChargeThrowsExceptionWhenStatusIsPending(Charge $charge): void + { + $charge->setAmount(120); + $this->expectException(UnzerApiException::class); + + $this->getUnzerObject()->updateCharge($charge->getPaymentId(), $charge); + } + + /** + * Test PayPal Express checkout. + * + * @test + * + * @depends paypalShouldBeCreatableAndFetchable + * + * @param Paypal $paypal + * + * @return Authorization + * + * @throws UnzerApiException + */ + public function paypalAuthorizeWithExpressCheckout(Paypal $paypal): Authorization + { + $initialAmount = 100.00; + $authorize = new Authorization($initialAmount, 'EUR', self::RETURN_URL); + $authorize->setCheckoutType('express', $paypal->getId()); + + $basketItem = (new BasketItem()) + ->setTitle('ItemTitle') + ->setAmountPerUnitGross($initialAmount); + $basket = (new Basket())->setTotalValueGross($initialAmount); + $basket->addBasketItem($basketItem); + + $this->getUnzerObject()->performAuthorization($authorize, $paypal, null, null, $basket); + $this->assertNotEmpty($authorize->getId()); + + $this->assertTrue($authorize->isPending()); + $this->assertNotNull($authorize->getCheckoutType()); + + return $authorize; + } + + /** + * Test PayPal Express checkout. + * + * @test + * + * @depends paypalShouldBeCreatableAndFetchable + * + * @param Paypal $paypal + * + * @return Authorization + * + * @throws UnzerApiException + */ + public function invalidCheckoutTypeThrowsApiException(Paypal $paypal): Authorization + { + $authorize = new Authorization(100.00, 'EUR', self::RETURN_URL); + $authorize->setCheckoutType('expresso', $paypal); + + $this->expectException(UnzerApiException::class); + + $this->getUnzerObject()->performAuthorization($authorize, $paypal); + + return $authorize; + } + + /** + * Verify Authorize can be updated + * + * @test + * + * @depends paypalAuthorizeWithExpressCheckout + */ + public function updateAuthorizeThrowsApiExceptionWhenStatusIsPending(Authorization $authorize): void + { + $authorize->setAmount(120); + $this->expectException(UnzerApiException::class); + $this->getUnzerObject()->updateAuthorization($authorize->getPaymentId(), $authorize); + } } diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PostFinanceCardTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PostFinanceCardTest.php new file mode 100644 index 0000000..a311e6a --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PostFinanceCardTest.php @@ -0,0 +1,86 @@ +unzer->createPaymentType(new PostFinanceCard()); + $this->assertInstanceOf(PostFinanceCard::class, $paymentType); + $this->assertNotNull($paymentType->getId()); + + /** @var PostFinanceCard $fetchedType */ + $fetchedType = $this->unzer->fetchPaymentType($paymentType->getId()); + $this->assertInstanceOf(PostFinanceCard::class, $fetchedType); + $this->assertEquals($paymentType->expose(), $fetchedType->expose()); + $this->assertNotEmpty($fetchedType->getGeoLocation()->getClientIp()); + + return $fetchedType; + } + + /** + * Verify PostFinanceCard is chargeable. + * + * @test + * + * @param PostFinanceCard $paymentType + * + * @return Charge + * + * @depends postFinanceCardShouldBeCreatableAndFetchable + */ + public function postFinanceCardShouldBeAbleToCharge(PostFinanceCard $paymentType): Charge + { + $charge = new Charge(100.0, 'CHF', self::RETURN_URL); + $this->getUnzerObject()->performCharge($charge, $paymentType); + + $this->assertNotNull($charge); + $this->assertNotEmpty($charge->getId()); + $this->assertNotEmpty($charge->getRedirectUrl()); + + return $charge; + } + + /** + * Verify postFinanceCard is not authorizable. + * + * @test + * + * @param PostFinanceCard $postFinanceCard + * + * @depends postFinanceCardShouldBeCreatableAndFetchable + */ + public function postFinanceCardShouldNotBeAuthorizable(PostFinanceCard $postFinanceCard): void + { + $this->expectException(UnzerApiException::class); + $this->expectExceptionCode(ApiResponseCodes::API_ERROR_TRANSACTION_AUTHORIZE_NOT_ALLOWED); + + $authorization = new Authorization(100.0, 'CHF', self::RETURN_URL); + $this->unzer->performAuthorization($authorization, $postFinanceCard); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PostFinanceEfinanceTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PostFinanceEfinanceTest.php new file mode 100644 index 0000000..6452a70 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PostFinanceEfinanceTest.php @@ -0,0 +1,86 @@ +unzer->createPaymentType(new PostFinanceEfinance()); + $this->assertInstanceOf(PostFinanceEfinance::class, $paymentType); + $this->assertNotNull($paymentType->getId()); + + /** @var PostFinanceEfinance $fetchedType */ + $fetchedType = $this->unzer->fetchPaymentType($paymentType->getId()); + $this->assertInstanceOf(PostFinanceEfinance::class, $fetchedType); + $this->assertEquals($paymentType->expose(), $fetchedType->expose()); + $this->assertNotEmpty($fetchedType->getGeoLocation()->getClientIp()); + + return $fetchedType; + } + + /** + * Verify PostFinanceEfinance is chargeable. + * + * @test + * + * @param PostFinanceEfinance $paymentType + * + * @return Charge + * + * @depends postFinanceEfinanceShouldBeCreatableAndFetchable + */ + public function postFinanceEfinanceShouldBeAbleToCharge(PostFinanceEfinance $paymentType): Charge + { + $charge = new Charge(100.0, 'CHF', self::RETURN_URL); + $this->getUnzerObject()->performCharge($charge, $paymentType); + + $this->assertNotNull($charge); + $this->assertNotEmpty($charge->getId()); + $this->assertNotEmpty($charge->getRedirectUrl()); + + return $charge; + } + + /** + * Verify PostFinanceEfinance is not authorizable. + * + * @test + * + * @param PostFinanceEfinance $postFinanceEfinance + * + * @depends postFinanceEfinanceShouldBeCreatableAndFetchable + */ + public function postFinanceEfinanceShouldNotBeAuthorizable(PostFinanceEfinance $postFinanceEfinance): void + { + $this->expectException(UnzerApiException::class); + $this->expectExceptionCode(ApiResponseCodes::API_ERROR_TRANSACTION_AUTHORIZE_NOT_ALLOWED); + + $authorization = new Authorization(100.0, 'CHF', self::RETURN_URL); + $this->unzer->performAuthorization($authorization, $postFinanceEfinance); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PrepaymentTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PrepaymentTest.php index 82e8628..4f89dd9 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PrepaymentTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/PrepaymentTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -39,6 +24,7 @@ class PrepaymentTest extends BaseIntegrationTest * Verify Prepayment can be created and fetched. * * @return Prepayment + * * @test */ public function prepaymentShouldBeCreatableAndFetchable(): AbstractUnzerResource diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/Przelewy24Test.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/Przelewy24Test.php index 2ce7fb9..37c2374 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/Przelewy24Test.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/Przelewy24Test.php @@ -1,37 +1,24 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Przelewy24; +use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class Przelewy24Test extends BaseIntegrationTest { @@ -60,13 +47,20 @@ public function przelewy24ShouldBeCreatableAndFetchable(): BasePaymentType * Verify przelewy24 can authorize. * * @test + * * @depends przelewy24ShouldBeCreatableAndFetchable * * @param Przelewy24 $przelewy24 */ public function przelewy24ShouldBeChargeable(Przelewy24 $przelewy24): void { - $charge = $przelewy24->charge(100.0, 'PLN', self::RETURN_URL); + $charge = new Charge(100.0, 'PLN', self::RETURN_URL); + $customer = $this->getMaximumCustomer(); + $customer->getShippingAddress() + ->setCountry('PL'); + $customer->getBillingAddress() + ->setCountry('PL'); + $this->getUnzerObject()->performCharge($charge, $przelewy24, $customer); $this->assertNotNull($charge); $this->assertNotEmpty($charge->getId()); $this->assertNotEmpty($charge->getRedirectUrl()); @@ -80,6 +74,7 @@ public function przelewy24ShouldBeChargeable(Przelewy24 $przelewy24): void * Verify przelewy24 can not be authorized. * * @test + * * @depends przelewy24ShouldBeCreatableAndFetchable * * @param Przelewy24 $przelewy24 @@ -103,6 +98,31 @@ public function przelewy24ShouldNotBeAuthorizable(Przelewy24 $przelewy24): void */ public function przelewy24ShouldThrowExceptionIfCurrencyIsNotSupported($currencyCode): void { + /** @var Przelewy24 $przelewy24 */ + $przelewy24 = $this->unzer->createPaymentType(new Przelewy24()); + $this->expectException(UnzerApiException::class); + $this->expectExceptionCode(ApiResponseCodes::API_ERROR_CURRENCY_IS_NOT_SUPPORTED); + $charge = new Charge(100.0, $currencyCode, self::RETURN_URL); + $customer = $this->getMaximumCustomer(); + $customer->getShippingAddress() + ->setCountry('PL'); + $customer->getBillingAddress() + ->setCountry('PL'); + $this->getUnzerObject()->performCharge($charge, $przelewy24, $customer); + } + + /** + * Verify przelewy24 can only handle Currency::POLISH_ZLOTY. + * + * @test + * + * @dataProvider legazyPrzelewy24CurrencyCodeProvider + * + * @param string $currencyCode + */ + public function legazyConfigPrzelewy24ShouldThrowExceptionIfCurrencyIsNotSupported($currencyCode): void + { + $this->getUnzerObject()->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); /** @var Przelewy24 $przelewy24 */ $przelewy24 = $this->unzer->createPaymentType(new Przelewy24()); $this->expectException(UnzerApiException::class); @@ -116,10 +136,21 @@ public function przelewy24ShouldThrowExceptionIfCurrencyIsNotSupported($currency * Provides a subset of currencies not allowed by this payment method. */ public function przelewy24CurrencyCodeProvider(): array + { + return [ + 'US Dollar' => ['USD'], + 'Swiss Franc' => ['CHF'] + ]; + } + + /** + * Provides a subset of currencies not allowed by this payment method. + */ + public function legazyPrzelewy24CurrencyCodeProvider(): array { return [ 'EUR' => ['EUR'], - 'US Dollar'=> ['USD'], + 'US Dollar' => ['USD'], 'Swiss Franc' => ['CHF'] ]; } diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitSecuredTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitSecuredTest.php index 4d82463..b2d89c4 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitSecuredTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitSecuredTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -32,9 +17,15 @@ use UnzerSDK\Resources\PaymentTypes\SepaDirectDebitSecured; use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class SepaDirectDebitSecuredTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->getUnzerObject(TestEnvironmentService::getLegacyTestPrivateKey()); + } + /** * Verify sepa direct debit secured can be created with mandatory fields only. * @@ -79,6 +70,7 @@ public function sepaDirectDebitSecuredShouldBeCreatable(): SepaDirectDebitSecure * Verify Sepa Direct Debit Secured needs a basket object * * @test + * * @depends sepaDirectDebitSecuredShouldBeCreatable * * @param sepaDirectDebitSecured $sepaDirectDebitSecured @@ -94,6 +86,7 @@ public function sepaDirectDebitSecuredRequiresBasket(SepaDirectDebitSecured $sep * Verify Sepa Direct Debit Secured needs a customer object * * @test + * * @depends sepaDirectDebitSecuredShouldBeCreatable * * @param sepaDirectDebitSecured $sepaDirectDebitSecured @@ -112,6 +105,7 @@ public function sepaDirectDebitSecuredRequiresCustomer(SepaDirectDebitSecured $s * @test * * @param SepaDirectDebitSecured $directDebitSecured + * * @depends sepaDirectDebitSecuredShouldBeCreatable */ public function directDebitSecuredShouldProhibitAuthorization(SepaDirectDebitSecured $directDebitSecured): void @@ -173,12 +167,12 @@ public function ddgTypeShouldBeFechable(): SepaDirectDebitSecured // When /** @var SepaDirectDebitSecured $insType */ $this->unzer->createPaymentType($ddgMock); - $this->assertRegExp('/^s-ddg-[.]*/', $ddgMock->getId()); + $this->assertMatchesRegularExpression('/^s-ddg-[.]*/', $ddgMock->getId()); // Then $fetchedType = $this->unzer->fetchPaymentType($ddgMock->getId()); $this->assertInstanceOf(SepaDirectDebitSecured::class, $fetchedType); - $this->assertRegExp('/^s-ddg-[.]*/', $fetchedType->getId()); + $this->assertMatchesRegularExpression('/^s-ddg-[.]*/', $fetchedType->getId()); return $fetchedType; } @@ -187,6 +181,7 @@ public function ddgTypeShouldBeFechable(): SepaDirectDebitSecured * Verify fetched ddg type can be charged * * @test + * * @depends ddgTypeShouldBeFechable * * @param SepaDirectDebitSecured $ddgType fetched ins type. @@ -211,6 +206,7 @@ public function ddgTypeCharge(SepaDirectDebitSecured $ddgType) * Verify fetched ddg payment throws an exception when being shipped. * * @test + * * @depends ddgTypeCharge * * @param Charge $ddgCharge diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitTest.php index 3d1a8ce..b97268e 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SepaDirectDebitTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -34,6 +19,11 @@ class SepaDirectDebitTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->useLegacyKey(); + } + /** * Verify sepa direct debit can be created. * diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SofortTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SofortTest.php index bb61684..ebcdd10 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SofortTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/SofortTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; @@ -52,6 +37,7 @@ public function sofortShouldBeCreatableAndFetchable(): Sofort $fetchedSofort = $this->unzer->fetchPaymentType($sofort->getId()); $this->assertInstanceOf(Sofort::class, $fetchedSofort); $this->assertEquals($sofort->expose(), $fetchedSofort->expose()); + $this->assertNotEmpty($fetchedSofort->getGeoLocation()->getClientIp()); return $fetchedSofort; } @@ -64,6 +50,7 @@ public function sofortShouldBeCreatableAndFetchable(): Sofort * @param Sofort $sofort * * @return Charge + * * @depends sofortShouldBeCreatableAndFetchable */ public function sofortShouldBeAbleToCharge(Sofort $sofort): Charge @@ -82,6 +69,7 @@ public function sofortShouldBeAbleToCharge(Sofort $sofort): Charge * @test * * @param Sofort $sofort + * * @depends sofortShouldBeCreatableAndFetchable */ public function sofortShouldNotBeAuthorizable(Sofort $sofort): void diff --git a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/WechatpayTest.php b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/WechatpayTest.php index fdd5565..0cff56f 100644 --- a/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/WechatpayTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/PaymentTypes/WechatpayTest.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\integration\PaymentTypes */ + namespace UnzerSDK\test\integration\PaymentTypes; use UnzerSDK\Constants\ApiResponseCodes; diff --git a/vendor/unzerdev/php-sdk/test/integration/RecurringPaymentTest.php b/vendor/unzerdev/php-sdk/test/integration/RecurringPaymentTest.php index 9cdce30..abc379a 100644 --- a/vendor/unzerdev/php-sdk/test/integration/RecurringPaymentTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/RecurringPaymentTest.php @@ -1,40 +1,25 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Constants\RecurrenceTypes; use UnzerSDK\Exceptions\UnzerApiException; +use UnzerSDK\test\Helper\TestEnvironmentService; use UnzerSDK\Unzer; use UnzerSDK\Resources\PaymentTypes\Card; use UnzerSDK\Resources\PaymentTypes\Paypal; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebit; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebitSecured; -use UnzerSDK\Services\EnvironmentService; use UnzerSDK\test\BaseIntegrationTest; use RuntimeException; @@ -58,6 +43,8 @@ public function exceptionShouldBeThrownIfTheObjectIsNotAResource(): void * After recurring call the parameters are set. * * @test + * + * @deprecated since 1.2.1.0 Get removed with `activateRecurring` method. */ public function recurringForCardWith3dsShouldReturnAttributes(): void { @@ -78,10 +65,12 @@ public function recurringForCardWith3dsShouldReturnAttributes(): void * Verify card without 3ds can activate recurring payments. * * @test + * + * @deprecated since 1.2.1.0 Get removed with `activateRecurring` method. */ public function recurringForCardWithout3dsShouldActivateRecurringAtOnce(): void { - $privateKey = EnvironmentService::getTestPrivateKey(true); + $privateKey = TestEnvironmentService::getTestPrivateKey(true); if (empty($privateKey)) { $this->markTestIncomplete('No non 3ds private key set'); } @@ -110,7 +99,7 @@ public function paypalShouldBeAbleToActivateRecurringPayments(): void { /** @var Paypal $paypal */ $paypal = $this->unzer->createPaymentType(new Paypal()); - $recurring = $paypal->activateRecurring('https://dev.unzer.com', RecurrenceTypes::ONE_CLICK); + $recurring = $paypal->activateRecurring('https://dev.unzer.com'); $this->assertPending($recurring); $this->assertNotEmpty($recurring->getReturnUrl()); } @@ -122,6 +111,7 @@ public function paypalShouldBeAbleToActivateRecurringPayments(): void */ public function sepaDirectDebitShouldBeAbleToActivateRecurringPayments(): void { + $this->useLegacyKey(); /** @var SepaDirectDebit $dd */ $dd = $this->unzer->createPaymentType(new SepaDirectDebit('DE89370400440532013000')); $this->assertFalse($dd->isRecurring()); @@ -141,6 +131,7 @@ public function sepaDirectDebitShouldBeAbleToActivateRecurringPayments(): void */ public function sepaDirectDebitSecuredShouldBeAbleToActivateRecurringPayments(): void { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); /** @var SepaDirectDebitSecured $ddg */ $ddg = $this->unzer->createPaymentType(new SepaDirectDebitSecured('DE89370400440532013000')); $this->assertFalse($ddg->isRecurring()); @@ -153,7 +144,7 @@ public function sepaDirectDebitSecuredShouldBeAbleToActivateRecurringPayments(): $this->expectException(UnzerApiException::class); $this->expectExceptionCode(ApiResponseCodes::API_ERROR_RECURRING_ALREADY_ACTIVE); - $this->unzer->activateRecurringPayment($ddg, self::RETURN_URL, RecurrenceTypes::ONE_CLICK); + $this->unzer->activateRecurringPayment($ddg, self::RETURN_URL); } /** diff --git a/vendor/unzerdev/php-sdk/test/integration/SetMetadataTest.php b/vendor/unzerdev/php-sdk/test/integration/SetMetadataTest.php index 04750db..3391c16 100644 --- a/vendor/unzerdev/php-sdk/test/integration/SetMetadataTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/SetMetadataTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\ApiResponseCodes; diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/AuthorizationTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/AuthorizationTest.php index a2cbe8a..200097e 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/AuthorizationTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/AuthorizationTest.php @@ -1,32 +1,18 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; +use UnzerSDK\Constants\RecurrenceTypes; use UnzerSDK\Resources\AbstractUnzerResource; use UnzerSDK\Resources\Metadata; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; @@ -118,6 +104,7 @@ public function authorizationWithCustomerId(): Authorization * Verify authorization can be fetched. * * @depends authorizationWithCustomerId + * * @test * * @param Authorization $authorization @@ -125,13 +112,14 @@ public function authorizationWithCustomerId(): Authorization public function authorizationCanBeFetched(Authorization $authorization): void { $fetchedAuthorization = $this->unzer->fetchAuthorization($authorization->getPaymentId()); - $this->assertEquals($authorization->expose(), $fetchedAuthorization->expose()); + $this->assertEquals($authorization->setCard3ds(false)->expose(), $fetchedAuthorization->expose()); } /** * Verify authorization has the expected states. * * @test + * * @dataProvider authorizeHasExpectedStatesDP * * @param BasePaymentType|AbstractUnzerResource $paymentType @@ -162,7 +150,60 @@ public function authorizeShouldAcceptAllParameters(): void $invoiceId = 'i' . self::generateRandomId(); $paymentReference = 'paymentReference'; - $authorize = $card->authorize(119.0, 'EUR', self::RETURN_URL, $customer, $orderId, $metadata, $basket, true, $invoiceId, $paymentReference); + $authorize = $card->authorize(119.0, 'EUR', self::RETURN_URL, $customer, $orderId, $metadata, $basket, true, $invoiceId, $paymentReference, RecurrenceTypes::ONE_CLICK); + $payment = $authorize->getPayment(); + + $this->assertSame($card, $payment->getPaymentType()); + $this->assertEquals(119.0, $authorize->getAmount()); + $this->assertEquals('EUR', $authorize->getCurrency()); + $this->assertEquals(self::RETURN_URL, $authorize->getReturnUrl()); + $this->assertSame($customer, $payment->getCustomer()); + $this->assertEquals($orderId, $authorize->getOrderId()); + $this->assertSame($metadata, $payment->getMetadata()); + $this->assertSame($basket, $payment->getBasket()); + $this->assertTrue($authorize->isCard3ds()); + $this->assertEquals($invoiceId, $authorize->getInvoiceId()); + $this->assertEquals($paymentReference, $authorize->getPaymentReference()); + + $fetchedAuthorize = $this->unzer->fetchAuthorization($authorize->getPaymentId()); + $fetchedPayment = $fetchedAuthorize->getPayment(); + + $this->assertEquals($payment->getPaymentType()->expose(), $fetchedPayment->getPaymentType()->expose()); + $this->assertEquals($authorize->getAmount(), $fetchedAuthorize->getAmount()); + $this->assertEquals($authorize->getCurrency(), $fetchedAuthorize->getCurrency()); + $this->assertEquals($authorize->getReturnUrl(), $fetchedAuthorize->getReturnUrl()); + $this->assertEquals($payment->getCustomer()->expose(), $fetchedPayment->getCustomer()->expose()); + $this->assertEquals($authorize->getOrderId(), $fetchedAuthorize->getOrderId()); + $this->assertEquals($payment->getMetadata()->expose(), $fetchedPayment->getMetadata()->expose()); + $this->assertEquals($payment->getBasket()->expose(), $fetchedPayment->getBasket()->expose()); + $this->assertEquals($authorize->isCard3ds(), $fetchedAuthorize->isCard3ds()); + $this->assertEquals($authorize->getInvoiceId(), $fetchedAuthorize->getInvoiceId()); + $this->assertEquals($authorize->getPaymentReference(), $fetchedAuthorize->getPaymentReference()); + } + + /** + * Verify authorize accepts all parameters. + * + * @test + */ + public function requestAuthorizationShouldAcceptAllParameters(): void + { + /** @var Card $card */ + $card = $this->unzer->createPaymentType($this->createCardObject()); + $customer = $this->getMinimalCustomer(); + $orderId = 'o' . self::generateRandomId(); + $metadata = (new Metadata())->addMetadata('key', 'value'); + $basket = $this->createBasket(); + $invoiceId = 'i' . self::generateRandomId(); + $paymentReference = 'paymentReference'; + + $authorize = new Authorization(119.0, 'EUR', self::RETURN_URL); + $authorize->setRecurrenceType(RecurrenceTypes::ONE_CLICK, $card) + ->setOrderId($orderId) + ->setInvoiceId($invoiceId) + ->setPaymentReference($paymentReference); + + $authorize = $this->unzer->performAuthorization($authorize, $card, $customer, $metadata, $basket); $payment = $authorize->getPayment(); $this->assertSame($card, $payment->getPaymentType()); diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterAuthorizationTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterAuthorizationTest.php index dd3d83e..4a30030 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterAuthorizationTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterAuthorizationTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; use UnzerSDK\Resources\TransactionTypes\Authorization; diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterChargeTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterChargeTest.php index 659eb4f..bd0b9b5 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterChargeTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelAfterChargeTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebit; @@ -32,6 +17,11 @@ class CancelAfterChargeTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->useLegacyKey(); + } + /** * Verify charge can be fetched by id. * @@ -45,7 +35,7 @@ public function chargeShouldBeFetchable(): Charge $charge = $this->unzer->charge(100.0000, 'EUR', $paymentType, self::RETURN_URL); $fetchedCharge = $this->unzer->fetchChargeById($charge->getPayment()->getId(), $charge->getId()); - $chargeArray = $charge->expose(); + $chargeArray = $charge->setCard3ds(false)->expose(); $this->assertEquals($chargeArray, $fetchedCharge->expose()); return $charge; @@ -55,6 +45,7 @@ public function chargeShouldBeFetchable(): Charge * Verify full refund of a charge. * * @test + * * @depends chargeShouldBeFetchable * * @param Charge $charge diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelTest.php index 4a8b0ca..f399dcc 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/CancelTest.php @@ -1,31 +1,17 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; +use UnzerSDK\Resources\TransactionTypes\Cancellation; use UnzerSDK\test\BaseIntegrationTest; class CancelTest extends BaseIntegrationTest @@ -65,6 +51,7 @@ public function reversalShouldBeFetchableViaPaymentObject(): void */ public function refundShouldBeFetchableViaUnzerObject(): void { + $this->useLegacyKey(); $charge = $this->createCharge(); $cancel = $charge->cancel(); $fetchedCancel = $this->unzer->fetchRefundById($charge->getPayment()->getId(), $charge->getId(), $cancel->getId()); @@ -79,8 +66,10 @@ public function refundShouldBeFetchableViaUnzerObject(): void */ public function refundShouldBeFetchableViaPaymentObject(): void { + $this->useLegacyKey(); $charge = $this->createCharge(); - $cancel = $charge->cancel(); + $cancel = new Cancellation(); + $this->getUnzerObject()->cancelChargedPayment($charge->getPayment(), $cancel); $fetchedCancel = $cancel->getPayment()->getCharge($charge->getId())->getCancellation($cancel->getId()); $this->assertTransactionResourceHasBeenCreated($fetchedCancel); $this->assertEquals($cancel->expose(), $fetchedCancel->expose()); @@ -97,7 +86,7 @@ public function authorizationCancellationsShouldBeFetchableViaPaymentObject(): v $reversal = $authorization->cancel(); $fetchedPayment = $this->unzer->fetchPayment($authorization->getPayment()->getId()); - $cancellation = $fetchedPayment->getCancellation($reversal->getId()); + $cancellation = $fetchedPayment->getAuthorization()->getCancellation($reversal->getId()); $this->assertTransactionResourceHasBeenCreated($cancellation); $this->assertEquals($cancellation->expose(), $reversal->expose()); } @@ -109,13 +98,14 @@ public function authorizationCancellationsShouldBeFetchableViaPaymentObject(): v */ public function chargeCancellationsShouldBeFetchableViaPaymentObject(): void { + $this->useLegacyKey(); $charge = $this->createCharge(); - $reversal = $charge->cancel(); + $refund = $charge->cancel(); $fetchedPayment = $this->unzer->fetchPayment($charge->getPayment()->getId()); - $cancellation = $fetchedPayment->getCancellation($reversal->getId()); + $cancellation = $fetchedPayment->getCharge($charge->getId())->getCancellation($refund->getId()); $this->assertTransactionResourceHasBeenCreated($cancellation); - $this->assertEquals($cancellation->expose(), $reversal->expose()); + $this->assertEquals($cancellation->expose(), $refund->expose()); } /** @@ -125,6 +115,7 @@ public function chargeCancellationsShouldBeFetchableViaPaymentObject(): void */ public function cancelStatusIsSetCorrectly(): void { + $this->useLegacyKey(); $charge = $this->createCharge(); $reversal = $charge->cancel(); $this->assertSuccess($reversal); diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeAfterAuthorizationTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeAfterAuthorizationTest.php index b96f567..8adfa04 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeAfterAuthorizationTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeAfterAuthorizationTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; use UnzerSDK\test\BaseIntegrationTest; diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeTest.php index 7b326e3..f9f489a 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ChargeTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; use UnzerSDK\Constants\RecurrenceTypes; @@ -32,7 +17,9 @@ use UnzerSDK\Resources\PaymentTypes\Card; use UnzerSDK\Resources\PaymentTypes\InvoiceSecured; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebit; +use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class ChargeTest extends BaseIntegrationTest { @@ -43,6 +30,7 @@ class ChargeTest extends BaseIntegrationTest */ public function chargeShouldWorkWithTypeId(): void { + $this->useLegacyKey(); $paymentType = $this->unzer->createPaymentType(new SepaDirectDebit('DE89370400440532013000')); $charge = $this->unzer->charge(100.0, 'EUR', $paymentType->getId(), self::RETURN_URL); $this->assertTransactionResourceHasBeenCreated($charge); @@ -58,6 +46,7 @@ public function chargeShouldWorkWithTypeId(): void */ public function chargeShouldWorkWithTypeObject(): void { + $this->useLegacyKey(); $paymentType = $this->unzer->createPaymentType(new SepaDirectDebit('DE89370400440532013000')); $charge = $this->unzer->charge(100.0, 'EUR', $paymentType, self::RETURN_URL); $this->assertTransactionResourceHasBeenCreated($charge); @@ -73,6 +62,7 @@ public function chargeShouldWorkWithTypeObject(): void */ public function chargeStatusIsSetCorrectly(): void { + $this->useLegacyKey(); $this->assertSuccess($this->createCharge()); } @@ -124,6 +114,60 @@ public function chargeShouldAcceptAllParameters(): void $this->assertEquals($payment->getBasket()->expose(), $fetchedPayment->getBasket()->expose()); } + /** + * Verify requestCharge accepts all parameters. + * + * @test + */ + public function requestChargeShouldAcceptAllParameters(): void + { + // prepare test data + /** @var Card $paymentType */ + $paymentType = $this->unzer->createPaymentType($this->createCardObject()); + $customer = $this->getMinimalCustomer(); + $orderId = 'o'. self::generateRandomId(); + $metadata = (new Metadata())->addMetadata('key', 'value'); + $basket = $this->createBasket(); + $invoiceId = 'i'. self::generateRandomId(); + $paymentReference = 'paymentReference'; + $recurrenceType = RecurrenceTypes::ONE_CLICK; + + // perform request + $charge = new Charge(119.0, 'EUR', self::RETURN_URL); + $charge->setRecurrenceType(RecurrenceTypes::ONE_CLICK, $paymentType) + ->setOrderId($orderId) + ->setInvoiceId($invoiceId) + ->setPaymentReference($paymentReference); + + $charge = $this->unzer->performCharge($charge, $paymentType, $customer, $metadata, $basket); + + // verify the data sent and received match + $payment = $charge->getPayment(); + $this->assertSame($paymentType, $payment->getPaymentType()); + $this->assertEquals(119.0, $charge->getAmount()); + $this->assertEquals('EUR', $charge->getCurrency()); + $this->assertEquals(self::RETURN_URL, $charge->getReturnUrl()); + $this->assertSame($customer, $payment->getCustomer()); + $this->assertEquals($orderId, $charge->getOrderId()); + $this->assertSame($metadata, $payment->getMetadata()); + $this->assertSame($basket, $payment->getBasket()); + $this->assertTrue($charge->isCard3ds()); + $this->assertEquals($invoiceId, $charge->getInvoiceId()); + $this->assertEquals($paymentReference, $charge->getPaymentReference()); + $this->assertEquals($recurrenceType, $charge->getRecurrenceType()); + + // fetch the charge + $fetchedCharge = $this->unzer->fetchChargeById($charge->getPaymentId(), $charge->getId()); + + // verify the fetched transaction matches the initial transaction + $this->assertEquals($charge->expose(), $fetchedCharge->expose()); + $fetchedPayment = $fetchedCharge->getPayment(); + $this->assertEquals($payment->getPaymentType()->expose(), $fetchedPayment->getPaymentType()->expose()); + $this->assertEquals($payment->getCustomer()->expose(), $fetchedPayment->getCustomer()->expose()); + $this->assertEquals($payment->getMetadata()->expose(), $fetchedPayment->getMetadata()->expose()); + $this->assertEquals($payment->getBasket()->expose(), $fetchedPayment->getBasket()->expose()); + } + /** * Verify charge accepts all parameters. * @@ -131,6 +175,7 @@ public function chargeShouldAcceptAllParameters(): void */ public function chargeWithCustomerShouldAcceptAllParameters(): void { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); // prepare test data /** @var InvoiceSecured $ivg */ $ivg = $this->unzer->createPaymentType(new InvoiceSecured()); @@ -159,6 +204,26 @@ public function chargeWithCustomerShouldAcceptAllParameters(): void $this->assertEquals($paymentReference, $charge->getPaymentReference()); $fetchedCharge = $this->unzer->fetchChargeById($charge->getPaymentId(), $charge->getId()); - $this->assertEquals($charge->expose(), $fetchedCharge->expose()); + $this->assertEquals($charge->setCard3ds(false)->expose(), $fetchedCharge->expose()); + } + + /** + * Verify checkoutType for not supported type gets ignored by Api. + * + * @test + */ + public function checkoutTypeGetsIgnordedByApiWithNotSupportedType() + { + $paymentType = $this->unzer->createPaymentType($this->createCardObject()); + $charge = new Charge(99.99, 'EUR', self::RETURN_URL); + $charge->setCheckoutType('express', $paymentType); + $this->getUnzerObject()->performCharge($charge, $paymentType); + + $fetchedCharge = $this->getUnzerObject()->fetchChargeById( + $charge->getPayment()->getId(), + $charge->getId() + ); + $this->assertTrue($fetchedCharge->isPending()); + $this->assertNull($fetchedCharge->getCheckoutType()); } } diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/PaylaterCancelTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/PaylaterCancelTest.php new file mode 100644 index 0000000..05451e5 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/PaylaterCancelTest.php @@ -0,0 +1,200 @@ +createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $cancellation = (new Cancellation())->setInvoiceId('i' . self::generateRandomId()); + $cancel = $this->unzer->cancelAuthorizedPayment($payment, $cancellation); + + $this->assertTrue($cancel->isSuccess()); + $this->assertNull($cancel->getParentResource()->getId()); + $this->assertCount(1, $payment->getCancellations()); + $this->assertCount(1, $payment->getReversals()); + $this->assertCount(0, $authorization->getCancellations()); + } + + /** + * @test + */ + public function reversalIsPossibleWOCancellationObject(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $cancel = $this->unzer->cancelAuthorizedPayment($payment); + + $this->assertTrue($cancel->isSuccess()); + $this->assertNull($cancel->getParentResource()->getId()); + $this->assertCount(1, $payment->getCancellations()); + $this->assertCount(1, $payment->getReversals()); + $this->assertCount(0, $authorization->getCancellations()); + } + + /** + * @test + */ + public function reversalIsFetchableViaUnzerFacade(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $cancel = $this->unzer->cancelAuthorizedPayment($payment, new Cancellation()); + $fetchedCancel = $this->unzer->fetchPaymentReversal($payment, $cancel->getId()); + + $this->assertNull($fetchedCancel->getParentResource()->getId()); + $this->assertEquals($cancel->getShortId(), $fetchedCancel->getShortId()); + $this->assertEquals($payment, $fetchedCancel->getPayment()); + $this->assertCount(1, $payment->getReversals()); + $this->assertCount(0, $payment->getRefunds()); + } + + /** + * @test + */ + public function verifyPartReversalIsPossible(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $reversalAmount = 33.33; + $this->assertAmounts($authorization->getPayment(), 99.99, 0, 99.99, 0); + + $this->unzer->cancelAuthorizedPayment($authorization->getPayment(), new Cancellation($reversalAmount)); + $this->assertAmounts($authorization->getPayment(), 66.66, 0, 66.66, 0); + } + + /** + * @test + */ + public function fullRefundWorksViaUnzerFacadeAsExpected(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $charge = $this->unzer->performChargeOnPayment($payment, new Charge()); + $cancellation = (new Cancellation())->setInvoiceId('i' . self::generateRandomId()); + $cancel = $this->unzer->cancelChargedPayment($payment, $cancellation); + + $this->assertInstanceOf(Charge::class, $cancel->getParentResource()); + $this->assertNull($cancel->getParentResource()->getId()); + + $this->assertTrue($cancel->isSuccess()); + $this->assertCount(1, $payment->getCancellations()); + $this->assertCount(1, $payment->getRefunds()); + $this->assertCount(0, $payment->getReversals()); + $this->assertCount(0, $charge->getCancellations()); + } + + /** + * @test + */ + public function fullRefundIsPossibleWOCancellationObject(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $charge = $this->unzer->performChargeOnPayment($payment, new Charge()); + $cancel = $this->unzer->cancelChargedPayment($payment); + + $this->assertInstanceOf(Charge::class, $cancel->getParentResource()); + $this->assertNull($cancel->getParentResource()->getId()); + + $this->assertTrue($cancel->isSuccess()); + $this->assertCount(1, $payment->getCancellations()); + $this->assertCount(1, $payment->getRefunds()); + $this->assertCount(0, $payment->getReversals()); + $this->assertCount(0, $charge->getCancellations()); + } + + /** + * @test + */ + public function partRefundIsPossibleViaUnzerFacade(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $this->unzer->performChargeOnPayment($payment, new Charge()); + + $cancel1 = $this->unzer->cancelChargedPayment($payment, new Cancellation(22.22)); + $cancel2 = $this->unzer->cancelChargedPayment($payment, new Cancellation(33.33)); + $cancel3 = $this->unzer->cancelChargedPayment($payment, new Cancellation(44.44)); + + $this->assertTrue($cancel1->isSuccess()); + $this->assertEquals(22.22, $cancel1->getAmount()); + + $this->assertTrue($cancel2->isSuccess()); + $this->assertEquals(33.33, $cancel2->getAmount()); + + $this->assertTrue($cancel3->isSuccess()); + $this->assertEquals(44.44, $cancel3->getAmount()); + + $this->assertCount(3, $payment->getCancellations()); + $refunds = $payment->getRefunds(); + $this->assertCount(3, $refunds); + $this->assertArrayHasKey('s-cnl-1', $refunds); + $this->assertArrayHasKey('s-cnl-2', $refunds); + $this->assertArrayHasKey('s-cnl-3', $refunds); + } + + /** + * @test + */ + public function reversalOnChargedPaymentThrowsException(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $charge1 = $this->unzer->performChargeOnPayment($payment, new Charge(11.11)); + $this->expectException(UnzerApiException::class); + + $cancel = $this->unzer->cancelAuthorizedPayment($payment, new Cancellation()); + $this->assertTrue($cancel->isSuccess()); + } + + /** + * @test + */ + public function ChargeToHighAmountThrowsException(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $this->expectException(UnzerApiException::class); + $this->unzer->performChargeOnPayment($payment, new Charge(100)); + } + + /** + * @test + */ + public function refundShouldBeFetchableViaUnzerObject(): void + { + $authorization = $this->createPaylaterInvoiceAuthorization(); + $payment = $authorization->getPayment(); + $this->unzer->performChargeOnPayment($payment, new Charge()); + $cancel = $this->unzer->cancelChargedPayment($payment, new Cancellation(33.33)); + + $fetchedCancel = $this->unzer->fetchPaymentRefund($payment, $cancel->getId()); + + $this->assertEquals($cancel->getShortId(), $fetchedCancel->getShortId()); + $this->assertEquals($payment->getId(), $fetchedCancel->getPayment()->getId()); + $this->assertInstanceOf(Charge::class, $fetchedCancel->getParentResource()); + + $this->assertCount(1, $payment->getCancellations()); + $this->assertCount(1, $payment->getRefunds()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/PayoutTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/PayoutTest.php index dcecf7f..5f0c823 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/PayoutTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/PayoutTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; use UnzerSDK\Resources\Metadata; @@ -34,6 +19,7 @@ use UnzerSDK\Resources\TransactionTypes\Payout; use UnzerSDK\Services\ResourceService; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class PayoutTest extends BaseIntegrationTest { @@ -68,6 +54,7 @@ public function payoutCanBeCalledForCardType(): void */ public function payoutCanBeCalledForSepaDirectDebitType(): void { + $this->useLegacyKey(); $sepa = new SepaDirectDebit('DE89370400440532013000'); $this->unzer->createPaymentType($sepa); $payout = $sepa->payout(100.0, 'EUR', self::RETURN_URL); @@ -87,6 +74,7 @@ public function payoutCanBeCalledForSepaDirectDebitType(): void */ public function payoutCanBeCalledForSepaDirectDebitSecuredType(): void { + $this->getUnzerObject()->setKey(TestEnvironmentService::getLegacyTestPrivateKey()); $sepa = new SepaDirectDebitSecured('DE89370400440532013000'); $this->unzer->createPaymentType($sepa); $customer = $this->getMaximumCustomer()->setShippingAddress($this->getBillingAddress()); @@ -100,7 +88,7 @@ public function payoutCanBeCalledForSepaDirectDebitSecuredType(): void $this->assertEquals(self::RETURN_URL, $payout->getReturnUrl()); $this->assertAmounts($payment, 0, 0, -100, 0); } - + /** * Verify Payout transaction is fetched with Payment resource. * diff --git a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ShipmentTest.php b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ShipmentTest.php index e3f5644..b5cea7b 100644 --- a/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ShipmentTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/TransactionTypes/ShipmentTest.php @@ -1,36 +1,27 @@ - * - * @package UnzerSDK\test\integration\TransactionTypes */ + namespace UnzerSDK\test\integration\TransactionTypes; use UnzerSDK\Resources\PaymentTypes\InvoiceSecured; use UnzerSDK\test\BaseIntegrationTest; +use UnzerSDK\test\Helper\TestEnvironmentService; class ShipmentTest extends BaseIntegrationTest { + protected function setUp(): void + { + $this->getUnzerObject(TestEnvironmentService::getLegacyTestPrivateKey()); + } + /** * Verify shipment transaction can be called. * diff --git a/vendor/unzerdev/php-sdk/test/integration/WebhookTest.php b/vendor/unzerdev/php-sdk/test/integration/WebhookTest.php index 57fa49a..5ea8e80 100644 --- a/vendor/unzerdev/php-sdk/test/integration/WebhookTest.php +++ b/vendor/unzerdev/php-sdk/test/integration/WebhookTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\integration */ + namespace UnzerSDK\test\integration; use UnzerSDK\Constants\ApiResponseCodes; @@ -31,6 +16,7 @@ use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\Webhook; use UnzerSDK\test\BaseIntegrationTest; + use function count; use function in_array; @@ -186,6 +172,7 @@ public function allWebhooksShouldBeRemovableAtOnce(): void * Verify setting multiple events at once. * * @test + * * @depends allWebhooksShouldBeRemovableAtOnce */ public function bulkSettingWebhookEventsShouldBePossible(): void @@ -249,7 +236,7 @@ private function generateUniqueUrl(): string /** * Returns true if the given Webhook exists in the given array. * - * @param $webhooksArray + * @param $webhooksArray * @param Webhook $webhook * * @return bool diff --git a/vendor/unzerdev/php-sdk/test/unit/Adapter/ApplepaySessionTest.php b/vendor/unzerdev/php-sdk/test/unit/Adapter/ApplepaySessionTest.php index 84dfa01..d2a2258 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Adapter/ApplepaySessionTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Adapter/ApplepaySessionTest.php @@ -2,26 +2,8 @@ /* * Test class for ApplepaySession. * - * Copyright (C) 2021 - today Unzer E-Com GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * * @link https://docs.unzer.com/ * - * @author David Owusu - * - * @package UnzerSDK - * */ namespace UnzerSDK\test\unit\Adapter; diff --git a/vendor/unzerdev/php-sdk/test/unit/Constants/PaymentStateTest.php b/vendor/unzerdev/php-sdk/test/unit/Constants/PaymentStateTest.php index e80cd3a..dd1300d 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Constants/PaymentStateTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Constants/PaymentStateTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Constants; use UnzerSDK\Constants\PaymentState; @@ -36,6 +21,7 @@ class PaymentStateTest extends BasePaymentTest * This should verify the mapping of the payment state to the state code. * * @test + * * @dataProvider codeToNameDataProvider * * @param integer $code @@ -50,6 +36,7 @@ public function shouldMapCodeToName($code, $name): void * This should verify the mapping of the payment state to the state code. * * @test + * * @dataProvider nameToCodeDataProvider * * @param integer $code @@ -69,7 +56,7 @@ public function mapCodeToNameShouldThrowAnExceptionIfTheCodeIsUnknown(): void { $this->expectException(RuntimeException::class); - PaymentState::mapStateCodeToName(6); + PaymentState::mapStateCodeToName(7); } /** diff --git a/vendor/unzerdev/php-sdk/test/unit/DummyResource.php b/vendor/unzerdev/php-sdk/test/unit/DummyResource.php index 2bd54fe..2a7f34c 100644 --- a/vendor/unzerdev/php-sdk/test/unit/DummyResource.php +++ b/vendor/unzerdev/php-sdk/test/unit/DummyResource.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit; use UnzerSDK\Adapter\HttpAdapterInterface; @@ -63,7 +48,7 @@ public function jsonSerialize() return '{"dummyResource": "JsonSerialized"}'; } - public function getUri($appendId = true, $httpMethod = HttpAdapterInterface::REQUEST_GET): string + public function getUri(bool $appendId = true, string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return '/my/uri' . ($appendId ? '/123' : ''); } diff --git a/vendor/unzerdev/php-sdk/test/unit/Exceptions/UnzerApiExceptionTest.php b/vendor/unzerdev/php-sdk/test/unit/Exceptions/UnzerApiExceptionTest.php index c793f7a..0d2f129 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Exceptions/UnzerApiExceptionTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Exceptions/UnzerApiExceptionTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Exceptions; use UnzerSDK\Exceptions\UnzerApiException; @@ -49,6 +34,7 @@ public function unzerApiExceptionShouldReturnDefaultDataWhenNoneIsSet(): void * Verify the exception stores the given data. * * @test + * * @dataProvider exceptionDataProvider * * @param array $expected diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/AbstractUnzerResourceTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/AbstractUnzerResourceTest.php index 2409f85..2212a5c 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/AbstractUnzerResourceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/AbstractUnzerResourceTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use DateTime; @@ -83,6 +68,8 @@ public function settersAndGettersShouldWork(): void $customer->setFetchedAt(new DateTime('2018-12-03')); $this->assertEquals(new DateTime('2018-12-03'), $customer->getFetchedAt()); + + $this->assertEquals(Unzer::API_VERSION, $customer->getApiVersion()); } /** @@ -188,7 +175,7 @@ public function fetchPaymentContainsNoTypeNameInUri(AbstractUnzerResource $resou /** * Verify that installment plans use the correct path for fetching. Special case, fetching Instalmentplans contains - * hinstallment-secured as parent resource that should appear in resource path. + * Installment-secured as parent resource that should appear in resource path. * * @test */ @@ -493,8 +480,8 @@ public function fetchUriDataProvider() 'Webhooks' => [new Webhook(), 'parent/resource/path/webhooks'], 'Recurring' => [new Recurring('s-crd-123', ''), 'parent/resource/path/types/s-crd-123/recurring'], 'Payout' => [new Payout(), 'parent/resource/path/payouts'], - 'PayPage charge' => [new Paypage(123.4567, 'EUR', 'url'), 'parent/resource/path/paypage/charge'], - 'PayPage authorize' => [(new Paypage(123.4567, 'EUR', 'url'))->setAction(TransactionTypes::AUTHORIZATION), 'parent/resource/path/paypage/authorize'], + 'PayPage charge' => [new Paypage(123.4567, 'EUR', 'url'), 'parent/resource/path/paypage'], + 'PayPage authorize' => [(new Paypage(123.4567, 'EUR', 'url'))->setAction(TransactionTypes::AUTHORIZATION), 'parent/resource/path/paypage'], ]; } } diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/BasketTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/BasketTest.php index 12602ea..fbf4af9 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/BasketTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/BasketTest.php @@ -1,35 +1,21 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; +use stdClass; use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\EmbeddedResources\BasketItem; use UnzerSDK\test\BasePaymentTest; -use stdClass; +use UnzerSDK\Unzer; class BasketTest extends BasePaymentTest { @@ -44,6 +30,7 @@ public function gettersAndSettersShouldWorkProperly(): void $this->assertEquals(0, $basket->getAmountTotalGross()); $this->assertEquals(0, $basket->getAmountTotalDiscount()); $this->assertEquals(0, $basket->getAmountTotalVat()); + $this->assertEquals(0, $basket->getTotalValueGross()); $this->assertEquals('EUR', $basket->getCurrencyCode()); $this->assertEquals('', $basket->getNote()); $this->assertEquals('', $basket->getOrderId()); @@ -51,12 +38,14 @@ public function gettersAndSettersShouldWorkProperly(): void $this->assertNull($basket->getBasketItemByIndex(1)); $basket->setAmountTotalGross(12.34); + $basket->setTotalValueGross(99.99); $basket->setAmountTotalDiscount(34.56); $basket->setAmountTotalVat(45.67); $basket->setCurrencyCode('USD'); $basket->setNote('This is something I have to remember!'); $basket->setOrderId('myOrderId'); $this->assertEquals(12.34, $basket->getAmountTotalGross()); + $this->assertEquals(99.99, $basket->getTotalValueGross()); $this->assertEquals(34.56, $basket->getAmountTotalDiscount()); $this->assertEquals(45.67, $basket->getAmountTotalVat()); $this->assertEquals('USD', $basket->getCurrencyCode()); @@ -155,4 +144,39 @@ public function referenceIdShouldBeAutomaticallySetToTheArrayIndexIfItIsNotSet() $this->assertEquals('0', $basketItem3->getBasketItemReferenceId()); $this->assertEquals('1', $basketItem4->getBasketItemReferenceId()); } + + /** + * Verify basket provides expected API version based ond set parameters. + * + * @test + * + * @dataProvider getApiVersionShouldReturnExpectedVersionDP + * + * @param Basket $basket + * @param $expectedApiVersion + */ + public function getApiVersionShouldReturnExpectedVersion(Basket $basket, $expectedApiVersion): void + { + $this->assertEquals($expectedApiVersion, $basket->getApiVersion()); + } + + // + + /** + * @return array + */ + public function getApiVersionShouldReturnExpectedVersionDP(): array + { + $v1Basket = (new Basket())->setAmountTotalGross(100); + $v2Basket = (new Basket())->setTotalValueGross(100); + $mixedBasket = (new Basket())->setAmountTotalGross(100)->setTotalValueGross(100); + return [ + 'empty basket ' => [new Basket(), Unzer::API_VERSION], + 'minimum v1 basket ' => [$v1Basket, Unzer::API_VERSION], + 'minimum v2 basket ' => [$v2Basket, BasePaymentTest::API_VERSION_2], + 'mixed v1/v2 basket ' => [$mixedBasket, BasePaymentTest::API_VERSION_2], + ]; + } + + // } diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/ConfigTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/ConfigTest.php new file mode 100644 index 0000000..dab4ba0 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/ConfigTest.php @@ -0,0 +1,64 @@ +assertNull($config->getDataPrivacyConsent()); + $this->assertNull($config->getDataPrivacyDeclaration()); + $this->assertNull($config->getTermsAndConditions()); + $this->assertIsEmptyArray($config->getQueryParams()); + + $config->setDataPrivacyConsent('dataPrivacyConsent') + ->setDataPrivacyDeclaration('dataPrivacyDeclaration') + ->setTermsAndConditions('termsAndConditions'); + + $this->assertEquals('dataPrivacyConsent', $config->getDataPrivacyConsent()); + $this->assertEquals('dataPrivacyDeclaration', $config->getDataPrivacyDeclaration()); + $this->assertEquals('termsAndConditions', $config->getTermsAndConditions()); + } + + /** + * Verify query params can be set via Config class. + * + * @test + */ + public function queryParameterCanBeSetViaConfigClass(): void + { + $config = new Config(); + $queryParams = $config->getQueryParams(); + $this->assertIsEmptyArray($queryParams); + + $queryArray = [ + 'param1' => 'param1', + 'param2' => 'param2', + 'param3' => 'param3', + ]; + + $config->setQueryParams($queryArray); + $updatedParams = $config->getQueryParams(); + $this->assertEquals('param1', $updatedParams['param1']); + $this->assertEquals('param2', $updatedParams['param2']); + $this->assertEquals('param3', $updatedParams['param3']); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerFactoryTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerFactoryTest.php index 826521c..94d2488 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerFactoryTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerFactoryTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Constants\CompanyCommercialSectorItems; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerTest.php index c52fa05..0f11b1f 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/CustomerTest.php @@ -1,34 +1,20 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Constants\CompanyCommercialSectorItems; use UnzerSDK\Constants\CompanyRegistrationTypes; use UnzerSDK\Constants\Salutations; +use UnzerSDK\Resources\EmbeddedResources\CompanyOwner; use UnzerSDK\Unzer; use UnzerSDK\Interfaces\ResourceServiceInterface; use UnzerSDK\Resources\Customer; @@ -134,7 +120,8 @@ public function settersAndGettersOfShippingAddressShouldWork(): void ->setName('shipping_name') ->setCity('shipping_city') ->setZip('shipping_zip') - ->setStreet('shipping_street'); + ->setStreet('shipping_street') + ->setShippingType('shipping_type'); $customer = new Customer(); $shippingAddress = $customer->getBillingAddress(); @@ -144,6 +131,7 @@ public function settersAndGettersOfShippingAddressShouldWork(): void $this->assertNull($shippingAddress->getCity()); $this->assertNull($shippingAddress->getZip()); $this->assertNull($shippingAddress->getStreet()); + $this->assertNull($shippingAddress->getShippingType()); $customer->setShippingAddress($address); $shippingAddress = $customer->getShippingAddress(); @@ -153,6 +141,7 @@ public function settersAndGettersOfShippingAddressShouldWork(): void $this->assertEquals('shipping_city', $shippingAddress->getCity()); $this->assertEquals('shipping_zip', $shippingAddress->getZip()); $this->assertEquals('shipping_street', $shippingAddress->getStreet()); + $this->assertEquals('shipping_type', $shippingAddress->getShippingType()); } /** @@ -167,6 +156,8 @@ public function gettersAndSettersOfCompanyInfoShouldWork(): void $this->assertNull($companyInfo->getCommercialRegisterNumber()); $this->assertNull($companyInfo->getFunction()); $this->assertNull($companyInfo->getRegistrationType()); + $this->assertNull($companyInfo->getCompanyType()); + $this->assertNull($companyInfo->getOwner()); $companyInfo->setCommercialSector(CompanyCommercialSectorItems::ACCOMMODATION); $this->assertSame(CompanyCommercialSectorItems::ACCOMMODATION, $companyInfo->getCommercialSector()); @@ -180,6 +171,15 @@ public function gettersAndSettersOfCompanyInfoShouldWork(): void $companyInfo->setRegistrationType(CompanyRegistrationTypes::REGISTRATION_TYPE_REGISTERED); $this->assertSame(CompanyRegistrationTypes::REGISTRATION_TYPE_REGISTERED, $companyInfo->getRegistrationType()); + $companyInfo->setCompanyType('companyType'); + $this->assertSame('companyType', $companyInfo->getCompanyType()); + + $owner = (new CompanyOwner())->setFirstname('firstname') + ->setLastname('lastname') + ->setBirthdate('01.01.1999'); + $companyInfo->setOwner($owner); + $this->assertEquals($owner, $companyInfo->getOwner()); + $customer = new Customer(); $this->assertNull($customer->getCompanyInfo()); $customer->setCompanyInfo($companyInfo); @@ -312,6 +312,38 @@ public function customerShouldBeUpdateable(): void $this->assertEquals('country code', $geoLocation->getCountryCode()); } + /** + * Verify that CompanyOwner data are correctly set when handling a response. + * + * @test + */ + public function handleResponseShouldSetCompanyOwnerData() + { + $customer = new Customer(); + $this->assertEmpty($customer->getCompanyInfo()); + + $owner = (object)[ + 'firstname' => 'firstname', + 'lastname' => 'lastname', + 'birthdate' => 'birthdate', + ]; + + $customerResponse = (object)[ + 'companyInfo' => (object)[ + 'owner' => $owner + ] + ]; + + $customer->handleResponse($customerResponse); + + $this->assertNotEmpty($customer->getCompanyInfo()); + $companyOwner = $customer->getCompanyInfo()->getOwner(); + $this->assertNotEmpty($companyOwner); + $this->assertEquals('firstname', $companyOwner->getFirstname()); + $this->assertEquals('lastname', $companyOwner->getLastname()); + $this->assertEquals('birthdate', $companyOwner->getBirthdate()); + } + // // diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/DummyUnzerResource.php b/vendor/unzerdev/php-sdk/test/unit/Resources/DummyUnzerResource.php index 22dc6b8..06d4bbc 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/DummyUnzerResource.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/DummyUnzerResource.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Resources\AbstractUnzerResource; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/AmountTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/AmountTest.php index 0d1b3da..0f8d894 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/AmountTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/AmountTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\EmbeddedResources; use UnzerSDK\Resources\EmbeddedResources\Amount; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/ApplePayHeaderTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/ApplePayHeaderTest.php index 0dc6a20..372e1b2 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/ApplePayHeaderTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/ApplePayHeaderTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\EmbeddedResources; use UnzerSDK\Resources\EmbeddedResources\ApplePayHeader; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/BasketItemTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/BasketItemTest.php index a422db7..bf5b3b1 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/BasketItemTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/BasketItemTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\EmbeddedResources; use UnzerSDK\Resources\EmbeddedResources\BasketItem; @@ -42,6 +27,8 @@ public function settersAndGettersShouldWork(): void $this->assertEquals(1, $basketItem->getQuantity()); $this->assertEquals(0, $basketItem->getAmountDiscount()); $this->assertEquals(0, $basketItem->getAmountGross()); + $this->assertEquals(0, $basketItem->getAmountPerUnitGross()); + $this->assertEquals(0, $basketItem->getAmountDiscountPerUnitGross()); $this->assertEquals(0, $basketItem->getAmountPerUnit()); $this->assertEquals(0, $basketItem->getAmountNet()); $this->assertEquals(0, $basketItem->getAmountVat()); @@ -59,6 +46,8 @@ public function settersAndGettersShouldWork(): void $basketItem->setAmountNet(6543); $basketItem->setAmountVat(5432); $basketItem->setVat(6543); + $basketItem->setAmountPerUnitGross(5432); + $basketItem->setAmountDiscountPerUnitGross(4321); $basketItem->setBasketItemReferenceId('myRefId'); $basketItem->setUnit('myUnit'); $basketItem->setTitle('myTitle'); @@ -73,6 +62,8 @@ public function settersAndGettersShouldWork(): void $this->assertEquals(6543, $basketItem->getAmountNet()); $this->assertEquals(5432, $basketItem->getAmountVat()); $this->assertEquals(6543, $basketItem->getVat()); + $this->assertEquals(5432, $basketItem->getAmountPerUnitGross()); + $this->assertEquals(4321, $basketItem->getAmountDiscountPerUnitGross()); $this->assertEquals('myRefId', $basketItem->getBasketItemReferenceId()); $this->assertEquals('myUnit', $basketItem->getUnit()); $this->assertEquals('myTitle', $basketItem->getTitle()); diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/CompanyOwnerTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/CompanyOwnerTest.php new file mode 100644 index 0000000..f25bda5 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/CompanyOwnerTest.php @@ -0,0 +1,36 @@ +assertNull($owner->getFirstname()); + $this->assertNull($owner->getLastname()); + $this->assertNull($owner->getBirthdate()); + + $owner->setFirstname('firstname') + ->setLastname('lastname') + ->setBirthdate('01.01.1999'); + + $this->assertEquals('firstname', $owner->getFirstname()); + $this->assertEquals('lastname', $owner->getLastname()); + $this->assertEquals('01.01.1999', $owner->getBirthdate()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/GeoLocationTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/GeoLocationTest.php index 1ac024e..19c9d6e 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/GeoLocationTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/GeoLocationTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\EmbeddedResources; use UnzerSDK\Resources\EmbeddedResources\GeoLocation; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/RiskDataTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/RiskDataTest.php new file mode 100644 index 0000000..1fa5123 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/RiskDataTest.php @@ -0,0 +1,55 @@ +assertNull($riskData->getRegistrationDate()); + $this->assertNull($riskData->getRegistrationLevel()); + $this->assertNull($riskData->getThreatMetrixId()); + $this->assertNull($riskData->getConfirmedAmount()); + $this->assertNull($riskData->getConfirmedAmount()); + $this->assertNull($riskData->getCustomerGroup()); + $this->assertNull($riskData->getCustomerId()); + + $resp = [ + "threatMetrixId" => "f544if49wo4f74ef1x", + "customerGroup" => "TOP", + "customerId" => "C-122345", + "confirmedAmount" => "2569", + "confirmedOrders" => "14", + "registrationLevel" => "1", + "registrationDate" => "20160412" + ]; + $riskData->handleResponse((object)$resp); + + $this->assertEquals('f544if49wo4f74ef1x', $riskData->getThreatMetrixId()); + $this->assertEquals('TOP', $riskData->getCustomerGroup()); + $this->assertEquals('C-122345', $riskData->getCustomerId()); + $this->assertEquals(2569, $riskData->getConfirmedAmount()); + $this->assertEquals(14, $riskData->getConfirmedOrders()); + $this->assertEquals('1', $riskData->getRegistrationLevel()); + $this->assertEquals('20160412', $riskData->getRegistrationDate()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/ShippingDataTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/ShippingDataTest.php new file mode 100644 index 0000000..ff05b58 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/EmbeddedResources/ShippingDataTest.php @@ -0,0 +1,43 @@ +assertNull($shipping->getDeliveryService()); + $this->assertNull($shipping->getDeliveryTrackingId()); + $this->assertNull($shipping->getReturnTrackingId()); + + $resp = [ + "deliveryTrackingId" => "deliveryTrackingId", + "deliveryService" => "deliveryService", + "returnTrackingId" => "returnTrackingId", + ]; + $shipping->handleResponse((object)$resp); + + $this->assertEquals('deliveryTrackingId', $shipping->getDeliveryTrackingId()); + $this->assertEquals('deliveryService', $shipping->getDeliveryService()); + $this->assertEquals('returnTrackingId', $shipping->getReturnTrackingId()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/InstalmentPlanTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/InstalmentPlanTest.php index 6555dde..a795539 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/InstalmentPlanTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/InstalmentPlanTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use DateTime; @@ -37,6 +22,7 @@ class InstalmentPlanTest extends BasePaymentTest * Verify the functionalities of the instalment plan resources. * * @test + * * @dataProvider verifyQueryStringDP * * @param float $amount diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/KeypairTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/KeypairTest.php index 8161c42..0abba06 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/KeypairTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/KeypairTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Resources\Keypair; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/MetadataTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/MetadataTest.php index f960373..eae3c23 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/MetadataTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/MetadataTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Resources\Metadata; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaylaterInstallmentPlansTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaylaterInstallmentPlansTest.php new file mode 100644 index 0000000..607189c --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaylaterInstallmentPlansTest.php @@ -0,0 +1,148 @@ +assertNull($PaylaterInstallmentPlans->getAmount()); + $this->assertNull($PaylaterInstallmentPlans->getCurrency()); + $this->assertNull($PaylaterInstallmentPlans->getCountry()); + $this->assertNull($PaylaterInstallmentPlans->getCustomerType()); + + // when + $PaylaterInstallmentPlans->setAmount(2.345) + ->setCurrency('USD') + ->setCountry('DE') + ->setCustomerType(CustomerTypes::B2C); + + // then + $this->assertEquals(2.345, $PaylaterInstallmentPlans->getAmount()); + $this->assertEquals('USD', $PaylaterInstallmentPlans->getCurrency()); + $this->assertEquals('DE', $PaylaterInstallmentPlans->getCountry()); + $this->assertEquals(CustomerTypes::B2C, $PaylaterInstallmentPlans->getCustomerType()); + } + + /** + * Verify the functionalities of the instalment plan resources. + * + * @test + * + * @dataProvider verifyQueryStringDP + * + * @param float $amount + * @param string $currency + * @param string $country + * @param string $customerType + */ + public function verifyQueryString(float $amount, string $currency, string $country, string $customerType): void + { + $plansQuery = new InstallmentPlansQuery($amount, $currency, $country, $customerType); + $plans = (new PaylaterInstallmentPlans())->setQueryParameter($plansQuery); + $this->assertEquals("plans?amount={$amount}&country={$country}¤cy={$currency}&customerType={$customerType}", $plans->getResourcePath()); + } + + /** + * Verify that Jsonresponse gets handled properly + * + * @test + */ + public function verifyJsonResponseIsHandledProperly(): void + { + // when + $paylaterInstallmentPlans = new PaylaterInstallmentPlans(); + $jsonResponse = json_decode(JsonProvider::getJsonFromFile('paylaterPlansResponse.json')); + $paylaterInstallmentPlans->handleResponse($jsonResponse); + + $this->assertCount(count($jsonResponse->plans), $paylaterInstallmentPlans->getPlans()); + + // then + $this->assertEquals($jsonResponse->id ?? null, $paylaterInstallmentPlans->getId()); + $this->assertEquals($jsonResponse->amount ?? null, $paylaterInstallmentPlans->getAmount()); + $this->assertEquals($jsonResponse->currency ?? null, $paylaterInstallmentPlans->getCurrency()); + $this->assertEquals($jsonResponse->isError ?? null, $paylaterInstallmentPlans->isError()); + $this->assertEquals($jsonResponse->isSuccess ?? null, $paylaterInstallmentPlans->isSuccess()); + $this->assertEquals($jsonResponse->isPending ?? null, $paylaterInstallmentPlans->isPending()); + + $this->comparePlans($jsonResponse->plans, $paylaterInstallmentPlans->getPlans()); + } + + // + + /** + * @param object[] $expected + * @param InstallmentPlan[] $actual + * + * @return void + */ + protected function comparePlans(array $expected, array $actual): void + { + $this->assertCount(count($expected), $actual); + + foreach ($expected as $index => $plan) { + $this->assertEquals($plan->totalAmount ?? null, $actual[$index]->getTotalAmount()); + $this->assertEquals($plan->nominalInterestRate ?? null, $actual[$index]->getNominalInterestRate()); + $this->assertEquals($plan->effectiveInterestRate ?? null, $actual[$index]->getEffectiveInterestRate()); + $this->compareRates($plan->installmentRates ?? null, $actual[$index]->getInstallmentRates()); + $this->assertEquals($plan->secciUrl ?? null, $actual[$index]->getSecciUrl()); + } + } + + // + + // + + /** + * @param object[] $expected + * @param InstallmentRate[] $actual + * + * @return void + */ + protected function compareRates(array $expected, array $actual): void + { + foreach ($expected as $index => $rate) { + $this->assertEquals($rate->date, $actual[$index]->getDate()); + $this->assertEquals($rate->rate, $actual[$index]->getRate()); + } + } + + /** + * @return array + */ + public function verifyQueryStringDP(): array + { + return [ + [100, 'EUR', 'DE', 'B2C'], + [100, 'EUR', 'GB', 'B2B'], + [100, 'CHF', 'CHE', 'B2C'], + ]; + } + // +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTest.php index d0cb10a..5197acb 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTest.php @@ -1,51 +1,39 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; +use PHPUnit\Framework\MockObject\MockObject; +use RuntimeException; +use stdClass; use UnzerSDK\Constants\PaymentState; -use UnzerSDK\Unzer; use UnzerSDK\Resources\Basket; use UnzerSDK\Resources\Customer; use UnzerSDK\Resources\CustomerFactory; use UnzerSDK\Resources\EmbeddedResources\Amount; use UnzerSDK\Resources\Metadata; use UnzerSDK\Resources\Payment; +use UnzerSDK\Resources\PaymentTypes\Paypage; use UnzerSDK\Resources\PaymentTypes\Sofort; use UnzerSDK\Resources\TransactionTypes\AbstractTransactionType; use UnzerSDK\Resources\TransactionTypes\Authorization; use UnzerSDK\Resources\TransactionTypes\Cancellation; use UnzerSDK\Resources\TransactionTypes\Charge; +use UnzerSDK\Resources\TransactionTypes\Chargeback; use UnzerSDK\Resources\TransactionTypes\Payout; use UnzerSDK\Resources\TransactionTypes\Shipment; use UnzerSDK\Services\ResourceService; use UnzerSDK\test\BasePaymentTest; -use PHPUnit\Framework\MockObject\MockObject; -use RuntimeException; -use stdClass; +use UnzerSDK\test\Fixtures\JsonProvider; +use UnzerSDK\Unzer; class PaymentTest extends BasePaymentTest { @@ -63,6 +51,9 @@ public function gettersAndSettersShouldWorkProperly(): void /** @noinspection UnnecessaryAssertionInspection */ $this->assertInstanceOf(Amount::class, $payment->getAmount()); $this->assertNull($payment->getTraceId()); + $this->assertNull($payment->getAuthorization()); + $this->assertIsEmptyArray($payment->getReversals()); + $this->assertIsEmptyArray($payment->getRefunds()); // update $ids = (object)['traceId' => 'myTraceId']; @@ -79,6 +70,81 @@ public function gettersAndSettersShouldWorkProperly(): void $this->assertSame('myTraceId', $payment->getTraceId()); } + /** + * Verify that direct payment cancellations are handled correctly. + * + * @test + */ + public function PaymentCancellationsShouldBeHandledAsExpected() + { + $payment = (new Payment())->setParentResource(new Unzer('s-priv-1234')); + + $this->assertIsEmptyArray($payment->getReversals()); + $this->assertIsEmptyArray($payment->getRefunds()); + + $transactions = [ + (object)[ + "date" => "2022-05-13 08:04:29", + "type" => "authorize", + "status" => "success", + "url" => "https://api.unzer.com/v1/payments/s-pay-777/authorize/s-aut-1", + "amount" => "99.9900" + ], + (object)[ + "date" => "2022-05-13 08:04:30", + "type" => "charge", + "status" => "success", + "url" => "https://api.unzer.com/v1/payments/s-pay-777/charges/s-chg-1", + "amount" => "99.9900" + ], + (object)[ + "date" => "2022-05-13 08:04:31", + "type" => "cancel-authorize", + "status" => "success", + "url" => "https://api.unzer.com/v1/payments/s-pay-777/authorize/cancels/s-cnl-1", + "amount" => "22.2200" + ], + (object)[ + "date" => "2022-05-13 08:04:31", + "type" => "cancel-charge", + "status" => "success", + "url" => "https://api.unzer.com/v1/payments/s-pay-777/charges/cancels/s-cnl-1", + "amount" => "22.2200" + ] + ]; + + $payment->handleResponse((object)['transactions' => $transactions]); + + $this->assertCount(1, $payment->getReversals()); + $this->assertCount(1, $payment->getRefunds()); + $this->assertCount(2, $payment->getCancellations()); + } + + /** + * Verify that adding refunds/reversals to the payment happens as expected + * + * @test + */ + public function verifyAddingCancelationsWorksProperly() + { + $payment = (new Payment())->setParentResource(new Unzer('s-priv-1234')); + $this->assertIsEmptyArray($payment->getReversals()); + $this->assertIsEmptyArray($payment->getRefunds()); + $reversal1 = (new Cancellation())->setId('s-cnl-1')->setAmount(99.99); + $reversal2 = (new Cancellation())->setId('s-cnl-2')->setAmount(99.99); + $reversal3 = (new Cancellation())->setId('s-cnl-2')->setAmount(33.33); + + $payment->addReversal($reversal1); + $payment->addReversal($reversal2); + $this->assertCount(2, $payment->getReversals()); + + // update existing transaction. + $payment->addReversal($reversal3); + $this->assertCount(2, $payment->getReversals()); + + $this->assertEquals(33.33, $payment->getReversals()['s-cnl-2']->getAmount()); + } + /** * @test * @@ -468,6 +534,8 @@ public function getCancellationsShouldCollectAllCancellationsOfCorrespondingTran /** * Verify getCancellation calls getCancellations and returns null if cancellation does not exist. * + * @deprecated To be removed with Payment::getCancellation() + * * @test */ public function getCancellationShouldCallGetCancellationsAndReturnNullIfNoCancellationExists(): void @@ -482,6 +550,8 @@ public function getCancellationShouldCallGetCancellationsAndReturnNullIfNoCancel /** * Verify getCancellation returns cancellation if it exists. * + * @deprecated To be removed with Payment::getCancellation() + * * @test */ public function getCancellationShouldReturnCancellationIfItExists(): void @@ -501,6 +571,8 @@ public function getCancellationShouldReturnCancellationIfItExists(): void /** * Verify getCancellation fetches cancellation if it exists and lazy loading is false. * + * @deprecated To be removed with Payment::getCancellation() + * * @test */ public function getCancellationShouldReturnCancellationIfItExistsAndFetchItIfNotLazy(): void @@ -595,12 +667,60 @@ public function getAndSetCurrencyShouldPropagateToTheAmountObject(): void $this->assertEquals('MyTestGetCurrency', $payment->getCurrency()); } + /** + * Verify that a payment that contains a cancel-authorize transaction can be fetched, even though no authorize + * transaction exists. Can occur when canceling via Insights. + * + * @test + */ + public function cancelAuthorizeOnInvoiceShouldBeHandledCorrectly(): void + { + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->disableOriginalConstructor()->setMethods(['getResource'])->getMock(); + /** @noinspection PhpParamsInspection */ + + /** @var ResourceService $resourceServiceMock */ + $unzerObj = (new Unzer('s-priv-123'))->setResourceService($resourceServiceMock); + $payment = new Payment(); + $payment->setParentResource($unzerObj); + + $response = (object)[ + "id" => "s-pay-666", + "state" => (object)["id" => 1, "name" => "completed"], + "currency" => "EUR", + "transactions" => [ + (object)["date" => "2021-11-17 11:47:07", + "type" => "charge", + "status" => "pending", + "url" => "https://api.unzer.com/v1/payments/s-pay-666/charges/s-chg-1", "amount" => "14.9900" + ], + (object)[ + "date" => "2021-11-17 11:48:52", + "type" => "shipment", "status" => "success", + "url" => "https://api.unzer.com/v1/payments/s-pay-666/shipments/s-shp-1", + "amount" => "14.9900"], + (object)["date" => "2021-11-17 11:48:52", + "type" => "cancel-authorize", + "status" => "success", + "url" => "https://api.unzer.com/v1/payments/s-pay-666/charges/s-chg-1/cancels/s-cnl-1", + "amount" => "10.0000"] + ] + ]; + $payment->handleResponse($response); + $this->assertNull($payment->getAuthorization()); + /** @var Charge $initialCharge */ + $initialCharge = $payment->getCharges()[0]; + + $this->assertCount(1, $initialCharge->getCancellations()); + } + // /** * Verify handleResponse will update stateId. * * @test + * * @dataProvider stateDataProvider * * @param integer $state @@ -686,6 +806,32 @@ public function handleResponseShouldFetchAndUpdateCustomerIfItIsAlreadySet(): vo $payment->handleResponse($response); } + /** + * Verify handleResponse updates payPage if it set. + * + * @test + */ + public function handleResponseShouldFetchAndUpdatePayPageIfItIsAlreadySet(): void + { + $payment = (new Payment())->setId('myPaymentId'); + $payPage = (new Paypage(0, '', ''))->setId('payPageId'); + + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->disableOriginalConstructor()->setMethods(['fetchResource'])->getMock(); + /** @noinspection PhpParamsInspection */ + $resourceServiceMock->expects($this->never())->method('fetchResource')->with($payPage); + + /** @var ResourceService $resourceServiceMock */ + $unzerObj = (new Unzer('s-priv-123'))->setResourceService($resourceServiceMock); + $payment->setParentResource($unzerObj); + $payment->setpayPage($payPage); + + $response = new stdClass(); + $response->resources = new stdClass(); + $response->resources->payPageId = 'payPageId'; + $payment->handleResponse($response); + } + /** * Verify handleResponse updates paymentType. * @@ -758,6 +904,7 @@ public function handleResponseShouldGetMetadataIfUnfetchedMetadataObjectWithIdIs */ public function handleResponseShouldUpdateChargeTransactions(): void { + /** @var Payment $payment */ $payment = (new Payment())->setId('MyPaymentId'); $this->assertIsEmptyArray($payment->getCharges()); $this->assertIsEmptyArray($payment->getShipments()); @@ -771,6 +918,8 @@ public function handleResponseShouldUpdateChargeTransactions(): void $this->assertIsEmptyArray($payment->getCharges()); $this->assertIsEmptyArray($payment->getShipments()); $this->assertIsEmptyArray($payment->getCancellations()); + $this->assertIsEmptyArray($payment->getChargebacks()); + $this->assertNull($payment->getPayout()); $this->assertNull($payment->getAuthorization()); } @@ -803,6 +952,90 @@ public function handleResponseShouldUpdateAuthorizationFromResponse(): void $this->assertEquals(10.321, $authorization->getAmount()); } + /** + * Verify handleResponse updates existing chargebacks from response. + * + * @test + */ + public function handleResponseShouldUpdateChargebackFromResponse(): void + { + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->disableOriginalConstructor()->onlyMethods(['getResource'])->getMock(); + + $unzer = (new Unzer('s-priv-123'))->setResourceService($resourceServiceMock); + $payment = (new Payment()) + ->setParentResource($unzer) + ->setId('MyPaymentId'); + + $paymentJson = JsonProvider::getJsonFromFile('paymentWithMultipleChargebacks.json'); + $response = new stdClass(); + + $payment->handleResponse(json_decode($paymentJson)); + + $chargebacks = $payment->getChargebacks(true); + $charges = $payment->getCharges(); + $this->assertCount(2, $charges); + $this->assertCount(2, $chargebacks); + + $chargeback1 = $chargebacks[0]; + $this->assertInstanceOf(Chargeback::class, $chargeback1); + $this->assertInstanceOf(Charge::class, $chargeback1->getParentResource()); + $this->assertEquals(0.5, $chargeback1->getAmount()); + + $chargeback2 = $chargebacks[1]; + $this->assertInstanceOf(Chargeback::class, $chargeback2); + $this->assertInstanceOf(Charge::class, $chargeback2->getParentResource()); + $this->assertEquals(0.5, $chargeback2->getAmount()); + + // Charges contain chargeback reference. + $charge1 = $charges[0]; + $this->assertCount(1, $charge1->getChargebacks()); + + $charge2 = $charges[1]; + $this->assertCount(1, $charge1->getChargebacks()); + } + + /** + * Verify handleResponse updates existing chargebacks from response. + * + * @test + */ + public function chargebackOnPaymentShouldBeHandledProperly(): void + { + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->disableOriginalConstructor()->onlyMethods(['getResource', 'fetchResource'])->getMock(); + + $unzer = (new Unzer('s-priv-123'))->setResourceService($resourceServiceMock); + $payment = (new Payment()) + ->setParentResource($unzer) + ->setId('MyPaymentId'); + + $paymentResponse = JsonProvider::getJsonFromFile('paymentWithDirectChargeback.json'); + $payment->handleResponse(json_decode($paymentResponse, false)); + + $chargebacks = $payment->getChargebacks(true); + $charges = $payment->getCharges(); + $this->assertCount(2, $charges); + $this->assertCount(2, $chargebacks); + + $chargeback1 = $chargebacks[0]; + $this->assertInstanceOf(Chargeback::class, $chargeback1); + $this->assertInstanceOf(Payment::class, $chargeback1->getParentResource()); + $this->assertEquals(0.5, $chargeback1->getAmount()); + + $chargeback2 = $chargebacks[1]; + $this->assertInstanceOf(Chargeback::class, $chargeback2); + $this->assertInstanceOf(Payment::class, $chargeback2->getParentResource()); + $this->assertEquals(0.5, $chargeback2->getAmount()); + + // Charges contain chargeback reference. + $charge1 = $charges[0]; + $this->assertCount(0, $charge1->getChargebacks()); + + $charge2 = $charges[1]; + $this->assertCount(0, $charge2->getChargebacks()); + } + /** * Verify handleResponse adds authorization from response. * @@ -976,7 +1209,7 @@ public function handleResponseShouldThrowExceptionIfAnAuthorizeToAReversalDoesNo $response->transactions = [$cancellation]; $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('The Authorization object can not be found.'); + $this->expectExceptionMessage('The initial transaction object (Authorize or Charge) can not be found.'); $payment->handleResponse($response); } @@ -1193,13 +1426,13 @@ public function chargeMethodShouldPropagateToUnzerChargePaymentMethod(): void ->withConsecutive( [$payment, null, null], [$payment, 1.1, null], - [$payment, 2.2, 'MyCurrency'] + [$payment, 2.2] )->willReturn(new Charge()); $payment->setParentResource($unzerMock); $payment->charge(); $payment->charge(1.1); - $payment->charge(2.2, 'MyCurrency'); + $payment->charge(2.2); } /** @@ -1271,7 +1504,7 @@ public function metadataMustBeOfTypeMetadata(): void // when /** @noinspection PhpParamsInspection */ - $payment->setMetadata('test'); + $payment->setMetadata(null); // then $this->assertNull($payment->getMetadata()); @@ -1303,7 +1536,8 @@ public function setBasketShouldCallCreateIfTheGivenBasketObjectDoesNotExistYet() static function ($object) use ($basket, $unzer) { /** @var Basket $object */ return $object === $basket && $object->getParentResource() === $unzer; - }) + } + ) ); $payment = new Payment($unzer); @@ -1376,6 +1610,7 @@ public function paymentShouldBeFetchedByOrderIdIfIdIsNotSet(): void * Autofetch is disabled due to missing transactionIds. * * @test + * * @dataProvider initialTransactionDP * * @param AbstractTransactionType $expected diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/ApplePayTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/ApplePayTest.php index 0b6374d..7d33e68 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/ApplePayTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/ApplePayTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\EmbeddedResources\ApplePayHeader; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/BancontactTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/BancontactTest.php index a4478c9..c518890 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/BancontactTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/BancontactTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\PaymentTypes\Bancontact; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/CardTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/CardTest.php index 7888c9f..d956d0a 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/CardTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/CardTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\EmbeddedResources\CardDetails; @@ -135,6 +120,7 @@ public function constructorShouldSetEmail() * Verify expiryDate year is extended if it is the short version. * * @test + * * @dataProvider expiryDateDataProvider * * @param string $testData @@ -150,6 +136,7 @@ public function expiryDateShouldBeExtendedToLongVersion($testData, $expected): v * Verify invalid expiryDate throws Exception. * * @test + * * @dataProvider invalidExpiryDateDataProvider * * @param string $testData @@ -276,7 +263,7 @@ public function verifyCardCanBeUpdated(): void $this->assertEquals('client ip', $geoLocation->getClientIp()); $this->assertEquals('country code', $geoLocation->getCountryCode()); - $cardDetails = new stdClass; + $cardDetails = new stdClass(); $cardDetails->cardType = 'my card type'; $cardDetails->account = 'CREDIT'; $cardDetails->countryIsoA2 = 'DE'; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/EPSTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/EPSTest.php index 99b62f4..19c84ad 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/EPSTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/EPSTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\PaymentTypes\EPS; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/GooglePayTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/GooglePayTest.php new file mode 100644 index 0000000..80559db --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/GooglePayTest.php @@ -0,0 +1,90 @@ +assertEquals($protocolVersion, $googlepay->getProtocolVersion()); + $this->assertEquals($signature, $googlepay->getSignature()); + $this->assertEquals($intermediaSigningKey, $googlepay->getIntermediateSigningKey()); + $this->assertEquals($signedMessage, $googlepay->getSignedMessage()); + } + + /** + * Test Google Pay json serialization. + * + * @test + */ + public function jsonSerializationExposesOnlyRequestParameter(): void + { + $googlepay = $this->getTestGooglepay(); + + $expectedJson = JsonProvider::getJsonFromFile('googlePay/createRequest.json'); + $this->assertJsonStringEqualsJsonString($expectedJson, $googlepay->jsonSerialize()); + } + + /** + * @return Googlepay + */ + private function getTestGooglepay(): Googlepay + { + $intermediateSigningKey = (new IntermediateSigningKey()) + ->setSignatures(['signature1']) + ->setSignedKey(new SignedKey('1542394027316', 'key-value-xyz\\u003d\\u003d"}')); + return new Googlepay( + 'ECv2', + 'signature-xyz=', + $intermediateSigningKey, + new SignedMessage( + '001 Cryptogram 3ds', + 'ephemeralPublicKey-xyz\\u003d"', + 'encryptedMessage-xyz"' + ) + ); + } + + /** + * Test GooglePay json response handling. + * + * @test + */ + public function googlepayAuthorizationShouldBeMappedCorrectly(): void + { + $googlepay = new Googlepay(null, null, null, null); + + $jsonResponse = JsonProvider::getJsonFromFile('googlePay/fetchResponse.json'); + + $jsonObject = json_decode($jsonResponse, false, 512, JSON_THROW_ON_ERROR); + $googlepay->handleResponse($jsonObject); + + $this->assertEquals('s-gop-q0nucec6itwe', $googlepay->getId()); + $this->assertEquals('10/2025', $googlepay->getExpiryDate()); + $this->assertEquals('518834******0003', $googlepay->getNumber()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/IdealTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/IdealTest.php index f4d7416..6113d61 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/IdealTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/IdealTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\PaymentTypes\Ideal; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/InstallmentSecuredTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/InstallmentSecuredTest.php index 822daf1..bf5741c 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/InstallmentSecuredTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/InstallmentSecuredTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use DateInterval; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPageTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPageTest.php index c0aabb8..10083bc 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPageTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPageTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Adapter\HttpAdapterInterface; @@ -205,7 +190,7 @@ public function responseHandlingShouldWorkProperly(): void $response->imprintUrl = 'imprint url'; $response->privacyPolicyUrl = 'privacy policy url'; $response->termsAndConditionUrl = 'tac url'; - $response->css = ['my'=> 'styles']; + $response->css = ['my' => 'styles']; $paypage->handleResponse($response); // then diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPalTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPalTest.php index b5f445a..2832416 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPalTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PayPalTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\PaymentTypes\Paypal; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PaylaterDirectDebitTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PaylaterDirectDebitTest.php new file mode 100644 index 0000000..920163e --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PaylaterDirectDebitTest.php @@ -0,0 +1,39 @@ +assertEquals('iban', $pdd->getIban()); + $this->assertEquals('holder', $pdd->getHolder()); + } + + /** + * Verify setter and getter work. + * + * @test + */ + public function getterAndSetterWorkAsExpected(): void + { + $pdd = new PaylaterDirectDebit(); + + $this->assertNull($pdd->getIban()); + $pdd->setIban('DE89370400440532013000'); + $this->assertEquals('DE89370400440532013000', $pdd->getIban()); + + $this->assertNull($pdd->getHolder()); + $pdd->setHolder('Max Mustermann'); + $this->assertEquals('Max Mustermann', $pdd->getHolder()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PaylaterInstallmentTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PaylaterInstallmentTest.php new file mode 100644 index 0000000..d993553 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/PaylaterInstallmentTest.php @@ -0,0 +1,57 @@ +assertNull($pit->getInquiryId()); + $this->assertNull($pit->getNumberOfRates()); + $this->assertNull($pit->getIban()); + $this->assertNull($pit->getCountry()); + $this->assertNull($pit->getHolder()); + + $pit->setInquiryId('inquiryId'); + $pit->setNumberOfRates(7); + $pit->setIban('DE89370400440532013000'); + $pit->setCountry('DE'); + $pit->setHolder('Max Mustermann'); + + $this->assertEquals('inquiryId', $pit->getInquiryId()); + $this->assertEquals(7, $pit->getNumberOfRates()); + $this->assertEquals('DE89370400440532013000', $pit->getIban()); + $this->assertEquals('DE', $pit->getCountry()); + $this->assertEquals('Max Mustermann', $pit->getHolder()); + + $pit->setInquiryId(null); + $pit->setNumberOfRates(null); + $pit->setIban(null); + $pit->setCountry(null); + $pit->setHolder(null); + + $this->assertNull($pit->getInquiryId()); + $this->assertNull($pit->getNumberOfRates()); + $this->assertNull($pit->getIban()); + $this->assertNull($pit->getCountry()); + $this->assertNull($pit->getHolder()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitSecuredTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitSecuredTest.php index e315907..3d195fd 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitSecuredTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitSecuredTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebitSecured; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitTest.php index ca74ede..50c3167 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SepaDirectDebitTest.php @@ -1,29 +1,8 @@ - * - * @package UnzerSDK\test\unit - */ + namespace UnzerSDK\test\unit\Resources\PaymentTypes; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebit; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SofortTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SofortTest.php new file mode 100644 index 0000000..6006bf7 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/PaymentTypes/SofortTest.php @@ -0,0 +1,33 @@ +assertNull($sofort->getId()); + + $jsonResponse = JsonProvider::getJsonFromFile('sofortResponseWithIban.json'); + $sofort->handleResponse((object)json_decode($jsonResponse, false)); + + $this->assertEquals('s-sft-123', $sofort->getId()); + $this->assertEquals('DE-IBAN', $sofort->getIban()); + $this->assertEquals('test-bin', $sofort->getBic()); + $this->assertEquals('holder', $sofort->getHolder()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/RecurringTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/RecurringTest.php index 759e170..ae0c222 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/RecurringTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/RecurringTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Resources\Recurring; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AbstractTransactionTypeTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AbstractTransactionTypeTest.php index ba7c6a9..d4821b8 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AbstractTransactionTypeTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AbstractTransactionTypeTest.php @@ -1,28 +1,12 @@ - * - * @package UnzerSDK\test\unit */ namespace UnzerSDK\test\unit\Resources\TransactionTypes; @@ -31,6 +15,8 @@ use PHPUnit\Framework\MockObject\MockObject; use stdClass; use UnzerSDK\Adapter\HttpAdapterInterface; +use UnzerSDK\Constants\LiabilityShiftIndicator; +use UnzerSDK\Constants\TransactionStatus; use UnzerSDK\Resources\Payment; use UnzerSDK\Resources\TransactionTypes\AbstractTransactionType; use UnzerSDK\Services\ResourceService; @@ -96,13 +82,66 @@ public function theGettersAndSettersShouldWorkProperly(): void $this->assertSame('myUniqueId', $transactionType->getUniqueId()); $this->assertSame('myTraceId', $transactionType->getTraceId()); $this->assertNotNull($transactionType->getAdditionalTransactionData()); - $this->assertObjectHasAttribute('someDataKey', $transactionType->getAdditionalTransactionData()); + $this->assertTrue(property_exists($transactionType->getAdditionalTransactionData(), 'someDataKey')); $message = $transactionType->getMessage(); $this->assertSame('1234', $message->getCode()); $this->assertSame('Customer message!', $message->getCustomer()); } + /** + * Set status should set state flags correctly. + * + * @test + */ + public function setStatusShouldSetStateFlagsCorrectly(): void + { + $transactionType = new DummyTransactionType(); + + // Initial checks. + $this->assertFalse($transactionType->isSuccess()); + $this->assertFalse($transactionType->isPending()); + $this->assertFalse($transactionType->isError()); + $this->assertFalse($transactionType->isResumed()); + + $responseArray = ['status' => TransactionStatus::STATUS_ERROR]; + $transactionType->handleResponse((object)$responseArray); + + $this->assertFalse($transactionType->isSuccess()); + $this->assertFalse($transactionType->isPending()); + $this->assertTrue($transactionType->isError()); + $this->assertFalse($transactionType->isResumed()); + + $responseArray['status'] = TransactionStatus::STATUS_SUCCESS; + $transactionType->handleResponse((object)$responseArray); + + $this->assertTrue($transactionType->isSuccess()); + $this->assertFalse($transactionType->isPending()); + $this->assertFalse($transactionType->isError()); + $this->assertFalse($transactionType->isResumed()); + + $responseArray['status'] = TransactionStatus::STATUS_PENDING; + $transactionType->handleResponse((object)$responseArray); + + $this->assertFalse($transactionType->isSuccess()); + $this->assertTrue($transactionType->isPending()); + $this->assertFalse($transactionType->isError()); + $this->assertFalse($transactionType->isResumed()); + + $responseArray['status'] = TransactionStatus::STATUS_RESUMED; + $transactionType->handleResponse((object)$responseArray); + + $this->assertFalse($transactionType->isSuccess()); + $this->assertFalse($transactionType->isPending()); + $this->assertFalse($transactionType->isError()); + $this->assertTrue($transactionType->isResumed()); + + $this->expectException(\RuntimeException::class); + + $responseArray['status'] = 'Invalid status.'; + $transactionType->handleResponse((object)$responseArray); + } + /** * Verify getters and setters work properly. * @@ -179,6 +218,7 @@ public function handleResponseShouldUpdateValuesOfAbstractTransaction(): void * Verify fetchPayment is never called after a Get-Request. * * @test + * * @dataProvider updatePaymentDataProvider * * @param string $method @@ -215,6 +255,24 @@ public function fetchPaymentShouldFetchPaymentObject(): void $transactionType->fetchPayment(); } + /** + * Liability indicator response should stored in transaction + * + * @test + */ + public function liabilityResponseShouldBeStroedInTransaction() + { + $jsonRespone = '{"additionalTransactionData":{"card":{"liability":"MERCHANT"}}}'; + + $transaction = new DummyTransactionType(); + $transaction->handleResponse(json_decode($jsonRespone, false)); + $this->assertEquals($transaction->getCardTransactionData()->getLiability(), LiabilityShiftIndicator::MERCHANT); + + $jsonRespone = '{"additionalTransactionData":{"card":{"liability":"ISSUER"}}}'; + $transaction->handleResponse(json_decode($jsonRespone, false)); + $this->assertEquals($transaction->getCardTransactionData()->getLiability(), LiabilityShiftIndicator::ISSUER); + } + // /** diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AuthorizationTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AuthorizationTest.php index bc76d56..89ef823 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AuthorizationTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/AuthorizationTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\TransactionTypes; use UnzerSDK\Unzer; @@ -35,6 +20,7 @@ use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BasePaymentTest; use RuntimeException; + use function Webmozart\Assert\Tests\StaticAnalysis\object; class AuthorizationTest extends BasePaymentTest @@ -175,6 +161,7 @@ public function cancelShouldCallCancelAuthorizationOnUnzerObject(): void * Verify charge throws exception if payment is not set. * * @test + * * @dataProvider chargeValueProvider * * @param float|null $value diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/CancellationTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/CancellationTest.php index 984608e..b8023c0 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/CancellationTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/CancellationTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\TransactionTypes; use UnzerSDK\Constants\CancelReasonCodes; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ChargeTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ChargeTest.php index c21f642..39ce511 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ChargeTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ChargeTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\TransactionTypes; use UnzerSDK\Constants\RecurrenceTypes; @@ -80,18 +65,16 @@ public function gettersAndSettersShouldWorkProperly(): void } /** - * Setting recurrence type without a payment type Should raise Exception. + * Setting recurrence type without a payment type does not raise exception. * * @test */ - public function SetRecurrenceTypeShouldRaiseExceptionWOPaymentType() + public function recurrenceTypeCanBeSetWithoutTypeParameter() { $charge = new Charge(); $this->assertEmpty($charge->getAdditionalTransactionData()); $this->assertEmpty($charge->getRecurrenceType()); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Payment type can not be determined. Set it first or provide it via parameter $paymentType.'); $charge->setRecurrenceType(RecurrenceTypes::ONE_CLICK); } @@ -138,6 +121,28 @@ public function aChargeShouldBeUpdatedThroughResponseHandling(): void $this->assertEquals('4065.6865.6416', $charge->getDescriptor()); } + /** + * Verify response with empty account data can be handled. + * + * @test + */ + public function verifyResponseWithEmptyAccountDataCanBeHandled() + { + $charge = new Charge(); + + $testResponse = new stdClass(); + $testResponse->Iban = ''; + $testResponse->Bic = ''; + $testResponse->Holder = ''; + $testResponse->Descriptor = ''; + + $charge->handleResponse($testResponse); + $this->assertNull($charge->getIban()); + $this->assertNull($charge->getBic()); + $this->assertNull($charge->getHolder()); + $this->assertNull($charge->getDescriptor()); + } + /** * Verify getLinkedResources throws exception if the paymentType is not set. * @@ -211,11 +216,19 @@ public function getCancelledAmountReturnsTheCancelledAmount(): void $charge = new Charge(123.4, 'myCurrency', 'https://my-return-url.test'); $this->assertEquals(0.0, $charge->getCancelledAmount()); - $cancellation1 = new Cancellation(10.0); + $cancellationJson = '{ + "type": "cancel-charge", + "status": "success", + "amount": "10" + }'; + + $cancellation1 = new Cancellation(); + $cancellation1->handleResponse(json_decode($cancellationJson)); $charge->addCancellation($cancellation1); $this->assertEquals(10.0, $charge->getCancelledAmount()); - $cancellation2 = new Cancellation(10.0); + $cancellation2 = new Cancellation(); + $cancellation2->handleResponse(json_decode($cancellationJson)); $charge->addCancellation($cancellation2); $this->assertEquals(20.0, $charge->getCancelledAmount()); } diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ChargebackTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ChargebackTest.php new file mode 100644 index 0000000..cee991c --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ChargebackTest.php @@ -0,0 +1,184 @@ +assertNull($chargeback->getAmount()); + $this->assertEmpty($chargeback->getPaymentReference()); + + $chargeback = new Chargeback(123.4); + $this->assertEquals(123.4, $chargeback->getAmount()); + + $chargeback->setAmount(567.8); + $this->assertEquals(567.8, $chargeback->getAmount()); + + $chargeback->setPaymentReference('my Payment Reference'); + $this->assertEquals('my Payment Reference', $chargeback->getPaymentReference()); + } + + /** + * Verify json response is handled properly + * + * @test + */ + public function jsonResponseShouldBeHandledProperly() + { + $responseObject = json_decode(JsonProvider::getJsonFromFile('chargeback.json')); + + $chargeback = (new Chargeback())->setPayment(new Payment()); + $this->assertFalse($chargeback->isSuccess()); + $this->assertNull($chargeback->getId()); + $this->assertNull($chargeback->getUniqueId()); + $this->assertNull($chargeback->getShortId()); + $this->assertNull($chargeback->getTraceId()); + $this->assertNull($chargeback->getAmount()); + $this->assertNull($chargeback->getDate()); + $this->assertEmpty($chargeback->getMessage()->getCustomer()); + $this->assertEmpty($chargeback->getMessage()->getMerchant()); + + $chargeback->handleResponse($responseObject); + + $this->assertEquals('s-cbk-1', $chargeback->getId()); + $this->assertEquals('31HA0xyz', $chargeback->getUniqueId()); + $this->assertEquals('1234.1234.1234', $chargeback->getShortId()); + $this->assertEquals('trace-123', $chargeback->getTraceId()); + $this->assertEquals(119.0000, $chargeback->getAmount()); + $this->assertEquals('2023-02-28 08:00:00', $chargeback->getDate()); + $this->assertEquals('Your payments have been successfully processed.', $chargeback->getMessage()->getCustomer()); + $this->assertEquals('Transaction succeeded', $chargeback->getMessage()->getMerchant()); + + $this->assertEquals('s-pay-123', $chargeback->getPaymentId()); + } + + /** + * verify fetching Chargeback by id without charge ID uses expected endpoint. + * + * @test + */ + public function fetchChargebackByIdWithoutChargeId(): void + { + $responseObject = json_decode(JsonProvider::getJsonFromFile('paymentWithDirectChargeback.json')); + $chargebackJson = JsonProvider::getJsonFromFile('chargeback.json'); + + $unzer = (new Unzer('s-priv-123')); + $payment = (new Payment()) + ->setParentResource($unzer) + ->setId('MyPaymentId'); + + // Mock http service + $httpServiceMock = $this->getMockBuilder(HttpService::class) + ->disableOriginalConstructor()->onlyMethods(['send'])->getMock(); + + $httpServiceMock->expects($this->once()) + ->method('send') + ->with('/payments/s-pay-329982/chargebacks/s-cbk-1') + ->willReturn($chargebackJson); + + // Mock Resource service + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->disableOriginalConstructor()->onlyMethods(['getResource', 'fetchPayment', 'fetchPaymentType'])->getMock(); + $resourceServiceMock->method('fetchPaymentType')->willReturn(new PaylaterInvoice()); + $resourceServiceMock->expects($this->once())->method('fetchPayment')->willReturn($payment); + + $unzer->setResourceService($resourceServiceMock) + ->setHttpService($httpServiceMock); + + $payment->handleResponse($responseObject); + + $fetchedChargeback = $unzer->fetchChargebackById('MyPaymentId', 's-cbk-1', null); + $this->assertEquals('s-cbk-1', $fetchedChargeback->getId()); + $this->assertEquals('31HA0xyz', $fetchedChargeback->getUniqueId()); + $this->assertEquals('1234.1234.1234', $fetchedChargeback->getShortId()); + $this->assertEquals('trace-123', $fetchedChargeback->getTraceId()); + $this->assertInstanceOf(Payment::class, $fetchedChargeback->getParentResource()); + } + + /** + * verify fetching Chargeback by id without charge ID uses expected endpoint. + * + * @test + * + * @dataProvider fetchChargebackByIdDP + * + * @param mixed $chargeId + * @param mixed $expectedUri + */ + public function fetchChargebackById($chargeId, $expectedUri): void + { + $responseObject = json_decode(JsonProvider::getJsonFromFile('paymentWithMultipleChargebacks.json')); + $chargebackJson = JsonProvider::getJsonFromFile('chargeback.json'); + + $unzer = (new Unzer('s-priv-123')); + $payment = (new Payment()) + ->setParentResource($unzer); + + // Mock http service + $httpServiceMock = $this->getMockBuilder(HttpService::class) + ->disableOriginalConstructor()->onlyMethods(['send'])->getMock(); + + $httpServiceMock->expects($this->once()) + ->method('send') + ->with($expectedUri) + ->willReturn($chargebackJson); + + // Mock Resource service + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->disableOriginalConstructor()->onlyMethods(['getResource', 'fetchPayment', 'fetchPaymentType'])->getMock(); + $resourceServiceMock->method('fetchPaymentType')->willReturn(new PaylaterInvoice()); + $resourceServiceMock->expects($this->once())->method('fetchPayment')->willReturn($payment); + + $unzer->setResourceService($resourceServiceMock) + ->setHttpService($httpServiceMock); + + $payment->handleResponse($responseObject); + + $fetchedChargeback = $unzer->fetchChargebackById('s-pay-123', 's-cbk-1', $chargeId); + $this->assertEquals('s-cbk-1', $fetchedChargeback->getId()); + $this->assertEquals('31HA0xyz', $fetchedChargeback->getUniqueId()); + $this->assertEquals('1234.1234.1234', $fetchedChargeback->getShortId()); + $this->assertEquals('trace-123', $fetchedChargeback->getTraceId()); + $this->assertInstanceOf(Charge::class, $fetchedChargeback->getParentResource()); + } + + public function fetchChargebackByIdDP(): array + { + return [ + 'first chargeback' => [ + 's-chg-1', + '/payments/s-pay-123/charges/s-chg-1/chargebacks/s-cbk-1' + ], + 'second chargeback' => [ + 's-chg-2', + '/payments/s-pay-123/charges/s-chg-2/chargebacks/s-cbk-1' + ] + ]; + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/DummyTransactionType.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/DummyTransactionType.php index 641c844..3205ae9 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/DummyTransactionType.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/DummyTransactionType.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\TransactionTypes; use UnzerSDK\Resources\TransactionTypes\AbstractTransactionType; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/PayoutTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/PayoutTest.php index 791c296..95e8873 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/PayoutTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/PayoutTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\TransactionTypes; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ShipmentTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ShipmentTest.php index 260b0c3..77795f5 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ShipmentTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/TransactionTypes/ShipmentTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources\TransactionTypes; use UnzerSDK\Resources\TransactionTypes\Shipment; @@ -57,6 +42,7 @@ public function gettersAndSettersShouldWorkProperly(): Shipment * @test * * @param Shipment $shipment + * * @depends gettersAndSettersShouldWorkProperly */ public function aShipmentShouldBeUpdatedThroughResponseHandling(Shipment $shipment): void diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/WebhookTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/WebhookTest.php index 7542d91..12c76f4 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/WebhookTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/WebhookTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Resources\Webhook; diff --git a/vendor/unzerdev/php-sdk/test/unit/Resources/WebhooksTest.php b/vendor/unzerdev/php-sdk/test/unit/Resources/WebhooksTest.php index 07e2c7f..436aeaf 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Resources/WebhooksTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Resources/WebhooksTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Resources; use UnzerSDK\Constants\WebhookEvents; diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/CancelServiceTest.php b/vendor/unzerdev/php-sdk/test/unit/Services/CancelServiceTest.php index c59c4dc..8b56bfd 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/CancelServiceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/CancelServiceTest.php @@ -1,35 +1,23 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Exceptions\UnzerApiException; use UnzerSDK\Resources\EmbeddedResources\Amount; use UnzerSDK\Resources\Payment; +use UnzerSDK\Resources\PaymentTypes\BasePaymentType; +use UnzerSDK\Resources\PaymentTypes\Klarna; +use UnzerSDK\Resources\PaymentTypes\PaylaterInvoice; use UnzerSDK\Resources\TransactionTypes\Authorization; use UnzerSDK\Resources\TransactionTypes\Cancellation; use UnzerSDK\Resources\TransactionTypes\Charge; @@ -121,10 +109,38 @@ public function chargesShouldBeCancelledIfAuthDoesNotExist2(): void $this->assertEquals([$cancellation1, $cancellation2], $payment->cancelAmount()); } + /** + * Verify that max cancel amount is calculated correctly in edge case. + * + * @test + */ + public function maxCancelAmountShouldBeRoundedCorrectly(): void + { + $cancelSrvMock = new CancelService($this->unzer); + $reflection = new \ReflectionClass(get_class($cancelSrvMock)); + $method = $reflection->getMethod('calculateMaxReversalAmount'); + $method->setAccessible(true); + + $chargeAmount = 12.3; + $receiptAmount = 10.0; + $canceledAmount = 2.3; + + // Verify not rounded result would not equal zero. + $this->assertNotEquals(0, $chargeAmount - $receiptAmount - $canceledAmount); + + $chargeMock = $this->getMockBuilder(Charge::class)->setMethods(['getCancelledAmount'])->setConstructorArgs([$chargeAmount])->getMock(); + $chargeMock->method('getCancelledAmount')->willReturn($canceledAmount); + + $maxReversalAmount = $method->invokeArgs($cancelSrvMock, [$chargeMock , $receiptAmount]); + + $this->assertEquals(0, $maxReversalAmount); + } + /** * Verify certain errors are allowed during cancellation and will be ignored. * * @test + * * @dataProvider allowedErrorCodesDuringChargeCancel * * @param string $allowedExceptionCode @@ -204,6 +220,7 @@ public function cancelAuthorizationAmountShouldCallCancelWithTheRemainingAmountA * Verify certain errors are allowed during cancellation and will be ignored. * * @test + * * @dataProvider allowedErrorCodesDuringAuthCancel * * @param string $exceptionCode @@ -270,6 +287,24 @@ public function paymentCancelShouldFetchPaymentIfPaymentIdIsPassed(): void $cancelService->cancelPayment('paymentId'); } + /** Verify that payment types processed on P3 are not canceled via unzer::cancelPayment method. + * @test + * + * @dataProvider p3PaymentTypes + * + * @param BasePaymentType $paymentType + */ + public function cancelPaymentMethodThrowsRuntimeExceptionWithP3PaymentType(BasePaymentType $paymentType): void + { + $dummyPayment = new Payment($this->unzer); + $dummyPayment->setPaymentType($paymentType); + + $this->expectException(\RuntimeException::class); + $expectedMessage = 'The used payment type is not supported by this cancel method. Please use Unzer::cancelAuthorizedPayment() or Unzer::cancelChargedPayment() instead.'; + $this->expectExceptionMessage($expectedMessage); + $this->unzer->cancelPayment($dummyPayment, 33.33); + } + // /** @@ -297,5 +332,16 @@ public function allowedErrorCodesDuringAuthCancel(): array ]; } + /** + * @return array + */ + public function p3PaymentTypes(): array + { + return [ + 'Paylater Invoice' => [(new PaylaterInvoice())->setId('s-piv-dummyId')], + 'Klarna' => [(new Klarna())->setId('s-piv-dummyId')] + ]; + } + // } diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/DummyAdapter.php b/vendor/unzerdev/php-sdk/test/unit/Services/DummyAdapter.php index 48cae05..399d50c 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/DummyAdapter.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/DummyAdapter.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use UnzerSDK\Adapter\HttpAdapterInterface; @@ -33,7 +18,7 @@ class DummyAdapter implements HttpAdapterInterface /** * {@inheritDoc} */ - public function init($url, $payload = null, $httpMethod = HttpAdapterInterface::REQUEST_GET): void + public function init(string $url, string $payload = null, string $httpMethod = HttpAdapterInterface::REQUEST_GET): void { // do nothing } diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/DummyDebugHandler.php b/vendor/unzerdev/php-sdk/test/unit/Services/DummyDebugHandler.php index 72b0855..e95126f 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/DummyDebugHandler.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/DummyDebugHandler.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use UnzerSDK\Interfaces\DebugHandlerInterface; diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/EnvironmentServiceTest.php b/vendor/unzerdev/php-sdk/test/unit/Services/EnvironmentServiceTest.php index 24460da..4bdfbbb 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/EnvironmentServiceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/EnvironmentServiceTest.php @@ -1,33 +1,18 @@ - * - * @package UnzerSDK\test\unit\Services */ + namespace UnzerSDK\test\unit\Services; -use UnzerSDK\Services\EnvironmentService; use PHPUnit\Framework\TestCase; +use UnzerSDK\test\Helper\TestEnvironmentService; class EnvironmentServiceTest extends TestCase { @@ -37,6 +22,7 @@ class EnvironmentServiceTest extends TestCase * Verify test logging environment vars are correctly interpreted. * * @test + * * @dataProvider envVarsShouldBeInterpretedAsExpectedDP * * @param mixed $verboseLog @@ -45,14 +31,14 @@ class EnvironmentServiceTest extends TestCase public function envVarsShouldBeInterpretedAsExpected($verboseLog, $expectedLogEnabled): void { unset( - $_SERVER[EnvironmentService::ENV_VAR_NAME_VERBOSE_TEST_LOGGING] + $_SERVER[TestEnvironmentService::ENV_VAR_NAME_VERBOSE_TEST_LOGGING] ); if ($verboseLog !== null) { - $_SERVER[EnvironmentService::ENV_VAR_NAME_VERBOSE_TEST_LOGGING] = $verboseLog; + $_SERVER[TestEnvironmentService::ENV_VAR_NAME_VERBOSE_TEST_LOGGING] = $verboseLog; } - $this->assertEquals($expectedLogEnabled, EnvironmentService::isTestLoggingActive()); + $this->assertEquals($expectedLogEnabled, TestEnvironmentService::isTestLoggingActive()); } /** @@ -70,19 +56,19 @@ public function envVarsShouldBeInterpretedAsExpected($verboseLog, $expectedLogEn public function privateKeyStringIsReturnedCorrectly($keyEnvVar, $non3dsKeyEnvVar, $non3ds, $expected): void { unset( - $_SERVER[EnvironmentService::ENV_VAR_TEST_PRIVATE_KEY], - $_SERVER[EnvironmentService::ENV_VAR_TEST_PRIVATE_KEY_NON_3DS] + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PRIVATE_KEY_DEFAULT], + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PRIVATE_KEY_ALTERNATIVE] ); if ($keyEnvVar !== null) { - $_SERVER[EnvironmentService::ENV_VAR_TEST_PRIVATE_KEY] = $keyEnvVar; + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PRIVATE_KEY_DEFAULT] = $keyEnvVar; } if ($non3dsKeyEnvVar !== null) { - $_SERVER[EnvironmentService::ENV_VAR_TEST_PRIVATE_KEY_NON_3DS] = $non3dsKeyEnvVar; + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PRIVATE_KEY_ALTERNATIVE] = $non3dsKeyEnvVar; } - $this->assertEquals($expected, EnvironmentService::getTestPrivateKey($non3ds)); + $this->assertEquals($expected, TestEnvironmentService::getTestPrivateKey($non3ds)); } /** @@ -100,19 +86,19 @@ public function privateKeyStringIsReturnedCorrectly($keyEnvVar, $non3dsKeyEnvVar public function publicKeyStringIsReturnedCorrectly($keyEnvVar, $non3dsKeyEnvVar, $non3ds, $expected): void { unset( - $_SERVER[EnvironmentService::ENV_VAR_TEST_PUBLIC_KEY], - $_SERVER[EnvironmentService::ENV_VAR_TEST_PUBLIC_KEY_NON_3DS] + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PUBLIC_KEY_DEFAULT], + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PUBLIC_KEY_ALTERNATIVE] ); if ($keyEnvVar !== null) { - $_SERVER[EnvironmentService::ENV_VAR_TEST_PUBLIC_KEY] = $keyEnvVar; + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PUBLIC_KEY_DEFAULT] = $keyEnvVar; } if ($non3dsKeyEnvVar !== null) { - $_SERVER[EnvironmentService::ENV_VAR_TEST_PUBLIC_KEY_NON_3DS] = $non3dsKeyEnvVar; + $_SERVER[TestEnvironmentService::ENV_VAR_TEST_PUBLIC_KEY_ALTERNATIVE] = $non3dsKeyEnvVar; } - $this->assertEquals($expected, EnvironmentService::getTestPublicKey($non3ds)); + $this->assertEquals($expected, TestEnvironmentService::getTestPublicKey($non3ds)); } // diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/HttpServiceTest.php b/vendor/unzerdev/php-sdk/test/unit/Services/HttpServiceTest.php index dc5c9c1..c186e5c 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/HttpServiceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/HttpServiceTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use UnzerSDK\Adapter\CurlAdapter; @@ -111,8 +96,9 @@ public function sendShouldInitAndSendRequest(): void $adapterMock->expects($this->once())->method('init')->with( $this->callback( static function ($url) { - return str_replace(['dev-api', 'stg-api'], 'api', $url) === 'https://api.unzer.com/v1/my/uri/123'; - }), + return str_replace(['dev-api', 'stg-api'], 'sbx-api', $url) === 'https://sbx-api.unzer.com/v1/my/uri/123'; + } + ), '{"dummyResource": "JsonSerialized"}', 'GET' ); @@ -142,6 +128,7 @@ static function ($url) { * Verify 'Accept-Language' header only set when a locale is defined in the Unzer object. * * @test + * * @dataProvider languageShouldOnlyBeSetIfSpecificallyDefinedDP * * @param $locale @@ -159,7 +146,8 @@ public function languageShouldOnlyBeSetIfSpecificallyDefined($locale): void $this->callback( static function ($headers) use ($locale) { return $locale === ($headers['Accept-Language'] ?? null); - }) + } + ) ); $adapterMock->method('execute')->willReturn('myResponseString'); @@ -167,6 +155,28 @@ static function ($headers) use ($locale) { $httpServiceMock->send('/my/uri/123', $resource); } + /** + * Verify 'CLIENTIP' header only set when a clientIp is defined in the Unzer object. + * + * @test + * + * @dataProvider clientIpHeaderShouldBeSetProperlyDP + * + * @param $clientIp + * @param mixed $isHeaderExpected + */ + public function clientIpHeaderShouldBeSetProperly($clientIp, $isHeaderExpected): void + { + $unzer = new Unzer('s-priv-MyTestKey'); + $unzer->setClientIp($clientIp); + + $composeHttpHeaders = $unzer->getHttpService()->composeHttpHeaders($unzer); + $this->assertEquals($isHeaderExpected, isset($composeHttpHeaders['CLIENTIP'])); + if ($isHeaderExpected) { + $this->assertEquals($clientIp, $composeHttpHeaders['CLIENTIP']); + } + } + /** * Verify debugLog logs to debug handler if debug mode and a handler are set. * @@ -184,9 +194,10 @@ public function sendShouldLogDebugMessagesIfDebugModeAndHandlerAreSet(): void $loggerMock = $this->getMockBuilder(DummyDebugHandler::class)->setMethods(['log'])->getMock(); $loggerMock->expects($this->exactly(7))->method('log')->withConsecutive( [ $this->callback( - static function ($string) { - return str_replace(['dev-api', 'stg-api'], 'api', $string) === '(' . (getmypid()) . ') GET: https://api.unzer.com/v1/my/uri/123'; - }) + static function ($string) { + return str_replace(['dev-api', 'stg-api'], 'sbx-api', $string) === '(' . (getmypid()) . ') GET: https://sbx-api.unzer.com/v1/my/uri/123'; + } + ) ], [ $this->callback( static function ($string) { @@ -195,13 +206,15 @@ static function ($string) { $elements = json_decode($matches[1], true); return array_key_exists('Authorization', $elements) && array_key_exists('Content-Type', $elements) && array_key_exists('SDK-TYPE', $elements) && array_key_exists('SDK-VERSION', $elements); - }) + } + ) ], ['(' . (getmypid()) . ') Response: (200) {"response":"myResponseString"}'], [ $this->callback( static function ($string) { - return str_replace(['dev-api', 'stg-api'], 'api', $string) === '(' . (getmypid()) . ') POST: https://api.unzer.com/v1/my/uri/123'; - }) + return str_replace(['dev-api', 'stg-api'], 'sbx-api', $string) === '(' . (getmypid()) . ') POST: https://sbx-api.unzer.com/v1/my/uri/123'; + } + ) ], [ $this->callback( static function ($string) { @@ -210,7 +223,8 @@ static function ($string) { $elements = json_decode($matches[1], true); return array_key_exists('Authorization', $elements) && array_key_exists('Content-Type', $elements) && array_key_exists('SDK-TYPE', $elements) && array_key_exists('SDK-VERSION', $elements); - }) + } + ) ], ['(' . (getmypid()) . ') Request: {"dummyResource": "JsonSerialized"}'], ['(' . (getmypid()) . ') Response: (201) {"response":"myResponseString"}'] @@ -257,6 +271,7 @@ public function handleErrorsShouldThrowExceptionIfResponseIsEmpty(): void * Verify handleErrors will throw Exception if responseCode is greaterOrEqual to 400 or is not a number. * * @test + * * @dataProvider responseCodeProvider * * @param string $responseCode @@ -369,21 +384,22 @@ public function handleErrorsShouldThrowExceptionIfResponseContainsErrorField(): } /** - * Verify environment switches when environment variable defines PAPI environment. + * Verify API environment switches accordingly depending on environment variable and keypair. * * @test * * @dataProvider environmentUrlSwitchesWithEnvironmentVariableDP * - * @param $environment - * @param $apiUrl + * @param $environment + * @param $apiUrl + * @param string $key */ - public function environmentUrlSwitchesWithEnvironmentVariable($environment, $apiUrl): void + public function environmentUrlSwitchesWithEnvironmentVariable($environment, $apiUrl, string $key): void { $adapterMock = $this->getMockBuilder(CurlAdapter::class)->setMethods(['init', 'setUserAgent', 'setHeaders', 'execute', 'getResponseCode', 'close'])->getMock(); /** @noinspection PhpParamsInspection */ $adapterMock->expects($this->once())->method('init')->with($apiUrl, self::anything(), self::anything()); - $resource = (new DummyResource())->setParentResource(new Unzer('s-priv-MyTestKey')); + $resource = (new DummyResource())->setParentResource(new Unzer($key)); $adapterMock->method('execute')->willReturn('myResponseString'); $adapterMock->method('getResponseCode')->willReturn('42'); @@ -434,17 +450,44 @@ public function languageShouldOnlyBeSetIfSpecificallyDefinedDP(): array ]; } + /** + * Returns test data for method public function languageShouldOnlyBeSetIfSpecificallyDefined. + */ + public function clientIpHeaderShouldBeSetProperlyDP(): array + { + return [ + 'valid ipv4' => ['111.222.333.444', true], + 'valid ipv6' => ['684D:1111:222:3333:4444:5555:6:7', true], + 'valid ipv6 (dual)' => ['2001:db8:3333:4444:5555:6666:1.2.3.4', true], + 'empty string' => ['', false], + 'null' => [null, false] + ]; + } + /** * @return array */ public function environmentUrlSwitchesWithEnvironmentVariableDP(): array { + $devUrl = 'https://dev-api.unzer.com/v1'; + $stgUrl = 'https://stg-api.unzer.com/v1'; + $sbxUrl = 'https://sbx-api.unzer.com/v1'; + $prodUrl = 'https://api.unzer.com/v1'; + + $prodKey = 'p-priv-MyTestKey'; + $sbxKey = 's-priv-MyTestKey'; + return [ - 'Dev' => [EnvironmentService::ENV_VAR_VALUE_DEVELOPMENT_ENVIRONMENT, 'https://dev-api.unzer.com/v1'], - 'Prod' => [EnvironmentService::ENV_VAR_VALUE_PROD_ENVIRONMENT, 'https://api.unzer.com/v1'], - 'Stg' => [EnvironmentService::ENV_VAR_VALUE_STAGING_ENVIRONMENT, 'https://stg-api.unzer.com/v1'], - 'else' => ['something else', 'https://api.unzer.com/v1'], - 'undefined' => ['', 'https://api.unzer.com/v1'] + 'Dev with production key' => [EnvironmentService::ENV_VAR_VALUE_DEVELOPMENT_ENVIRONMENT, $prodUrl, $prodKey], + 'Prod with production key' => [EnvironmentService::ENV_VAR_VALUE_PROD_ENVIRONMENT, $prodUrl, $prodKey], + 'Stg with production key' => [EnvironmentService::ENV_VAR_VALUE_STAGING_ENVIRONMENT, $prodUrl, $prodKey], + 'something else with production key' => ['something else', $prodUrl, $prodKey], + 'undefined with production key' => ['', $prodUrl, $prodKey], + 'Dev with sandbox key' => [EnvironmentService::ENV_VAR_VALUE_DEVELOPMENT_ENVIRONMENT, $devUrl, $sbxKey], + 'Prod with sandbox key' => [EnvironmentService::ENV_VAR_VALUE_PROD_ENVIRONMENT, $sbxUrl, $sbxKey], + 'Stg with sandbox key' => [EnvironmentService::ENV_VAR_VALUE_STAGING_ENVIRONMENT, $stgUrl, $sbxKey], + 'something else with sandbox key' => ['something else', $sbxUrl, $sbxKey], + 'undefined with sandbox key' => ['', $sbxUrl, $sbxKey], ]; } diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/PaymentServiceTest.php b/vendor/unzerdev/php-sdk/test/unit/Services/PaymentServiceTest.php index cc8c11e..f73cb6c 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/PaymentServiceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/PaymentServiceTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use UnzerSDK\Constants\ApiResponseCodes; @@ -52,6 +37,7 @@ use UnzerSDK\Services\ResourceService; use UnzerSDK\test\BasePaymentTest; use PHPUnit\Framework\MockObject\MockObject; + use function in_array; class PaymentServiceTest extends BasePaymentTest @@ -86,6 +72,7 @@ public function gettersAndSettersShouldWorkProperly(): void * @test * * @param $card3ds + * * @dataProvider card3dsDataProvider */ public function authorizeShouldCreateNewAuthorizationAndPayment($card3ds): void @@ -129,6 +116,7 @@ public function authorizeShouldCreateNewAuthorizationAndPayment($card3ds): void * @test * * @param $card3ds + * * @dataProvider card3dsDataProvider */ public function chargeShouldCreateNewPaymentAndCharge($card3ds): void @@ -182,23 +170,57 @@ public function chargeAuthorizationShouldCallChargePaymentWithTheGivenPaymentObj } /** + * @deprecated * Verify chargeAuthorization calls fetchPayment if the payment object is passed as id string. * * @test */ - public function chargeAuthorizationShouldCallFetchPaymentIfThePaymentIsPassedAsIdString(): void + public function chargeAuthorizationShouldCallChargePaymentMethod(): void { /** @var ResourceServiceInterface|MockObject $resourceSrvMock */ $resourceSrvMock = $this->getMockBuilder(ResourceService::class)->setMethods(['fetchPayment'])->disableOriginalConstructor()->getMock(); - $resourceSrvMock->expects($this->once())->method('fetchPayment')->willReturn(new Payment()); /** @var PaymentService|MockObject $paymentSrvMock */ - $paymentSrvMock = $this->getMockBuilder(PaymentService::class)->setMethods(['chargePayment', 'getResourceService'])->disableOriginalConstructor()->getMock(); + $paymentSrvMock = $this->getMockBuilder(PaymentService::class)->setMethods(['chargePayment'])->disableOriginalConstructor()->getMock(); $paymentSrvMock->expects($this->once())->method('chargePayment')->withAnyParameters(); - $paymentSrvMock->expects(self::once())->method('getResourceService')->willReturn($resourceSrvMock); $paymentSrvMock->chargeAuthorization('myPaymentId'); } + /** + * @deprecated + * Verify chargePayment calls fetchPayment if the payment object is passed as id string. + * + * @test + */ + public function chargePaymentShouldCallerformChargeOnPaymentMethod(): void + { + /** @var ResourceServiceInterface|MockObject $resourceSrvMock */ + $resourceSrvMock = $this->getMockBuilder(ResourceService::class)->setMethods(['fetchPayment'])->disableOriginalConstructor()->getMock(); + /** @var PaymentService|MockObject $paymentSrvMock */ + $paymentSrvMock = $this->getMockBuilder(PaymentService::class)->setMethods(['performChargeOnPayment'])->disableOriginalConstructor()->getMock(); + $paymentSrvMock->expects($this->once())->method('performChargeOnPayment')->withAnyParameters(); + + $paymentSrvMock->chargePayment('myPaymentId'); + } + + /** + * Verify performChargeOnPayment calls fetchPayment if the payment object is passed as id string. + * + * @test + */ + public function performChargeOnPaymentShouldCallFetchPaymentIfThePaymentIsPassedAsIdString(): void + { + /** @var ResourceServiceInterface|MockObject $resourceSrvMock */ + $resourceSrvMock = $this->getMockBuilder(ResourceService::class)->setMethods(['fetchPayment', 'createResource'])->disableOriginalConstructor()->getMock(); + $resourceSrvMock->expects($this->once())->method('fetchPayment')->willReturn(new Payment()); + $resourceSrvMock->expects($this->once())->method('createResource')->willReturn(new Charge()); + /** @var PaymentService|MockObject $paymentSrvMock */ + $paymentSrvMock = $this->getMockBuilder(PaymentService::class)->setMethods(['getResourceService'])->disableOriginalConstructor()->getMock(); + $paymentSrvMock->expects(self::exactly(2))->method('getResourceService')->willReturn($resourceSrvMock); + + $paymentSrvMock->performChargeOnPayment('myPaymentId', new Charge()); + } + /** * Verify chargePayment will create a charge object and call create on ResourceService with it. * @@ -218,7 +240,6 @@ public function chargePaymentShouldCallCreateOnResourceServiceWithNewCharge(): v $newPayment = $charge->getPayment(); return $charge instanceof Charge && $charge->getAmount() === 1.234 && - $charge->getCurrency() === 'myTestCurrency' && $charge->getOrderId() === null && $charge->getInvoiceId() === null && $newPayment instanceof Payment && @@ -227,7 +248,7 @@ public function chargePaymentShouldCallCreateOnResourceServiceWithNewCharge(): v })); $paymentSrv = $unzer->setResourceService($resourceSrvMock)->getPaymentService(); - $returnedCharge = $paymentSrv->chargePayment($payment, 1.234, 'myTestCurrency'); + $returnedCharge = $paymentSrv->chargePayment($payment, 1.234); $this->assertEquals([$returnedCharge], $payment->getCharges()); } @@ -250,7 +271,6 @@ public function chargePaymentShouldSetArgumentsInNewChargeObject(): void $newPayment = $charge->getPayment(); return $charge instanceof Charge && $charge->getAmount() === 1.234 && - $charge->getCurrency() === 'myTestCurrency' && $charge->getOrderId() === 'orderId' && $charge->getInvoiceId() === 'invoiceId' && $newPayment instanceof Payment && @@ -259,7 +279,7 @@ public function chargePaymentShouldSetArgumentsInNewChargeObject(): void })); $paymentSrv = $unzer->setResourceService($resourceSrvMock)->getPaymentService(); - $returnedCharge = $paymentSrv->chargePayment($payment, 1.234, 'myTestCurrency', 'orderId', 'invoiceId'); + $returnedCharge = $paymentSrv->chargePayment($payment, 1.234, 'orderId', 'invoiceId'); $this->assertEquals([$returnedCharge], $payment->getCharges()); } @@ -504,7 +524,9 @@ public function payoutShouldCreateNewPayout(): void 'orderId' => 'id-4', 'returnUrl' => 'url', 'resources' => ['basketId' => 'id-2', 'customerId' => 'id-1', 'metadataId' => 'id-3', 'typeId' => 'id'] - ], $returnedPayout->expose()); + ], + $returnedPayout->expose() + ); } // diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/ResourceNameServiceTest.php b/vendor/unzerdev/php-sdk/test/unit/Services/ResourceNameServiceTest.php index b0941fc..3df0cb9 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/ResourceNameServiceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/ResourceNameServiceTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use UnzerSDK\Services\ResourceNameService; @@ -35,6 +20,7 @@ class ResourceNameServiceTest extends BasePaymentTest * Verify getting the short name of a class. * * @test + * * @dataProvider classShortNameTestDP * * @param string $className diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/ResourceServiceTest.php b/vendor/unzerdev/php-sdk/test/unit/Services/ResourceServiceTest.php index 6564ce5..432bea0 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/ResourceServiceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/ResourceServiceTest.php @@ -1,36 +1,23 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use DateTime; +use PHPUnit\Framework\MockObject\MockObject; +use RuntimeException; +use stdClass; use UnzerSDK\Adapter\HttpAdapterInterface; use UnzerSDK\Constants\ApiResponseCodes; use UnzerSDK\Exceptions\UnzerApiException; -use UnzerSDK\Unzer; use UnzerSDK\Interfaces\ResourceServiceInterface; use UnzerSDK\Resources\AbstractUnzerResource; use UnzerSDK\Resources\Basket; @@ -44,12 +31,17 @@ use UnzerSDK\Resources\PaymentTypes\Card; use UnzerSDK\Resources\PaymentTypes\EPS; use UnzerSDK\Resources\PaymentTypes\Giropay; -use UnzerSDK\Resources\PaymentTypes\InstallmentSecured; +use UnzerSDK\Resources\PaymentTypes\Googlepay; use UnzerSDK\Resources\PaymentTypes\Ideal; +use UnzerSDK\Resources\PaymentTypes\InstallmentSecured; use UnzerSDK\Resources\PaymentTypes\Invoice; use UnzerSDK\Resources\PaymentTypes\InvoiceSecured; +use UnzerSDK\Resources\PaymentTypes\Klarna; +use UnzerSDK\Resources\PaymentTypes\PaylaterInvoice; use UnzerSDK\Resources\PaymentTypes\Paypal; use UnzerSDK\Resources\PaymentTypes\PIS; +use UnzerSDK\Resources\PaymentTypes\PostFinanceCard; +use UnzerSDK\Resources\PaymentTypes\PostFinanceEfinance; use UnzerSDK\Resources\PaymentTypes\Prepayment; use UnzerSDK\Resources\PaymentTypes\Przelewy24; use UnzerSDK\Resources\PaymentTypes\SepaDirectDebit; @@ -68,9 +60,7 @@ use UnzerSDK\test\BasePaymentTest; use UnzerSDK\test\unit\DummyResource; use UnzerSDK\test\unit\Traits\TraitDummyCanRecur; -use PHPUnit\Framework\MockObject\MockObject; -use RuntimeException; -use stdClass; +use UnzerSDK\Unzer; class ResourceServiceTest extends BasePaymentTest { @@ -96,6 +86,7 @@ public function gettersAndSettersShouldWorkProperly(): void * Verify send will call send on httpService. * * @test + * * @dataProvider sendShouldCallSendOnHttpServiceDP * * @param string $method @@ -131,6 +122,7 @@ public function sendShouldCallSendOnHttpService(string $method, string $uri, boo * Verify getResourceIdFromUrl works correctly. * * @test + * * @dataProvider urlIdStringProvider * * @param string $expected @@ -149,6 +141,7 @@ public function getResourceIdFromUrlShouldIdentifyAndReturnTheIdStringFromAGiven * Verify getResourceIdFromUrl throws exception if the id cannot be found. * * @test + * * @dataProvider failingUrlIdStringProvider * * @param mixed $uri @@ -168,6 +161,7 @@ public function getResourceIdFromUrlShouldThrowExceptionIfTheIdCanNotBeFound($ur * Verify fetchResource calls fetch if its id is set and it has never been fetched before. * * @test + * * @dataProvider fetchResourceFetchCallDP * * @param $resource @@ -252,6 +246,28 @@ public function updateShouldCallSendAndThenHandleResponseWithTheResponseData(): $this->assertSame($testResource, $resourceServiceMock->updateResource($testResource)); } + /** + * Verify patch method will call send method and call the resources handleResponse method with the response. + * + * @test + */ + public function patchShouldCallSendAndThenHandleResponseWithTheResponseData(): void + { + $response = new stdClass(); + + /** @var Customer|MockObject $testResource */ + $testResource = $this->getMockBuilder(Charge::class)->setMethods(['handleResponse'])->getMock(); + /** @noinspection PhpParamsInspection */ + $testResource->expects($this->once())->method('handleResponse')->with($response, HttpAdapterInterface::REQUEST_PATCH); + + /** @var ResourceService|MockObject $resourceServiceMock */ + $resourceServiceMock = $this->getMockBuilder(ResourceService::class)->setMethods(['send'])->disableOriginalConstructor()->getMock(); + /** @noinspection PhpParamsInspection */ + $resourceServiceMock->expects($this->once())->method('send')->with($testResource, HttpAdapterInterface::REQUEST_PATCH)->willReturn($response); + + $this->assertSame($testResource, $resourceServiceMock->patchResource($testResource)); + } + /** * Verify update does not handle response with error. * @@ -279,12 +295,12 @@ public function updateShouldNotHandleResponseWithError(): void public function deleteShouldCallSendAndThenSetTheResourceNull(): void { /** @var Customer|MockObject $testResource */ - $testResource = $this->getMockBuilder(Customer::class)->getMock(); + $testResource = $this->getMockBuilder(Customer::class)->setMethods(['getApVersion'])->getMock(); /** @var ResourceService|MockObject $resourceServiceMock */ $resourceServiceMock = $this->getMockBuilder(ResourceService::class)->setMethods(['send'])->disableOriginalConstructor()->getMock(); /** @noinspection PhpParamsInspection */ - $resourceServiceMock->expects($this->once())->method('send')->with($testResource, HttpAdapterInterface::REQUEST_DELETE)->willReturn(new stdClass()); + $resourceServiceMock->expects($this->once())->method('send')->with($testResource, HttpAdapterInterface::REQUEST_DELETE, Unzer::API_VERSION)->willReturn(new stdClass()); $this->assertNull($resourceServiceMock->deleteResource($testResource)); $this->assertNull($testResource); @@ -298,7 +314,7 @@ public function deleteShouldCallSendAndThenSetTheResourceNull(): void public function deleteShouldNotDeleteObjectOnResponseWithError(): void { /** @var Customer|MockObject $testResource */ - $testResource = $this->getMockBuilder(Customer::class)->getMock(); + $testResource = $this->getMockBuilder(Customer::class)->setMethods(['send'])->getMock(); /** @var ResourceService|MockObject $resourceServiceMock */ $resourceServiceMock = $this->getMockBuilder(ResourceService::class)->setMethods(['send'])->disableOriginalConstructor()->getMock(); @@ -343,6 +359,7 @@ public function fetchShouldCallSendWithGetUpdateFetchedAtAndCallHandleResponse() * Verify fetchResourceByUrl calls fetch for the desired resource. * * @test + * * @dataProvider fetchResourceByUrlShouldFetchTheDesiredResourceDP * * @param string $fetchMethod @@ -363,6 +380,7 @@ public function fetchResourceByUrlShouldFetchTheDesiredResource($fetchMethod, $a * Verify fetchResourceByUrl calls fetch for the desired resource. * * @test + * * @dataProvider fetchResourceByUrlForAPaymentTypeShouldCallFetchPaymentTypeDP * * @param string $paymentTypeId @@ -396,6 +414,7 @@ public function fetchResourceByUrlForAPaymentTypeShouldReturnNullIfTheTypeIsUnkn * Verify fetchPayment method will fetch the passed payment object. * * @test + * * @dataProvider fetchShouldCallFetchResourceDP * * @param string $fetchMethod @@ -453,6 +472,7 @@ public function createPaymentTypeShouldSetUnzerObjectAndCallCreate(): void * Verify fetchPaymentType will throw exception if the id does not fit any type or is invalid. * * @test + * * @dataProvider paymentTypeIdProviderInvalid * * @param string $typeId @@ -989,6 +1009,107 @@ public function updateBasketShouldCallUpdateAndReturnTheGivenBasket(): void $this->assertEquals($unzer, $basket->getUnzerObject()); } + /** + * Verify fetchBasket will use the v2 endpoint end then the v1 endpoint if basket wasn't found initially. + * + * @test + */ + public function fetchBasketShouldCallV1EnpointIfBasketWasNotFound(): void + { + $unzer = new Unzer('s-priv-123'); + $basket = (new Basket())->setId('s-bsk-testbasket'); + + /** @var ResourceServiceInterface|MockObject $resourceServiceMock */ + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->setConstructorArgs([$unzer]) + ->setMethods(['fetchResource'])->getMock(); + + $resourceServiceMock->expects(self::exactly(2)) + ->method('fetchResource') + ->withConsecutive([$basket, BasePaymentTest::API_VERSION_2], [$basket, Unzer::API_VERSION]) + ->will($this->returnCallback(function ($basket, $version) { + if ($version === BasePaymentTest::API_VERSION_2) { + throw new UnzerApiException(null, null, ApiResponseCodes::API_ERROR_BASKET_NOT_FOUND); + } + return $basket; + })); + + $resourceServiceMock->fetchBasket($basket); + } + + /** + * Verify fetchBasket will call FetchResource max two time, if the basket was not found. + * Exception should be thrown. + * + * @test + */ + public function fetchBasketShouldCallFetchResourceMaxTwoTimes(): void + { + $unzer = new Unzer('s-priv-123'); + $basket = (new Basket())->setId('s-bsk-testbasket'); + + /** @var ResourceServiceInterface|MockObject $resourceServiceMock */ + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->setConstructorArgs([$unzer]) + ->setMethods(['fetchResource'])->getMock(); + + $resourceServiceMock->expects(self::exactly(2)) + ->method('fetchResource') + ->withConsecutive([$basket, BasePaymentTest::API_VERSION_2], [$basket, Unzer::API_VERSION]) + ->willThrowException(new UnzerApiException(null, null, ApiResponseCodes::API_ERROR_BASKET_NOT_FOUND)); + + $this->expectException(UnzerApiException::class); + $resourceServiceMock->fetchBasket($basket); + } + + /** + * Verify fetchBasket call fetchResource only once with v2 parameter, when basket was returned. + * + * @test + */ + public function fetchBasketShouldCallFetchResourceOnlyOnceIfNoExceptionOccurs(): void + { + $unzer = new Unzer('s-priv-123'); + $basket = (new Basket())->setId('s-bsk-testbasket'); + + /** @var ResourceServiceInterface|MockObject $resourceServiceMock */ + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->setConstructorArgs([$unzer]) + ->setMethods(['fetchResource'])->getMock(); + + $resourceServiceMock->expects(self::once()) + ->method('fetchResource') + ->with($basket, BasePaymentTest::API_VERSION_2) + ->willReturn($basket); + + $resourceServiceMock->fetchBasket($basket); + } + + /** + * Verify fetchBasket will call fetchResource only once if Exception ist not "API_ERROR_BASKET_NOT_FOUND" exception. + * Exception should be thrown. + * + * @test + */ + public function fetchBasketShouldNotCallFetchResourcheMethodIfAnyOtherExceptionIsThrown(): void + { + $unzer = new Unzer('s-priv-123'); + $basket = (new Basket())->setId('s-bsk-testbasket'); + + /** @var ResourceServiceInterface|MockObject $resourceServiceMock */ + $resourceServiceMock = $this->getMockBuilder(ResourceService::class) + ->setConstructorArgs([$unzer]) + ->setMethods(['fetchResource'])->getMock(); + + $resourceServiceMock->expects(self::once()) + ->method('fetchResource') + ->with($basket, BasePaymentTest::API_VERSION_2) + ->willThrowException(new UnzerApiException(null, null, ApiResponseCodes::API_ERROR_BASKET_ITEM_IMAGE_INVALID_URL)); + + $this->expectException(UnzerApiException::class); + $resourceServiceMock->fetchBasket($basket); + } + // // @@ -996,6 +1117,7 @@ public function updateBasketShouldCallUpdateAndReturnTheGivenBasket(): void /** * Verify createRecurring calls fetch for the payment type if it is given the id. * + * * @test */ public function createRecurringShouldFetchThePaymentTypeById(): void @@ -1018,6 +1140,7 @@ public function createRecurringShouldFetchThePaymentTypeById(): void /** * Verify createRecurring does not call fetch for the payment type if it is given the object itself. * + * * @test */ public function createRecurringShouldNotFetchThePaymentTypeByObject(): void @@ -1038,6 +1161,8 @@ public function createRecurringShouldNotFetchThePaymentTypeByObject(): void /** * Verify createRecurring throws exception if it is called with a payment type which does not support recurring payment. * + * @deprecated since 1.2.1.0 Get removed with `activateRecurring` method. + * * @test */ public function createRecurringShouldThrowExceptionWhenRecurringPaymentIsNotSupportedByType(): void @@ -1109,7 +1234,6 @@ public function paymentTypeIdProviderInvalid(): array ['p-crd12345678abc'], ['pcrd12345678abc'], ['myId'], - [null], [''] ]; } @@ -1126,11 +1250,14 @@ public function fetchResourceByUrlShouldFetchTheDesiredResourceDP(): array 'Charge' => ['fetchChargeById', ['s-pay-100798', 's-chg-1'], 'https://api.unzer.com/v1/payments/s-pay-100798/charges/s-chg-1/'], 'Shipment' => ['fetchShipment', ['s-pay-100801', 's-shp-1'], 'https://api.unzer.com/v1/payments/s-pay-100801/shipments/s-shp-1/'], 'Refund' => ['fetchRefundById', ['s-pay-100802', 's-chg-1', 's-cnl-1'], 'https://api.unzer.com/v1/payments/s-pay-100802/charges/s-chg-1/cancels/s-cnl-1/'], + 'Payment Refund' => ['fetchPaymentRefund', ['s-pay-100802', 's-cnl-1'], 'https://api.unzer.com/v1/payments/s-pay-100802/charges/cancels/s-cnl-1/'], 'Reversal' => ['fetchReversal', ['s-pay-100803', 's-cnl-1'], 'https://api.unzer.com/v1/payments/s-pay-100803/authorize/s-aut-1/cancels/s-cnl-1/'], + 'Payment Reversal' => ['fetchPaymentReversal', ['s-pay-100803', 's-cnl-1'], 'https://api.unzer.com/v1/payments/s-pay-100803/authorize/cancels/s-cnl-1/'], 'Payment' => ['fetchPayment', ['s-pay-100801'], 'https://api.unzer.com/v1/payments/s-pay-100801'], 'Metadata' => ['fetchMetadata', ['s-mtd-6glqv9axjpnc'], 'https://api.unzer.com/v1/metadata/s-mtd-6glqv9axjpnc/'], 'Customer' => ['fetchCustomer', ['s-cst-50c14d49e2fe'], 'https://api.unzer.com/v1/customers/s-cst-50c14d49e2fe'], - 'Basket' => ['fetchBasket', ['s-bsk-1254'], 'https://api.unzer.com/v1/baskets/s-bsk-1254/'], + 'v1Basket' => ['fetchBasket', ['s-bsk-1254'], 'https://api.unzer.com/v1/baskets/s-bsk-1254/'], + 'v2Basket' => ['fetchBasket', ['s-bsk-1254'], 'https://api.unzer.com/v2/baskets/s-bsk-1254/'], 'Payout' => ['fetchPayout', ['s-pay-100746'], 'https://api.unzer.com/v1/payments/s-pay-100746/payout/s-out-1/'] ]; } @@ -1156,8 +1283,11 @@ public function fetchResourceByUrlForAPaymentTypeShouldCallFetchPaymentTypeDP(): 'INVOICE_GUARANTEED' => ['s-ivg-xen2ybcovn56', 'https://api.unzer.com/v1/types/invoice-guaranteed/s-ivg-xen2ybcovn56/'], 'INVOICE_SECURED' => ['s-ivs-xen2ybcovn56', 'https://api.unzer.com/v1/types/invoice-secured/s-ivs-xen2ybcovn56/'], 'Installment_SECURED' => ['s-ins-xen2ybcovn56', 'https://api.unzer.com/v1/types/installment-secured/s-ins-xen2ybcovn56/'], + 'PAYLATER_INVOICE' => ['s-piv-xen2ybcovn56', 'https://api.unzer.com/v1/types/paylater-invoice/s-piv-xen2ybcovn56/'], 'PAYPAL' => ['s-ppl-xen2ybcovn56', 'https://api.unzer.com/v1/types/paypal/s-ppl-xen2ybcovn56/'], 'PIS' => ['s-pis-xen2ybcovn56', 'https://api.unzer.com/v1/types/pis/s-pis-xen2ybcovn56/'], + 'POST_FINANCE_EFINANCE' => ['s-pfe-xen2ybcovn56', 'https://api.unzer.com/v1/types/pfe/s-pfe-xen2ybcovn56/'], + 'POST_FINANCE_CARD' => ['s-pfc-xen2ybcovn56', 'https://api.unzer.com/v1/types/pfc/s-pfc-xen2ybcovn56/'], 'PREPAYMENT' => ['s-ppy-xen2ybcovn56', 'https://api.unzer.com/v1/types/prepayment/s-ppy-xen2ybcovn56/'], 'PRZELEWY24' => ['s-p24-xen2ybcovn56', 'https://api.unzer.com/v1/types/przelewy24/s-p24-xen2ybcovn56/'], 'SEPA_DIRECT_DEBIT' => ['s-sdd-xen2ybcovn56', 'https://api.unzer.com/v1/types/direct-debit/s-sdd-xen2ybcovn56/'], @@ -1174,6 +1304,7 @@ public function sendShouldCallSendOnHttpServiceDP(): array { return [ HttpAdapterInterface::REQUEST_GET => [HttpAdapterInterface::REQUEST_GET, '/my/get/uri', true], + HttpAdapterInterface::REQUEST_PATCH => [HttpAdapterInterface::REQUEST_PATCH, '/my/patch/uri', true], HttpAdapterInterface::REQUEST_POST => [HttpAdapterInterface::REQUEST_POST, '/my/post/uri', false], HttpAdapterInterface::REQUEST_PUT => [HttpAdapterInterface::REQUEST_PUT, '/my/put/uri', true], HttpAdapterInterface::REQUEST_DELETE => [HttpAdapterInterface::REQUEST_DELETE, '/my/delete/uri', true], @@ -1223,12 +1354,15 @@ public function fetchShouldCallFetchResourceDP(): array 'fetchBasket by obj' => ['fetchBasket', [(new Basket())->setId('myBasketId')], $fetchBasketCB], 'PaymentType Card sandbox' => ['fetchPaymentType', ['s-crd-12345678'], $getPaymentTypeCB(Card::class)], 'PaymentType Giropay sandbox' => ['fetchPaymentType', ['s-gro-12345678'], $getPaymentTypeCB(Giropay::class)], + 'PaymentType Google Pay sandbox' => ['fetchPaymentType', ['s-gop-12345678'], $getPaymentTypeCB(Googlepay::class)], 'PaymentType Ideal sandbox' => ['fetchPaymentType', ['s-idl-12345678'], $getPaymentTypeCB(Ideal::class)], 'PaymentType Invoice sandbox' => ['fetchPaymentType', ['s-ivc-12345678'], $getPaymentTypeCB(Invoice::class)], 'PaymentType InvoiceGuaranteed sandbox' => ['fetchPaymentType', ['s-ivg-12345678'], $getPaymentTypeCB(InvoiceSecured::class)], 'PaymentType InvoiceSecured sandbox' => ['fetchPaymentType', ['s-ivs-12345678'], $getPaymentTypeCB(InvoiceSecured::class)], 'PaymentType Invoie factoring sandbox' => ['fetchPaymentType', ['s-ivf-12345678'], $getPaymentTypeCB(InvoiceSecured::class)], + 'PaymentType Klarna' => ['fetchPaymentType', ['s-kla-12345678'], $getPaymentTypeCB(Klarna::class)], 'PaymentType Paypal sandbox' => ['fetchPaymentType', ['s-ppl-12345678'], $getPaymentTypeCB(Paypal::class)], + 'PaymentType Paylater-Invoice sandbox' => ['fetchPaymentType', ['s-piv-12345678'], $getPaymentTypeCB(PaylaterInvoice::class)], 'PaymentType Prepayment sandbox' => ['fetchPaymentType', ['s-ppy-12345678'], $getPaymentTypeCB(Prepayment::class)], 'PaymentType Przelewy24 sandbox' => ['fetchPaymentType', ['s-p24-12345678'], $getPaymentTypeCB(Przelewy24::class)], 'PaymentType SepaDirectDebit sandbox' => ['fetchPaymentType', ['s-sdd-12345678'], $getPaymentTypeCB(SepaDirectDebit::class)], @@ -1236,31 +1370,36 @@ public function fetchShouldCallFetchResourceDP(): array 'PaymentType SepaDirectDebitSecured sandbox' => ['fetchPaymentType', ['s-dds-12345678'], $getPaymentTypeCB(SepaDirectDebitSecured::class)], 'PaymentType Sofort sandbox' => ['fetchPaymentType', ['s-sft-12345678'], $getPaymentTypeCB(Sofort::class)], 'PaymentType PIS sandbox' => ['fetchPaymentType', ['s-pis-12345678'], $getPaymentTypeCB(PIS::class)], + 'PaymentType PFC sandbox' => ['fetchPaymentType', ['s-pfc-12345678'], $getPaymentTypeCB(PostFinanceCard::class)], + 'PaymentType PFE sandbox' => ['fetchPaymentType', ['s-pfe-12345678'], $getPaymentTypeCB(PostFinanceEfinance::class)], 'PaymentType EPS sandbox' => ['fetchPaymentType', ['s-eps-12345678'], $getPaymentTypeCB(EPS::class)], 'PaymentType Alipay sandbox' => ['fetchPaymentType', ['s-ali-12345678'], $getPaymentTypeCB(Alipay::class)], 'PaymentType Wechatpay sandbox' => ['fetchPaymentType', ['s-wcp-12345678'], $getPaymentTypeCB(Wechatpay::class)], 'PaymentType HirePurchaseDirectDebit sandbox' => ['fetchPaymentType', ['s-hdd-12345678'], $getPaymentTypeCB(InstallmentSecured::class)], 'PaymentType InstallmentSecured sandbox' => ['fetchPaymentType', ['s-ins-12345678'], $getPaymentTypeCB(InstallmentSecured::class)], 'PaymentType Bancontact sandbox' => ['fetchPaymentType', ['s-bct-12345678'], $getPaymentTypeCB(Bancontact::class)], + 'PaymentType Alipay production' => ['fetchPaymentType', ['p-ali-12345678'], $getPaymentTypeCB(Alipay::class)], + 'PaymentType Bancontact production' => ['fetchPaymentType', ['p-bct-12345678'], $getPaymentTypeCB(Bancontact::class)], 'PaymentType Card production' => ['fetchPaymentType', ['p-crd-12345678'], $getPaymentTypeCB(Card::class)], + 'PaymentType EPS production' => ['fetchPaymentType', ['p-eps-12345678'], $getPaymentTypeCB(EPS::class)], 'PaymentType Giropay production' => ['fetchPaymentType', ['p-gro-12345678'], $getPaymentTypeCB(Giropay::class)], + 'PaymentType HirePurchaseDirectDebit production' => ['fetchPaymentType', ['p-hdd-12345678'], $getPaymentTypeCB(InstallmentSecured::class)], 'PaymentType Ideal production' => ['fetchPaymentType', ['p-idl-12345678'], $getPaymentTypeCB(Ideal::class)], + 'PaymentType InstallmentSecured production' => ['fetchPaymentType', ['p-hdd-12345678'], $getPaymentTypeCB(InstallmentSecured::class)], + 'PaymentType Invoice factoring production' => ['fetchPaymentType', ['p-ivf-12345678'], $getPaymentTypeCB(InvoiceSecured::class)], 'PaymentType Invoice production' => ['fetchPaymentType', ['p-ivc-12345678'], $getPaymentTypeCB(Invoice::class)], 'PaymentType InvoiceGuaranteed production' => ['fetchPaymentType', ['p-ivg-12345678'], $getPaymentTypeCB(InvoiceSecured::class)], - 'PaymentType Invoice factoring production' => ['fetchPaymentType', ['p-ivf-12345678'], $getPaymentTypeCB(InvoiceSecured::class)], + 'PaymentType Paylater-Invoice production' => ['fetchPaymentType', ['p-piv-12345678'], $getPaymentTypeCB(PaylaterInvoice::class)], 'PaymentType Paypal production' => ['fetchPaymentType', ['p-ppl-12345678'], $getPaymentTypeCB(Paypal::class)], + 'PaymentType PFC production' => ['fetchPaymentType', ['p-pfc-12345678'], $getPaymentTypeCB(PostFinanceCard::class)], + 'PaymentType PFE production' => ['fetchPaymentType', ['p-pfe-12345678'], $getPaymentTypeCB(PostFinanceEfinance::class)], 'PaymentType Prepayment production' => ['fetchPaymentType', ['p-ppy-12345678'], $getPaymentTypeCB(Prepayment::class)], 'PaymentType Przelewy24 production' => ['fetchPaymentType', ['p-p24-12345678'], $getPaymentTypeCB(Przelewy24::class)], 'PaymentType SepaDirectDebit production' => ['fetchPaymentType', ['p-sdd-12345678'], $getPaymentTypeCB(SepaDirectDebit::class)], 'PaymentType SepaDirectDebitGuaranteed production' => ['fetchPaymentType', ['p-ddg-12345678'], $getPaymentTypeCB(SepaDirectDebitSecured::class)], 'PaymentType SepaDirectDebitSecured production' => ['fetchPaymentType', ['p-dds-12345678'], $getPaymentTypeCB(SepaDirectDebitSecured::class)], 'PaymentType Sofort production' => ['fetchPaymentType', ['p-sft-12345678'], $getPaymentTypeCB(Sofort::class)], - 'PaymentType EPS production' => ['fetchPaymentType', ['p-eps-12345678'], $getPaymentTypeCB(EPS::class)], - 'PaymentType Alipay production' => ['fetchPaymentType', ['p-ali-12345678'], $getPaymentTypeCB(Alipay::class)], 'PaymentType Wechatpay production' => ['fetchPaymentType', ['p-wcp-12345678'], $getPaymentTypeCB(Wechatpay::class)], - 'PaymentType HirePurchaseDirectDebit production' => ['fetchPaymentType', ['p-hdd-12345678'], $getPaymentTypeCB(InstallmentSecured::class)], - 'PaymentType InstallmentSecured production' => ['fetchPaymentType', ['p-hdd-12345678'], $getPaymentTypeCB(InstallmentSecured::class)], - 'PaymentType Bancontact production' => ['fetchPaymentType', ['p-bct-12345678'], $getPaymentTypeCB(Bancontact::class)], ]; } diff --git a/vendor/unzerdev/php-sdk/test/unit/Services/WebhooksServiceTest.php b/vendor/unzerdev/php-sdk/test/unit/Services/WebhooksServiceTest.php index 975a056..b21f940 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Services/WebhooksServiceTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Services/WebhooksServiceTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Services; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeTest.php index c326915..5597d71 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeWithCustomerTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeWithCustomerTest.php index fade082..c5f46e4 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeWithCustomerTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/CanAuthorizeWithCustomerTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeTest.php index 5e6d0a7..4c40330 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeWithCustomerTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeWithCustomerTest.php index 9a6bbbb..5cd94ea 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeWithCustomerTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/CanDirectChargeWithCustomerTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutTest.php index 32f335e..f026fe5 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutWithCustomerTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutWithCustomerTest.php index 7bf318b..83cb619 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutWithCustomerTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/CanPayoutWithCustomerTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/CanRecurTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/CanRecurTest.php index cb0ddda..2d4738a 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/CanRecurTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/CanRecurTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/HasAdditionalTransactionDataTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/HasAdditionalTransactionDataTest.php new file mode 100644 index 0000000..2a926e8 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/HasAdditionalTransactionDataTest.php @@ -0,0 +1,143 @@ +assertNull($dummy->getShipping()); + $this->assertNull($dummy->getRiskData()); + $this->assertNull($dummy->getPrivacyPolicyUrl()); + $this->assertNull($dummy->getTermsAndConditionUrl()); + $this->assertNull($dummy->getCheckoutType()); + + $shipping = (new ShippingData()) + ->setDeliveryService('deliveryService') + ->setDeliveryTrackingId('deliveryTrackingId') + ->setReturnTrackingId('returnTrackingId'); + + $riskData = (new RiskData()) + ->setThreatMetrixId('threatMetrixId'); + + $privacyPolicyUrl = 'privacyPolicyUrl'; + $termsAndConditionUrl = 'termsAndConditionUrl'; + $dummy->setShipping($shipping) + ->setRiskData($riskData) + ->setPrivacyPolicyUrl($privacyPolicyUrl) + ->setCheckoutType('express', new Paypal()) + ->setTermsAndConditionUrl($termsAndConditionUrl); + + $this->assertNotNull($dummy->getShipping()); + $this->assertNotNull($dummy->getRiskData()); + $this->assertNotNull($dummy->getPrivacyPolicyUrl()); + $this->assertNotNull($dummy->getTermsAndConditionUrl()); + $this->assertNotNull($dummy->getCheckoutType()); + + $this->assertEquals($shipping, $dummy->getShipping()); + $this->assertEquals($riskData, $dummy->getRiskData()); + $this->assertEquals($privacyPolicyUrl, $dummy->getPrivacyPolicyUrl()); + $this->assertEquals($termsAndConditionUrl, $dummy->getTermsAndConditionUrl()); + } + + /** + * Setting and getting card data should work as expected. + * + * @test + */ + public function setAndGetCardData(): void + { + $dummy = new TraitDummyHasAdditionalTransactionData(); + $this->assertNull($dummy->getCardTransactionData()); + + $cardTransactionData = (new CardTransactionData()) + ->setRecurrenceType('recurrenceType') + ->setExemptionType('exemptionType'); + + $dummy->setCardTransactionData($cardTransactionData); + + $cardData = $dummy->getCardTransactionData(); + $this->assertNotNull($cardData); + $this->assertEquals('exemptionType', $cardData->getExemptionType()); + $this->assertNull($cardData->getLiability()); + $this->assertEquals('recurrenceType', $cardData->getRecurrenceType()); + } + + /** + * CardData should be exposed correctly. + * + * @test + */ + public function exposeCardDataAsExpected(): void + { + $dummy = new TraitDummyHasAdditionalTransactionData(); + $this->assertNull($dummy->getCardTransactionData()); + + $cardTransactionData = (new CardTransactionData()) + ->setRecurrenceType('recurrenceType') + ->setExemptionType('exemptionType'); + + $dummy->setCardTransactionData($cardTransactionData); + + $exposedResource = $dummy->expose(); + $this->assertNotNull($exposedResource['additionalTransactionData']); + $additionalTransactionData = $exposedResource['additionalTransactionData']; + + $this->assertFalse(isset($additionalTransactionData->card['liability'])); + $this->assertEquals('recurrenceType', $additionalTransactionData->card['recurrenceType']); + $this->assertEquals('exemptionType', $additionalTransactionData->card['exemptionType']); + } + + /** + * Verify checkoutType can be set via typeId correctly. + * + * @test + */ + public function checkoutTypeCanBeSetViaTypeId(): void + { + $dummy = new TraitDummyHasAdditionalTransactionData(); + $dummy->setCheckoutType('checkoutType', 's-ppl-xyz'); + + $additionalTransactionData = $dummy->getAdditionalTransactionData(); + $this->assertTrue(property_exists($additionalTransactionData, 'paypal')); + $this->assertEquals($additionalTransactionData->paypal->checkoutType, 'checkoutType'); + } + + /** + * @test + */ + public function getterShouldReturnNullIfAdittionalTransactionDataDoNOtContainProperObject() + { + $dummy = new TraitDummyHasAdditionalTransactionData(); + $dummy->addAdditionalTransactionData('shipping', 'This is not a shippingObject!'); + $dummy->addAdditionalTransactionData('riskData', 'This is not a riskDataObject!'); + + $this->assertEquals('This is not a shippingObject!', $dummy->getAdditionalTransactionData()->shipping); + $this->assertEquals('This is not a riskDataObject!', $dummy->getAdditionalTransactionData()->riskData); + + $this->assertNull($dummy->getShipping()); + $this->assertNull($dummy->getRiskData()); + } +} diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/HasCancellationsTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/HasCancellationsTest.php index 459715e..36b76a2 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/HasCancellationsTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/HasCancellationsTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Resources\TransactionTypes\Authorization; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/HasInvoiceIdTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/HasInvoiceIdTest.php index a184151..ff0a489 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/HasInvoiceIdTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/HasInvoiceIdTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\test\BasePaymentTest; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/HasPaymentStateTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/HasPaymentStateTest.php index ad3b086..1a71580 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/HasPaymentStateTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/HasPaymentStateTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Constants\PaymentState; @@ -35,6 +20,7 @@ class HasPaymentStateTest extends BasePaymentTest * Verify that getters and setters work properly. * * @test + * * @dataProvider gettersAndSettersShouldWorkProperlyDP * * @param mixed $state @@ -45,6 +31,7 @@ class HasPaymentStateTest extends BasePaymentTest * @param mixed $partlyPaid * @param mixed $paymentReview * @param mixed $chargeBack + * @param mixed $create */ public function gettersAndSettersShouldWorkProperly( $state, @@ -54,7 +41,8 @@ public function gettersAndSettersShouldWorkProperly( $canceled, $partlyPaid, $paymentReview, - $chargeBack + $chargeBack, + $create ): void { $traitDummy = new TraitDummyHasCancellationsHasPaymentState(); $this->assertEquals(PaymentState::STATE_PENDING, $traitDummy->getState()); @@ -65,6 +53,7 @@ public function gettersAndSettersShouldWorkProperly( $this->assertFalse($traitDummy->isPartlyPaid()); $this->assertFalse($traitDummy->isPaymentReview()); $this->assertFalse($traitDummy->isChargeBack()); + $this->assertFalse($traitDummy->isCreate()); $traitDummy->handleResponse((object)['state' => $state]); $this->assertEquals($state, $traitDummy->getState()); @@ -75,6 +64,7 @@ public function gettersAndSettersShouldWorkProperly( $this->assertEquals($partlyPaid, $traitDummy->isPartlyPaid()); $this->assertEquals($paymentReview, $traitDummy->isPaymentReview()); $this->assertEquals($chargeBack, $traitDummy->isChargeBack()); + $this->assertEquals($create, $traitDummy->isCreate()); } // @@ -95,6 +85,7 @@ public function gettersAndSettersShouldWorkProperlyDP(): array false, false, false, + false, false ], 'completed' => [ @@ -105,6 +96,7 @@ public function gettersAndSettersShouldWorkProperlyDP(): array false, false, false, + false, false ], 'canceled' => [ @@ -115,6 +107,7 @@ public function gettersAndSettersShouldWorkProperlyDP(): array true, false, false, + false, false ], 'partly_paid' => [ @@ -125,6 +118,7 @@ public function gettersAndSettersShouldWorkProperlyDP(): array false, true, false, + false, false ], 'payment_review' => [ @@ -135,6 +129,7 @@ public function gettersAndSettersShouldWorkProperlyDP(): array false, false, true, + false, false ], 'chargeback' => [ @@ -145,6 +140,18 @@ public function gettersAndSettersShouldWorkProperlyDP(): array false, false, false, + true, + false + ], + 'create' => [ + PaymentState::STATE_CREATE, + PaymentState::STATE_NAME_CREATE, + false, + false, + false, + false, + false, + false, true ] ]; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/HasRecurrenceTypeTest.php b/vendor/unzerdev/php-sdk/test/unit/Traits/HasRecurrenceTypeTest.php index 526b0f1..f2044f2 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/HasRecurrenceTypeTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/HasRecurrenceTypeTest.php @@ -1,39 +1,19 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; -use RuntimeException; use UnzerSDK\Constants\RecurrenceTypes; use UnzerSDK\Resources\Payment; -use UnzerSDK\Resources\PaymentTypes\BasePaymentType; use UnzerSDK\Resources\PaymentTypes\Card; -use UnzerSDK\Resources\PaymentTypes\Paypal; -use UnzerSDK\Resources\PaymentTypes\SepaDirectDebit; -use UnzerSDK\Resources\PaymentTypes\Sofort; use UnzerSDK\Resources\Recurring; use UnzerSDK\Resources\TransactionTypes\Charge; use UnzerSDK\test\BasePaymentTest; @@ -63,8 +43,8 @@ public function hasRecurrenceTypeGettersAndSettersShouldWorkProperly(): void // Check correct data structure. $this->assertNotNull($charge->getAdditionalTransactionData()); - $this->assertObjectHasAttribute('card', $charge->getAdditionalTransactionData()); - $this->assertObjectHasAttribute('recurrenceType', $charge->getAdditionalTransactionData()->card); + $this->assertTrue(property_exists($charge->getAdditionalTransactionData(), 'card')); + $this->assertTrue(property_exists($charge->getAdditionalTransactionData()->card, 'recurrenceType')); // Recurrence type can be updated correctly. $this->assertEquals('oneclick', $charge->getRecurrenceType()); @@ -93,7 +73,7 @@ public function recurrenceTypeShouldBeExposedProperly(): void $charge->setRecurrenceType(RecurrenceTypes::ONE_CLICK); $exposedTransaction = $charge->expose(); - $this->assertEquals('oneclick', $exposedTransaction['additionalTransactionData']->card->recurrenceType); + $this->assertEquals('oneclick', $exposedTransaction['additionalTransactionData']->card['recurrenceType']); $this->assertStringContainsString( '"additionalTransactionData":{"card":{"recurrenceType":"oneclick"}}', $charge->jsonSerialize() @@ -132,30 +112,6 @@ public function responseShouldBeHandledProperlyWithRecurrenceType(): void ); } - /** - * The object containing recurrenceType should named according to the current payment Type. - * - * @test - * - * @dataProvider recurrenceTypeShouldConsiderPaymentTypeDP - * - * @param $paymentType - * @param mixed $methodName - * - * @throws \UnzerSDK\Exceptions\UnzerApiException - */ - public function recurrenceTypeShouldConsiderPaymentType(BasePaymentType $paymentType, $methodName): void - { - $unzerObj = new Unzer('s-priv-123345'); - $paymentType->setId('123'); - $payment = new Payment(); - $payment->setParentResource($unzerObj)->setPaymentType($paymentType); - $charge = (new Charge())->setPayment($payment); - $this->assertNull($charge->getAdditionalTransactionData()); - $charge->setRecurrenceType(RecurrenceTypes::ONE_CLICK); - $this->assertObjectHasAttribute($methodName, $charge->getAdditionalTransactionData()); - } - /** * recurrence type should be set properly for recurring. * @@ -169,32 +125,4 @@ public function recurrenceTypeShouldBeSetProperlyForRecurring() $this->assertEquals('scheduled', $recurring->getRecurrenceType()); } - - /** - * recurrence type should be set properly for recurring. - * - * @test - */ - public function settingRecurrenceTypeShouldTrowExceptionIfTypeIsNotProvidedForRecurring(): void - { - $recurring = new Recurring('typeId', 'returnUrl'); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Payment type can not be determined. Set it first or provide it via parameter $paymentType.'); - - $recurring->setRecurrenceType(RecurrenceTypes::SCHEDULED); - } - - /** Provides payment types and expected key name that should be used to set the recurrence type. - * @return array[] - */ - public function recurrenceTypeShouldConsiderPaymentTypeDP(): array - { - return [ - 'card' => [new Card(null, null), 'card'], - 'sofort' => [new Sofort(), 'sofort'], - 'sepa-direct-debit' => [new SepaDirectDebit(null), 'sepa-direct-debit'], - 'paypal' => [new Paypal(), 'paypal'] - ]; - } } diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecur.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecur.php index fb61927..af8dc50 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecur.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecur.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Resources\PaymentTypes\BasePaymentType; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecurNonResource.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecurNonResource.php index 05676bf..6f887e8 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecurNonResource.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyCanRecurNonResource.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Traits\CanRecur; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyHasAdditionalTransactionData.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyHasAdditionalTransactionData.php new file mode 100644 index 0000000..7af7c01 --- /dev/null +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyHasAdditionalTransactionData.php @@ -0,0 +1,20 @@ + - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Resources\AbstractUnzerResource; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyHasInvoiceId.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyHasInvoiceId.php index 149036b..2b11875 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyHasInvoiceId.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyHasInvoiceId.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Traits\HasInvoiceId; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithParentIF.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithParentIF.php index 1e8cc65..ed72041 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithParentIF.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithParentIF.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Unzer; @@ -52,12 +37,12 @@ public function getUnzerObject(): Unzer /** * Returns the url string for this resource. * - * @param bool $appendId - * @param $httpMethod + * @param bool $appendId + * @param string $httpMethod * * @return string */ - public function getUri($appendId = true, $httpMethod = HttpAdapterInterface::REQUEST_GET): string + public function getUri(bool $appendId = true, string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'test/uri/'; } diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithoutParentIF.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithoutParentIF.php index f69b99d..c8eedaf 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithoutParentIF.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithCustomerWithoutParentIF.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Traits\CanAuthorizeWithCustomer; diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithParentIF.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithParentIF.php index bc573e2..084bde4 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithParentIF.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithParentIF.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Adapter\HttpAdapterInterface; @@ -58,7 +43,7 @@ public function getUnzerObject(): Unzer * * @return string */ - public function getUri($appendId = true, $httpMethod = HttpAdapterInterface::REQUEST_GET): string + public function getUri(bool $appendId = true, string $httpMethod = HttpAdapterInterface::REQUEST_GET): string { return 'test/uri/'; } diff --git a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithoutParentIF.php b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithoutParentIF.php index 7c1f35a..abb2d9c 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithoutParentIF.php +++ b/vendor/unzerdev/php-sdk/test/unit/Traits/TraitDummyWithoutCustomerWithoutParentIF.php @@ -1,30 +1,15 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Traits; use UnzerSDK\Traits\CanAuthorize; diff --git a/vendor/unzerdev/php-sdk/test/unit/UnzerTest.php b/vendor/unzerdev/php-sdk/test/unit/UnzerTest.php index fc67c67..771196b 100644 --- a/vendor/unzerdev/php-sdk/test/unit/UnzerTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/UnzerTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit; use DateTime; @@ -82,7 +67,9 @@ public function gettersAndSettersShouldWorkProperly(): void { $unzer = new Unzer('s-priv-1234'); $unzer->setLocale('myLocale'); + $unzer->setClientIp('myIpAddress'); $this->assertEquals('myLocale', $unzer->getLocale()); + $this->assertEquals('myIpAddress', $unzer->getClientIp()); try { $unzer->setKey('this is not a valid key'); @@ -126,6 +113,7 @@ public function gettersAndSettersShouldWorkProperly(): void * Verify Unzer propagates resource actions to the resource service. * * @test + * * @dataProvider resourceServiceDP * * @param string $unzerMethod @@ -151,6 +139,7 @@ public function unzerShouldForwardResourceActionCallsToTheResourceService( * Verify Unzer propagates payment actions to the payment service. * * @test + * * @dataProvider paymentServiceDP * * @param string $unzerMethod @@ -176,6 +165,7 @@ public function unzerShouldForwardPaymentActionCallsToThePaymentService( * Verify Unzer propagates webhook actions to the webhook service. * * @test + * * @dataProvider UnzerShouldForwardWebhookActionCallsToTheWebhookServiceDP * * @param string $unzerMethod @@ -201,6 +191,7 @@ public function unzerShouldForwardWebhookActionCallsToTheWebhookService( * Verify Unzer propagates cancel actions to the cancel service. * * @test + * * @dataProvider cancelServiceDP * * @param string $unzerMethod @@ -321,7 +312,7 @@ public static function paymentServiceDP(): array 'chargePayment' => ['chargePayment', [$payment, 1.234, 'ALL'], 'chargePayment', [$payment, 1.234, 'ALL']], 'chargePaymentAlt' => ['chargePayment', [$payment], 'chargePayment', [$payment]], 'ship' => ['ship', [$payment], 'ship', [$payment]], - 'payout' => ['payout', [123, 'EUR', $paymentTypeId, 'url', $customer, $orderId, $metadata, 'basketId'], 'payout', [123, 'EUR', $paymentTypeId, 'url', $customer, $orderId, $metadata, 'basketId']], + 'payout' => ['payout', [123, 'EUR', $paymentTypeId, 'url', $customer, $orderId, $metadata, $basket], 'payout', [123, 'EUR', $paymentTypeId, 'url', $customer, $orderId, $metadata, $basket]], 'initPayPageCharge' => ['initPayPageCharge', [$paypage, $customer, $basket, $metadata], 'initPayPageCharge', [$paypage, $customer, $basket, $metadata]], 'initPayPageAuthorize' => ['initPayPageAuthorize', [$paypage, $customer, $basket, $metadata], 'initPayPageAuthorize', [$paypage, $customer, $basket, $metadata]], 'fetchDDInstalmentPlans' => ['fetchInstallmentPlans', [123.4567, 'EUR', 4.99, $today], 'fetchInstallmentPlans', [123.4567, 'EUR', 4.99, $today]] @@ -341,16 +332,16 @@ public static function unzerShouldForwardWebhookActionCallsToTheWebhookServiceDP $event = ['event1', 'event2']; return [ - 'createWebhook'=> [ 'createWebhook', [$url, 'event'], 'createWebhook', [$url, 'event'] ], - 'fetchWebhook'=> [ 'fetchWebhook', [$webhookId], 'fetchWebhook', [$webhookId] ], - 'fetchWebhook by object'=> [ 'fetchWebhook', [$webhook], 'fetchWebhook', [$webhook] ], - 'updateWebhook'=> [ 'updateWebhook', [$webhook], 'updateWebhook', [$webhook] ], - 'deleteWebhook'=> [ 'deleteWebhook', [$webhookId], 'deleteWebhook', [$webhookId] ], - 'deleteWebhook by object'=> [ 'deleteWebhook', [$webhook], 'deleteWebhook', [$webhook] ], - 'fetchAllWebhooks'=> [ 'fetchAllWebhooks', [], 'fetchAllWebhooks', [] ], - 'deleteAllWebhooks'=> [ 'deleteAllWebhooks', [], 'deleteAllWebhooks', [] ], - 'registerMultipleWebhooks'=> ['registerMultipleWebhooks', [$url, $event], 'registerMultipleWebhooks', [$url, $event] ], - 'fetchResourceFromEvent'=> ['fetchResourceFromEvent', [], 'fetchResourceFromEvent', [] ] + 'createWebhook' => [ 'createWebhook', [$url, 'event'], 'createWebhook', [$url, 'event'] ], + 'fetchWebhook' => [ 'fetchWebhook', [$webhookId], 'fetchWebhook', [$webhookId] ], + 'fetchWebhook by object' => [ 'fetchWebhook', [$webhook], 'fetchWebhook', [$webhook] ], + 'updateWebhook' => [ 'updateWebhook', [$webhook], 'updateWebhook', [$webhook] ], + 'deleteWebhook' => [ 'deleteWebhook', [$webhookId], 'deleteWebhook', [$webhookId] ], + 'deleteWebhook by object' => [ 'deleteWebhook', [$webhook], 'deleteWebhook', [$webhook] ], + 'fetchAllWebhooks' => [ 'fetchAllWebhooks', [], 'fetchAllWebhooks', [] ], + 'deleteAllWebhooks' => [ 'deleteAllWebhooks', [], 'deleteAllWebhooks', [] ], + 'registerMultipleWebhooks' => ['registerMultipleWebhooks', [$url, $event], 'registerMultipleWebhooks', [$url, $event] ], + 'fetchResourceFromEvent' => ['fetchResourceFromEvent', [], 'fetchResourceFromEvent', [] ] ]; } diff --git a/vendor/unzerdev/php-sdk/test/unit/Validators/PrivateKeyValidatorTest.php b/vendor/unzerdev/php-sdk/test/unit/Validators/PrivateKeyValidatorTest.php index 31fa6eb..2777a88 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Validators/PrivateKeyValidatorTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Validators/PrivateKeyValidatorTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Validators; use UnzerSDK\test\BasePaymentTest; @@ -35,6 +20,7 @@ class PrivateKeyValidatorTest extends BasePaymentTest * Verify validate method behaves as expected. * * @test + * * @dataProvider validateShouldReturnTrueIfPrivateKeyHasCorrectFormatDP * * @param string $key diff --git a/vendor/unzerdev/php-sdk/test/unit/Validators/PublicKeyValidatorTest.php b/vendor/unzerdev/php-sdk/test/unit/Validators/PublicKeyValidatorTest.php index 18411ae..b00264d 100644 --- a/vendor/unzerdev/php-sdk/test/unit/Validators/PublicKeyValidatorTest.php +++ b/vendor/unzerdev/php-sdk/test/unit/Validators/PublicKeyValidatorTest.php @@ -1,29 +1,14 @@ - * - * @package UnzerSDK\test\unit */ + namespace UnzerSDK\test\unit\Validators; use UnzerSDK\test\BasePaymentTest; @@ -35,6 +20,7 @@ class PublicKeyValidatorTest extends BasePaymentTest * Verify validate method behaves as expected. * * @test + * * @dataProvider validateShouldReturnTrueIfPublicKeyHasCorrectFormatDP * * @param string $key diff --git a/vendor/unzerdev/php-sdk/unzer_logo.svg b/vendor/unzerdev/php-sdk/unzer_logo.svg new file mode 100644 index 0000000..bfe66da --- /dev/null +++ b/vendor/unzerdev/php-sdk/unzer_logo.svg @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + +