Data.php 48.3 KB
Newer Older
rikterbeek's avatar
rikterbeek committed
1 2
<?php
/**
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * Adyen Payment module (https://www.adyen.com/)
 *
 * Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
 * See LICENSE.txt for license details.
 *
 * Author: Adyen <magento@adyen.com>
rikterbeek's avatar
rikterbeek committed
22
 */
23

rikterbeek's avatar
rikterbeek committed
24 25 26 27 28 29 30 31 32
namespace Adyen\Payment\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

/**
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class Data extends AbstractHelper
{
33
    const MODULE_NAME = 'adyen-magento2';
34 35
    const TEST = 'test';
    const LIVE = 'live';
36
    const CHECKOUT_CONTEXT_URL_LIVE = 'https://checkoutshopper-live.adyen.com/checkoutshopper/';
Rik ter Beek's avatar
Rik ter Beek committed
37
    const CHECKOUT_CONTEXT_URL_TEST = 'https://checkoutshopper-test.adyen.com/checkoutshopper/';
38 39
    const CHECKOUT_COMPONENT_JS_LIVE = 'https://checkoutshopper-live.adyen.com/checkoutshopper/sdk/2.0.0/adyen.js';
    const CHECKOUT_COMPONENT_JS_TEST = 'https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/2.0.0/adyen.js';
40

41 42 43
    /**
     * @var \Magento\Framework\Encryption\EncryptorInterface
     */
44 45
    protected $_encryptor;

46 47 48 49
    /**
     * @var \Magento\Framework\Config\DataInterface
     */
    protected $_dataStorage;
50

rikterbeek's avatar
#40  
rikterbeek committed
51 52 53 54 55
    /**
     * @var \Magento\Directory\Model\Config\Source\Country
     */
    protected $_country;

rikterbeek's avatar
rikterbeek committed
56 57 58 59 60
    /**
     * @var \Magento\Framework\Module\ModuleListInterface
     */
    protected $_moduleList;

61
    /**
62
     * @var \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory
63 64 65 66
     */
    protected $_billingAgreementCollectionFactory;

    /**
67
     * @var \Magento\Framework\View\Asset\Repository
68 69 70 71 72 73 74 75
     */
    protected $_assetRepo;

    /**
     * @var \Magento\Framework\View\Asset\Source
     */
    protected $_assetSource;

76 77 78 79 80
    /**
     * @var \Adyen\Payment\Model\ResourceModel\Notification\CollectionFactory
     */
    protected $_notificationFactory;

81 82 83 84 85 86 87 88 89 90
    /**
     * @var \Magento\Tax\Model\Config
     */
    protected $_taxConfig;

    /**
     * @var \Magento\Tax\Model\Calculation
     */
    protected $_taxCalculation;

91 92 93
    /**
     * @var \Magento\Framework\App\ProductMetadataInterface
     */
94 95
    protected $productMetadata;

96 97 98
    /**
     * @var \Adyen\Payment\Logger\AdyenLogger
     */
99 100
    protected $adyenLogger;

Rik ter Beek's avatar
Rik ter Beek committed
101 102 103
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
104 105
    protected $storeManager;

Rik ter Beek's avatar
Rik ter Beek committed
106 107 108
    /**
     * @var \Magento\Framework\App\CacheInterface
     */
109
    protected $cache;
110

Rik ter Beek's avatar
Rik ter Beek committed
111
    /**
112
     * @var \Adyen\Payment\Model\Billing\AgreementFactory
Rik ter Beek's avatar
Rik ter Beek committed
113
     */
114
    protected $billingAgreementFactory;
115

116 117 118 119 120
    /**
     * @var ResourceModel\Billing\Agreement
     */
    private $agreementResourceModel;

Rik ter Beek's avatar
Rik ter Beek committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    /**
     * Data constructor.
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
     * @param \Magento\Framework\Config\DataInterface $dataStorage
     * @param \Magento\Directory\Model\Config\Source\Country $country
     * @param \Magento\Framework\Module\ModuleListInterface $moduleList
     * @param \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
     * @param \Magento\Framework\View\Asset\Repository $assetRepo
     * @param \Magento\Framework\View\Asset\Source $assetSource
     * @param \Adyen\Payment\Model\ResourceModel\Notification\CollectionFactory $notificationFactory
     * @param \Magento\Tax\Model\Config $taxConfig
     * @param \Magento\Tax\Model\Calculation $taxCalculation
     * @param \Magento\Framework\App\ProductMetadataInterface $productMetadata
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\App\CacheInterface $cache
     * @param \Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory
139
     * @param \Adyen\Payment\Model\ResourceModel\Billing\Agreement $agreementResourceModel
Rik ter Beek's avatar
Rik ter Beek committed
140
     */
141 142
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
143
        \Magento\Framework\Encryption\EncryptorInterface $encryptor,
rikterbeek's avatar
#40  
rikterbeek committed
144
        \Magento\Framework\Config\DataInterface $dataStorage,
rikterbeek's avatar
rikterbeek committed
145
        \Magento\Directory\Model\Config\Source\Country $country,
146
        \Magento\Framework\Module\ModuleListInterface $moduleList,
147
        \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory,
148
        \Magento\Framework\View\Asset\Repository $assetRepo,
149
        \Magento\Framework\View\Asset\Source $assetSource,
150 151
        \Adyen\Payment\Model\ResourceModel\Notification\CollectionFactory $notificationFactory,
        \Magento\Tax\Model\Config $taxConfig,
152
        \Magento\Tax\Model\Calculation $taxCalculation,
153 154 155 156
        \Magento\Framework\App\ProductMetadataInterface $productMetadata,
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\CacheInterface $cache,
157 158
        \Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory,
        \Adyen\Payment\Model\ResourceModel\Billing\Agreement $agreementResourceModel
159
    ) {
160
        parent::__construct($context);
161
        $this->_encryptor = $encryptor;
162
        $this->_dataStorage = $dataStorage;
rikterbeek's avatar
#40  
rikterbeek committed
163
        $this->_country = $country;
rikterbeek's avatar
rikterbeek committed
164
        $this->_moduleList = $moduleList;
165 166 167
        $this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
        $this->_assetRepo = $assetRepo;
        $this->_assetSource = $assetSource;
168
        $this->_notificationFactory = $notificationFactory;
169 170
        $this->_taxConfig = $taxConfig;
        $this->_taxCalculation = $taxCalculation;
171 172
        $this->productMetadata = $productMetadata;
        $this->adyenLogger = $adyenLogger;
173 174
        $this->storeManager = $storeManager;
        $this->cache = $cache;
175
        $this->billingAgreementFactory = $billingAgreementFactory;
176
        $this->agreementResourceModel = $agreementResourceModel;
177 178
    }

179
    /**
attilak's avatar
attilak committed
180
     * return recurring types for configuration setting
181 182
     * @return array
     */
183 184
    public function getRecurringTypes()
    {
rikterbeek's avatar
rikterbeek committed
185 186 187 188 189 190 191
        return [
            \Adyen\Payment\Model\RecurringType::ONECLICK => 'ONECLICK',
            \Adyen\Payment\Model\RecurringType::ONECLICK_RECURRING => 'ONECLICK,RECURRING',
            \Adyen\Payment\Model\RecurringType::RECURRING => 'RECURRING'
        ];
    }

192
    /**
attilak's avatar
attilak committed
193
     * return recurring types for configuration setting
194 195
     * @return array
     */
196 197
    public function getModes()
    {
198 199 200 201 202 203
        return [
            '1' => 'Test Mode',
            '0' => 'Production Mode'
        ];
    }

204
    /**
attilak's avatar
attilak committed
205
     * eturn recurring types for configuration setting
206 207
     * @return array
     */
208 209
    public function getCaptureModes()
    {
210 211 212 213 214 215
        return [
            'auto' => 'immediate',
            'manual' => 'manual'
        ];
    }

216
    /**
attilak's avatar
attilak committed
217
     * return recurring types for configuration setting
218 219
     * @return array
     */
220 221
    public function getPaymentRoutines()
    {
222 223 224 225 226 227
        return [
            'single' => 'Single Page Payment Routine',
            'multi' => 'Multi-page Payment Routine'
        ];
    }

228

229 230 231 232 233 234 235 236
    /**
     * Return the formatted currency. Adyen accepts the currency in multiple formats.
     * @param $amount
     * @param $currency
     * @return string
     */
    public function formatAmount($amount, $currency)
    {
237
        switch ($currency) {
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
            case "JPY":
            case "IDR":
            case "KRW":
            case "BYR":
            case "VND":
            case "CVE":
            case "DJF":
            case "GNF":
            case "PYG":
            case "RWF":
            case "UGX":
            case "VUV":
            case "XAF":
            case "XOF":
            case "XPF":
            case "GHC":
            case "KMF":
                $format = 0;
                break;
            case "MRO":
                $format = 1;
                break;
            case "BHD":
            case "JOD":
            case "KWD":
            case "OMR":
            case "LYD":
            case "TND":
                $format = 3;
                break;
            default:
                $format = 2;
                break;
        }

273 274 275 276 277 278 279 280 281 282 283 284 285
        return (int)number_format($amount, $format, '', '');
    }

    /**
     * Tax Percentage needs to be in minor units for Adyen
     *
     * @param float $taxPercent
     * @return int
     */
    public function getMinorUnitTaxPercent($taxPercent)
    {
        $taxPercent = $taxPercent * 100;
        return (int)$taxPercent;
286 287
    }

288 289 290 291 292
    /**
     * @param $amount
     * @param $currency
     * @return float
     */
293 294 295
    public function originalAmount($amount, $currency)
    {
        // check the format
296
        switch ($currency) {
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
            case "JPY":
            case "IDR":
            case "KRW":
            case "BYR":
            case "VND":
            case "CVE":
            case "DJF":
            case "GNF":
            case "PYG":
            case "RWF":
            case "UGX":
            case "VUV":
            case "XAF":
            case "XOF":
            case "XPF":
            case "GHC":
            case "KMF":
                $format = 1;
                break;
            case "MRO":
                $format = 10;
                break;
            case "BHD":
            case "JOD":
            case "KWD":
            case "OMR":
            case "LYD":
            case "TND":
                $format = 1000;
                break;
            default:
                $format = 100;
                break;
        }

        return ($amount / $format);
    }

335 336 337 338 339 340 341
    /**
     * Street format
     * @param type $address
     * @return array
     */
    public function getStreet($address)
    {
342 343 344 345
        if (empty($address)) {
            return false;
        }

346 347 348
        $street = self::formatStreet($address->getStreet());
        $streetName = $street['0'];
        unset($street['0']);
349
        $streetNr = implode(' ', $street);
rikterbeek's avatar
rikterbeek committed
350
        return (['name' => trim($streetName), 'house_number' => $streetNr]);
351 352 353 354 355
    }

    /**
     * Fix this one string street + number
     * @example street + number
356 357
     * @param array $street
     * @return array $street
358
     */
359
    public static function formatStreet($street)
360 361 362 363 364
    {
        if (count($street) != 1) {
            return $street;
        }
        preg_match('/((\s\d{0,10})|(\s\d{0,10}\w{1,3}))$/i', $street['0'], $houseNumber, PREG_OFFSET_CAPTURE);
365
        if (!empty($houseNumber['0'])) {
366 367
            $_houseNumber = trim($houseNumber['0']['0']);
            $position = $houseNumber['0']['1'];
368 369
            $streetName = trim(substr($street['0'], 0, $position));
            $street = [$streetName, $_houseNumber];
370 371 372 373 374
        }
        return $street;
    }


375
    /**
attilak's avatar
attilak committed
376 377
     * gives back global configuration values
     *
378 379 380 381
     * @param $field
     * @param null $storeId
     * @return mixed
     */
382 383 384 385 386
    public function getAdyenAbstractConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_abstract', $storeId);
    }

387
    /**
attilak's avatar
attilak committed
388 389
     * gives back global configuration values as boolean
     *
390 391 392 393
     * @param $field
     * @param null $storeId
     * @return mixed
     */
394 395 396 397 398
    public function getAdyenAbstractConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_abstract', $storeId, true);
    }

399
    /**
attilak's avatar
attilak committed
400 401
     * Gives back adyen_cc configuration values
     *
402 403 404 405
     * @param $field
     * @param null $storeId
     * @return mixed
     */
406 407 408 409 410
    public function getAdyenCcConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_cc', $storeId);
    }

411
    /**
attilak's avatar
attilak committed
412 413
     * Gives back adyen_cc configuration values as flag
     *
414 415 416 417
     * @param $field
     * @param null $storeId
     * @return mixed
     */
418 419 420 421 422
    public function getAdyenCcConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_cc', $storeId, true);
    }

423
    /**
attilak's avatar
attilak committed
424 425
     * Gives back adyen_cc configuration values as flag
     *
426 427 428 429 430 431 432 433 434
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenCcVaultConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_cc_vault', $storeId, true);
    }

435
    /**
attilak's avatar
attilak committed
436 437
     * Gives back adyen_hpp configuration values
     *
438 439 440 441
     * @param $field
     * @param null $storeId
     * @return mixed
     */
442 443 444 445 446
    public function getAdyenHppConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_hpp', $storeId);
    }

447
    /**
attilak's avatar
attilak committed
448 449
     * Gives back adyen_hpp configuration values as flag
     *
450 451 452 453
     * @param $field
     * @param null $storeId
     * @return mixed
     */
454 455 456 457 458
    public function getAdyenHppConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_hpp', $storeId, true);
    }

459
    /**
attilak's avatar
attilak committed
460 461
     * Gives back adyen_oneclick configuration values
     *
462 463 464 465 466 467 468 469 470 471
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenOneclickConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_oneclick', $storeId);
    }

    /**
attilak's avatar
attilak committed
472 473
     * Gives back adyen_oneclick configuration values as flag
     *
474 475 476 477 478 479 480 481 482
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenOneclickConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_oneclick', $storeId, true);
    }

483 484
    /**
     * @param $field
485
     * @param int|null $storeId
486 487 488 489 490 491 492 493 494
     * @return bool|mixed
     */
    public function getAdyenPosCloudConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pos_cloud', $storeId);
    }

    /**
     * @param $field
495
     * @param int|null $storeId
496 497 498 499 500 501 502
     * @return bool|mixed
     */
    public function getAdyenPosCloudConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pos_cloud', $storeId, true);
    }

503
    /**
attilak's avatar
attilak committed
504 505
     * Gives back adyen_pay_by_mail configuration values
     *
506
     * @param $field
507
     * @param int|null $storeId
508 509 510 511 512 513 514 515
     * @return mixed
     */
    public function getAdyenPayByMailConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pay_by_mail', $storeId);
    }

    /**
attilak's avatar
attilak committed
516 517
     * Gives back adyen_pay_by_mail configuration values as flag
     *
518
     * @param $field
519
     * @param int|null $storeId
520 521 522 523 524 525 526
     * @return mixed
     */
    public function getAdyenPayByMailConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pay_by_mail', $storeId, true);
    }

527
    /**
attilak's avatar
attilak committed
528 529
     * Gives back adyen_boleto configuration values
     *
530 531 532 533 534 535 536 537 538 539
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenBoletoConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_boleto', $storeId);
    }

    /**
attilak's avatar
attilak committed
540 541
     * Gives back adyen_boleto configuration values as flag
     *
542 543 544 545 546 547 548 549 550
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenBoletoConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_boleto', $storeId, true);
    }

Alessio Zampatti's avatar
Alessio Zampatti committed
551
    /**
attilak's avatar
attilak committed
552 553
     * Gives back adyen_apple_pay configuration values
     *
Alessio Zampatti's avatar
Alessio Zampatti committed
554 555 556 557 558 559 560 561
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenApplePayConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_apple_pay', $storeId);
    }
Rik ter Beek's avatar
Rik ter Beek committed
562

Alessio Zampatti's avatar
Alessio Zampatti committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    /**
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenApplePayMerchantIdentifier($storeId = null)
    {
        $demoMode = $this->getAdyenAbstractConfigDataFlag('demo_mode');
        if ($demoMode) {
            return $this->getAdyenApplePayConfigData('merchant_identifier_test', $storeId);
        } else {
            return $this->getAdyenApplePayConfigData('merchant_identifier_live', $storeId);
        }
    }

    /**
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenApplePayPemFileLocation($storeId = null)
    {
        $demoMode = $this->getAdyenAbstractConfigDataFlag('demo_mode');
        if ($demoMode) {
            return $this->getAdyenApplePayConfigData('full_path_location_pem_file_test', $storeId);
        } else {
            return $this->getAdyenApplePayConfigData('full_path_location_pem_file_live', $storeId);
        }
    }

591
    /**
attilak's avatar
attilak committed
592 593
     * Retrieve decrypted hmac key
     *
594 595
     * @return string
     */
596 597 598 599
    public function getHmac()
    {
        switch ($this->isDemoMode()) {
            case true:
600
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenHppConfigData('hmac_test')));
601 602 603
                break;
            default:
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenHppConfigData('hmac_live')));
604 605 606 607 608 609 610 611 612
                break;
        }
        return $secretWord;
    }

    public function getHmacPayByMail()
    {
        switch ($this->isDemoMode()) {
            case true:
613
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenPayByMailConfigData('hmac_test')));
614 615 616
                break;
            default:
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenPayByMailConfigData('hmac_live')));
617 618 619 620 621
                break;
        }
        return $secretWord;
    }

Rik ter Beek's avatar
Rik ter Beek committed
622
    /**
attilak's avatar
attilak committed
623
     * Check if configuration is set to demo mode
Rik ter Beek's avatar
Rik ter Beek committed
624 625 626 627
     *
     * @param int|null $storeId
     * @return mixed
     */
628
    public function isDemoMode($storeId = null)
629
    {
630
        return $this->getAdyenAbstractConfigDataFlag('demo_mode', $storeId);
631 632
    }

633
    /**
attilak's avatar
attilak committed
634 635
     * Retrieve the decrypted notification password
     *
636 637
     * @return string
     */
638 639 640 641 642
    public function getNotificationPassword()
    {
        return $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('notification_password')));
    }

Rik ter Beek's avatar
Rik ter Beek committed
643
    /**
attilak's avatar
attilak committed
644
     * Retrieve the API key
Rik ter Beek's avatar
Rik ter Beek committed
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
     *
     * @param int|null $storeId
     * @return string
     */
    public function getAPIKey($storeId = null)
    {
        if ($this->isDemoMode($storeId)) {
            $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('api_key_test',
                $storeId)));
        } else {
            $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('api_key_live',
                $storeId)));
        }
        return $apiKey;
    }
660

Rik ter Beek's avatar
Rik ter Beek committed
661
    /**
attilak's avatar
attilak committed
662
     * Retrieve the webserver username
Rik ter Beek's avatar
Rik ter Beek committed
663 664 665 666 667 668 669 670 671 672 673 674 675
     *
     * @param int|null $storeId
     * @return string
     */
    public function getWsUsername($storeId = null)
    {
        if ($this->isDemoMode($storeId)) {
            $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_test', $storeId));
        } else {
            $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_live', $storeId));
        }
        return $wsUsername;
    }
676

Rik ter Beek's avatar
Rik ter Beek committed
677
    /**
attilak's avatar
attilak committed
678
     * Retrieve the Live endpoint prefix key
Rik ter Beek's avatar
Rik ter Beek committed
679 680 681 682 683 684 685 686 687
     *
     * @param int|null $storeId
     * @return string
     */
    public function getLiveEndpointPrefix($storeId = null)
    {
        $prefix = trim($this->getAdyenAbstractConfigData('live_endpoint_url_prefix', $storeId));
        return $prefix;
    }
688

689
    /**
attilak's avatar
attilak committed
690 691
     * Cancels the order
     *
692 693
     * @param $order
     */
694 695 696 697 698 699 700 701 702 703 704 705
    public function cancelOrder($order)
    {
        $orderStatus = $this->getAdyenAbstractConfigData('payment_cancelled');
        $order->setActionFlag($orderStatus, true);

        switch ($orderStatus) {
            case \Magento\Sales\Model\Order::STATE_HOLDED:
                if ($order->canHold()) {
                    $order->hold()->save();
                }
                break;
            default:
706
                if ($order->canCancel()) {
707 708 709 710 711 712
                    $order->cancel()->save();
                }
                break;
        }
    }

713 714 715 716 717 718 719 720 721 722
    /**
     * Creditcard type that is selected is different from creditcard type that we get back from the request this
     * function get the magento creditcard type this is needed for getting settings like installments
     * @param $ccType
     * @return mixed
     */
    public function getMagentoCreditCartType($ccType)
    {
        $ccTypesMapper = $this->getCcTypesAltData();

723
        if (isset($ccTypesMapper[$ccType])) {
724 725 726 727 728 729
            $ccType = $ccTypesMapper[$ccType]['code'];
        }

        return $ccType;
    }

730 731 732
    /**
     * @return array
     */
733 734
    public function getCcTypesAltData()
    {
735
        $adyenCcTypes = $this->getAdyenCcTypes();
736
        $types = [];
737 738
        foreach ($adyenCcTypes as $key => $data) {
            $types[$data['code_alt']] = $data;
739
            $types[$data['code_alt']]['code'] = $key;
740 741 742 743
        }
        return $types;
    }

744 745 746
    /**
     * @return mixed
     */
747 748 749 750 751
    public function getAdyenCcTypes()
    {
        return $this->_dataStorage->get('adyen_credit_cards');
    }

752
    /**
attilak's avatar
attilak committed
753 754
     * Retrieve information from payment configuration
     *
755 756 757 758 759
     * @param $field
     * @param $paymentMethodCode
     * @param $storeId
     * @param bool|false $flag
     * @return bool|mixed
760 761 762 763 764
     */
    public function getConfigData($field, $paymentMethodCode, $storeId, $flag = false)
    {
        $path = 'payment/' . $paymentMethodCode . '/' . $field;

765
        if (!$flag) {
766
            return $this->scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
767
        } else {
768
            return $this->scopeConfig->isSetFlag($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
769 770
        }
    }
rikterbeek's avatar
#40  
rikterbeek committed
771 772 773 774 775 776 777 778


    /**
     * @return array
     */
    public function getSepaCountries()
    {
        $sepaCountriesAllowed = [
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
            "AT",
            "BE",
            "BG",
            "CH",
            "CY",
            "CZ",
            "DE",
            "DK",
            "EE",
            "ES",
            "FI",
            "FR",
            "GB",
            "GF",
            "GI",
            "GP",
            "GR",
            "HR",
            "HU",
            "IE",
            "IS",
            "IT",
            "LI",
            "LT",
            "LU",
            "LV",
            "MC",
            "MQ",
            "MT",
            "NL",
            "NO",
            "PL",
            "PT",
            "RE",
            "RO",
            "SE",
            "SI",
            "SK"
rikterbeek's avatar
#40  
rikterbeek committed
817 818 819 820 821 822 823 824 825 826 827 828 829
        ];

        $countryList = $this->_country->toOptionArray();
        $sepaCountries = [];

        foreach ($countryList as $key => $country) {
            $value = $country['value'];
            if (in_array($value, $sepaCountriesAllowed)) {
                $sepaCountries[$value] = $country['label'];
            }
        }
        return $sepaCountries;
    }
rikterbeek's avatar
rikterbeek committed
830

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
    /**
     * Get adyen magento module's name sent to Adyen
     *
     * @return string
     */
    public function getModuleName()
    {
        return (string)self::MODULE_NAME;
    }

    /**
     * Get adyen magento module's version
     *
     * @return string
     */
rikterbeek's avatar
rikterbeek committed
846 847
    public function getModuleVersion()
    {
848
        return (string)$this->_moduleList->getOne("Adyen_Payment")['setup_version'];
rikterbeek's avatar
rikterbeek committed
849
    }
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875

    public function getBoletoTypes()
    {
        return [
            [
                'value' => 'boletobancario_hsbc',
                'label' => __('boletobancario_hsbc'),
            ],
            [
                'value' => 'boletobancario_itau',
                'label' => __('boletobancario_itau'),
            ],
            [
                'value' => 'boletobancario_santander',
                'label' => __('boletobancario_santander'),
            ],
            [
                'value' => 'boletobancario_bradesco',
                'label' => __('boletobancario_bradesco'),
            ],
            [
                'value' => 'boletobancario_bancodobrasil',
                'label' => __('boletobancario_bancodobrasil'),
            ],
        ];
    }
876 877 878 879 880 881 882 883 884 885 886 887 888 889

    /**
     * @param $customerId
     * @param $storeId
     * @param $grandTotal
     * @param $recurringType
     * @return array
     */
    public function getOneClickPaymentMethods($customerId, $storeId, $grandTotal, $recurringType)
    {
        $billingAgreements = [];

        $baCollection = $this->_billingAgreementCollectionFactory->create();
        $baCollection->addFieldToFilter('customer_id', $customerId);
890 891 892
        if ($this->isPerStoreBillingAgreement($storeId)) {
            $baCollection->addFieldToFilter('store_id', $storeId);
        }
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
        $baCollection->addFieldToFilter('method_code', 'adyen_oneclick');
        $baCollection->addActiveFilter();

        foreach ($baCollection as $billingAgreement) {
            $agreementData = $billingAgreement->getAgreementData();

            // no agreementData and contractType then ignore
            if ((!is_array($agreementData)) || (!isset($agreementData['contractTypes']))) {
                continue;
            }

            // check if contractType is supporting the selected contractType for OneClick payments
            $allowedContractTypes = $agreementData['contractTypes'];
            if (in_array($recurringType, $allowedContractTypes)) {
                // check if AgreementLabel is set and if contract has an recurringType
                if ($billingAgreement->getAgreementLabel()) {
                    // for Ideal use sepadirectdebit because it is
                    if ($agreementData['variant'] == 'ideal') {
                        $agreementData['variant'] = 'sepadirectdebit';
                    }

914 915
                    $data = [
                        'reference_id' => $billingAgreement->getReferenceId(),
916 917 918 919 920 921 922 923 924 925
                        'agreement_label' => $billingAgreement->getAgreementLabel(),
                        'agreement_data' => $agreementData
                    ];

                    if ($this->showLogos()) {
                        $logoName = $agreementData['variant'];

                        $asset = $this->createAsset(
                            'Adyen_Payment::images/logos/' . $logoName . '.png'
                        );
926

927
                        $icon = null;
Rik ter Beek's avatar
Rik ter Beek committed
928
                        $placeholder = $this->_assetSource->findSource($asset);
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
                        if ($placeholder) {
                            list($width, $height) = getimagesize($asset->getSourceFile());
                            $icon = [
                                'url' => $asset->getUrl(),
                                'width' => $width,
                                'height' => $height
                            ];
                        }
                        $data['logo'] = $icon;
                    }

                    /**
                     * Check if there are installments for this creditcard type defined
                     */
                    $data['number_of_installments'] = 0;
                    $ccType = $this->getMagentoCreditCartType($agreementData['variant']);
                    $installments = null;
                    $installmentsValue = $this->getAdyenCcConfigData('installments');
                    if ($installmentsValue) {
                        $installments = unserialize($installmentsValue);
                    }

                    if ($installments) {
Alessio Zampatti's avatar
Alessio Zampatti committed
952
                        $numberOfInstallments = [];
953 954 955 956

                        foreach ($installments as $ccTypeInstallment => $installment) {
                            if ($ccTypeInstallment == $ccType) {
                                foreach ($installment as $amount => $installments) {
Alessio Zampatti's avatar
Alessio Zampatti committed
957 958
                                    if ($grandTotal >= $amount) {
                                        array_push($numberOfInstallments, $installments);
959 960 961 962 963
                                    }
                                }
                            }
                        }
                        if ($numberOfInstallments) {
Alessio Zampatti's avatar
Alessio Zampatti committed
964
                            sort($numberOfInstallments);
965 966 967 968 969 970 971 972 973 974
                            $data['number_of_installments'] = $numberOfInstallments;
                        }
                    }
                    $billingAgreements[] = $data;
                }
            }
        }
        return $billingAgreements;
    }

975 976
    public function isPerStoreBillingAgreement($storeId)
    {
977 978
        return !$this->getAdyenOneclickConfigDataFlag('share_billing_agreement', $storeId);
    }
979 980 981 982 983 984 985

    /**
     * @param $paymentMethod
     * @return bool
     */
    public function isPaymentMethodOpenInvoiceMethod($paymentMethod)
    {
986
        if (strpos($paymentMethod, 'afterpay') !== false) {
987
            return true;
988
        } elseif (strpos($paymentMethod, 'klarna') !== false) {
Rik ter Beek's avatar
Rik ter Beek committed
989
            return true;
990
        } elseif (strpos($paymentMethod, 'ratepay') !== false) {
991 992
            return true;
        }
Rik ter Beek's avatar
Rik ter Beek committed
993 994

        return false;
995 996
    }

997 998 999 1000 1001 1002 1003 1004 1005
    /**
     * @param $paymentMethod
     * @return bool
     */
    public function isPaymentMethodMolpayMethod($paymentMethod)
    {
        if (strpos($paymentMethod, 'molpay_') !== false) {
            return true;
        }
1006

1007 1008
        return false;
    }
1009

1010 1011 1012 1013 1014
    public function getRatePayId()
    {
        return $this->getAdyenHppConfigData("ratepay_id");
    }

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    /**
     * For Klarna And AfterPay use VatCategory High others use none
     *
     * @param $paymentMethod
     * @return bool
     */
    public function isVatCategoryHigh($paymentMethod)
    {
        if ($paymentMethod == "klarna" ||
            strlen($paymentMethod) >= 9 && substr($paymentMethod, 0, 9) == 'afterpay_'
        ) {
            return true;
        }
        return false;
    }
1030

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    /**
     * @return bool
     */
    public function showLogos()
    {
        $showLogos = $this->getAdyenAbstractConfigData('title_renderer');
        if ($showLogos == \Adyen\Payment\Model\Config\Source\RenderMode::MODE_TITLE_IMAGE) {
            return true;
        }
        return false;
    }

    /**
     * Create a file asset that's subject of fallback system
     *
     * @param string $fileId
     * @param array $params
     * @return \Magento\Framework\View\Asset\File
     */
    public function createAsset($fileId, array $params = [])
    {
        $params = array_merge(['_secure' => $this->_request->isSecure()], $params);
        return $this->_assetRepo->createAsset($fileId, $params);
    }

1056 1057
    public function getStoreLocale($storeId)
    {
1058 1059 1060 1061
        $path = \Magento\Directory\Helper\Data::XML_PATH_DEFAULT_LOCALE;
        return $this->scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
    }

Alessio Zampatti's avatar
Alessio Zampatti committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    public function getApplePayShippingTypes()
    {
        return [
            [
                'value' => 'shipping',
                'label' => __('Shipping Method')
            ],
            [
                'value' => 'delivery',
                'label' => __('Delivery Method')
            ],
            [
                'value' => 'storePickup',
                'label' => __('Store Pickup Method')
            ],
            [
                'value' => 'servicePickup',
                'label' => __('Service Pickup Method')
            ]
        ];
    }

1084 1085 1086 1087
    public function getUnprocessedNotifications()
    {
        $notifications = $this->_notificationFactory->create();
        $notifications->unprocessedNotificationsFilter();
1088
        return $notifications->getSize();
1089 1090
    }

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    /**
     * @param $formFields
     * @param $count
     * @param $name
     * @param $price
     * @param $currency
     * @param $taxAmount
     * @param $priceInclTax
     * @param $taxPercent
     * @param $numberOfItems
     * @param $payment
     * @return mixed
     */
    public function createOpenInvoiceLineItem(
        $formFields,
        $count,
        $name,
        $price,
        $currency,
        $taxAmount,
        $priceInclTax,
        $taxPercent,
        $numberOfItems,
        $payment
    ) {
        $description = str_replace("\n", '', trim($name));
        $itemAmount = $this->formatAmount($price, $currency);

1119 1120 1121 1122 1123 1124
        $itemVatAmount = $this->getItemVatAmount(
            $taxAmount,
            $priceInclTax,
            $price,
            $currency
        );
1125 1126 1127 1128

        // Calculate vat percentage
        $itemVatPercentage = $this->getMinorUnitTaxPercent($taxPercent);

1129 1130 1131 1132 1133
        return $this->getOpenInvoiceLineData(
            $formFields,
            $count,
            $currency,
            $description,
1134
            $itemAmount,
1135 1136 1137 1138 1139
            $itemVatAmount,
            $itemVatPercentage,
            $numberOfItems,
            $payment
        );
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    }

    /**
     * @param $formFields
     * @param $count
     * @param $order
     * @param $shippingAmount
     * @param $shippingTaxAmount
     * @param $currency
     * @param $payment
     * @return mixed
     */
    public function createOpenInvoiceLineShipping(
        $formFields,
        $count,
        $order,
        $shippingAmount,
        $shippingTaxAmount,
        $currency,
        $payment
    ) {
        $description = $order->getShippingDescription();
        $itemAmount = $this->formatAmount($shippingAmount, $currency);
        $itemVatAmount = $this->formatAmount($shippingTaxAmount, $currency);

        // Create RateRequest to calculate the Tax class rate for the shipping method
        $rateRequest = $this->_taxCalculation->getRateRequest(
            $order->getShippingAddress(),
            $order->getBillingAddress(),
            null,
            $order->getStoreId(),
            $order->getCustomerId()
        );

        $taxClassId = $this->_taxConfig->getShippingTaxClass($order->getStoreId());
        $rateRequest->setProductClassId($taxClassId);
        $rate = $this->_taxCalculation->getRate($rateRequest);

        $itemVatPercentage = $this->getMinorUnitTaxPercent($rate);
        $numberOfItems = 1;

1181 1182 1183 1184 1185
        return $this->getOpenInvoiceLineData(
            $formFields,
            $count,
            $currency,
            $description,
1186
            $itemAmount,
1187 1188 1189 1190 1191
            $itemVatAmount,
            $itemVatPercentage,
            $numberOfItems,
            $payment
        );
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    }

    /**
     * @param $taxAmount
     * @param $priceInclTax
     * @param $price
     * @param $currency
     * @return string
     */
    public function getItemVatAmount(
        $taxAmount,
        $priceInclTax,
        $price,
        $currency
    ) {
        if ($taxAmount > 0 && $priceInclTax > 0) {
            return $this->formatAmount($priceInclTax, $currency) - $this->formatAmount($price, $currency);
        }
        return $this->formatAmount($taxAmount, $currency);
    }

    /**
     * Set the openinvoice line
     *
     * @param $formFields
     * @param $count
     * @param $currencyCode
     * @param $description
     * @param $itemAmount
     * @param $itemVatAmount
     * @param $itemVatPercentage
     * @param $numberOfItems
     * @param $payment
     * @return
     */
    public function getOpenInvoiceLineData(
        $formFields,
        $count,
        $currencyCode,
        $description,
        $itemAmount,
        $itemVatAmount,
        $itemVatPercentage,
        $numberOfItems,
        $payment
    ) {
        $linename = "line" . $count;
        $formFields['openinvoicedata.' . $linename . '.currencyCode'] = $currencyCode;
        $formFields['openinvoicedata.' . $linename . '.description'] = $description;
        $formFields['openinvoicedata.' . $linename . '.itemAmount'] = $itemAmount;
        $formFields['openinvoicedata.' . $linename . '.itemVatAmount'] = $itemVatAmount;
        $formFields['openinvoicedata.' . $linename . '.itemVatPercentage'] = $itemVatPercentage;
        $formFields['openinvoicedata.' . $linename . '.numberOfItems'] = $numberOfItems;

        if ($this->isVatCategoryHigh($payment->getAdditionalInformation(
1247 1248
            \Adyen\Payment\Observer\AdyenHppDataAssignObserver::BRAND_CODE
        ))
1249 1250 1251 1252 1253 1254 1255
        ) {
            $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "High";
        } else {
            $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "None";
        }
        return $formFields;
    }
1256

stkams's avatar
stkams committed
1257
    /**
1258
     * @param int|null $storeId
stkams's avatar
stkams committed
1259 1260
     * @return string the X API Key for the specified or current store
     */
1261
    public function getPosApiKey($storeId = null)
1262
    {
stkams's avatar
stkams committed
1263
        if ($this->isDemoMode($storeId)) {
1264
            $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenPosCloudConfigData('api_key_test', $storeId)));
stkams's avatar
stkams committed
1265
        } else {
1266
            $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenPosCloudConfigData('api_key_live', $storeId)));
1267 1268 1269 1270
        }
        return $apiKey;
    }

1271 1272 1273 1274 1275 1276 1277
    /**
     * Return the Terminal ID for the current store/mode
     *
     * @param int|null $storeId
     * @return mixed
     */
    public function getPoiId($storeId = null)
1278
    {
1279
        return $this->getAdyenPosCloudConfigData('pos_terminal_id', $storeId);
1280 1281
    }

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    /**
     * Return the merchant account name configured for the proper payment method.
     * If it is not configured for the specific payment method,
     * return the merchant account name defined in required settings.
     *
     * @param $paymentMethod
     * @param int $storeId
     * @return string
     */
    public function getAdyenMerchantAccount($paymentMethod, $storeId)
1292 1293 1294 1295
    {
        $merchantAccount = $this->getAdyenAbstractConfigData("merchant_account", $storeId);
        $merchantAccountPos = $this->getAdyenPosCloudConfigData('pos_merchant_account', $storeId);

1296
        if ($paymentMethod == 'adyen_pos_cloud' && !empty($merchantAccountPos)) {
1297 1298 1299 1300 1301
            return $merchantAccountPos;
        }
        return $merchantAccount;
    }

1302 1303 1304 1305 1306 1307 1308
    /**
     * Format the Receipt sent in the Terminal API response in HTML
     * so that it can be easily shown to the shopper
     *
     * @param $paymentReceipt
     * @return string
     */
1309 1310
    public function formatTerminalAPIReceipt($paymentReceipt)
    {
1311
        $formattedHtml = "<table class='terminal-api-receipt'>";
1312
        foreach ($paymentReceipt as $receipt) {
1313 1314 1315 1316
            if ($receipt['DocumentQualifier'] == "CustomerReceipt") {
                foreach ($receipt['OutputContent']['OutputText'] as $item) {
                    parse_str($item['Text'], $textParts);
                    $formattedHtml .= "<tr class='terminal-api-receipt'>";
1317
                    if (!empty($textParts['name'])) {
1318
                        $formattedHtml .= "<td class='terminal-api-receipt-name'>" . $textParts['name'] . "</td>";
1319
                    } else {
1320
                        $formattedHtml .= "<td class='terminal-api-receipt-name'>&nbsp;</td>";
1321 1322
                    }
                    if (!empty($textParts['value'])) {
1323
                        $formattedHtml .= "<td class='terminal-api-receipt-value' align='right'>" . $textParts['value'] . "</td>";
1324
                    } else {
1325
                        $formattedHtml .= "<td class='terminal-api-receipt-value' align='right'>&nbsp;</td>";
1326
                    }
1327
                    $formattedHtml .= "</tr>";
1328 1329 1330
                }
            }
        }
1331 1332
        $formattedHtml .= "</table>";
        return $formattedHtml;
1333 1334
    }

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    /**
     * Initializes and returns Adyen Client and sets the required parameters of it
     *
     * @param int|null $storeId
     * @param string|null $apiKey
     * @return \Adyen\Client
     * @throws \Adyen\AdyenException
     */
    public function initializeAdyenClient($storeId = null, $apiKey = null)
    {
        // initialize client
cyattilakiss's avatar
cyattilakiss committed
1346
        if ($storeId === null) {
alessio's avatar
alessio committed
1347 1348 1349
            $storeId = $this->storeManager->getStore()->getId();
        }

1350 1351 1352
        if (empty($apiKey)) {
            $apiKey = $this->getAPIKey($storeId);
        }
1353

1354
        $client = $this->createAdyenClient();
Rik ter Beek's avatar
Rik ter Beek committed
1355
        $client->setApplicationName("Magento 2 plugin");
1356
        $client->setXApiKey($apiKey);
1357

Rik ter Beek's avatar
Rik ter Beek committed
1358
        $client->setAdyenPaymentSource($this->getModuleName(), $this->getModuleVersion());
1359

Rik ter Beek's avatar
Rik ter Beek committed
1360
        $client->setExternalPlatform($this->productMetadata->getName(), $this->productMetadata->getVersion());
1361

Rik ter Beek's avatar
Rik ter Beek committed
1362 1363 1364
        if ($this->isDemoMode($storeId)) {
            $client->setEnvironment(\Adyen\Environment::TEST);
        } else {
1365
            $client->setEnvironment(\Adyen\Environment::LIVE, $this->getLiveEndpointPrefix($storeId));
Rik ter Beek's avatar
Rik ter Beek committed
1366
        }
1367

Rik ter Beek's avatar
Rik ter Beek committed
1368
        $client->setLogger($this->adyenLogger);
1369 1370 1371 1372 1373

        return $client;
    }

    /**
1374
     * @param \Adyen\Client $client
1375 1376 1377 1378 1379 1380 1381
     * @return \Adyen\Service\PosPayment
     * @throws \Adyen\AdyenException
     */
    public function createAdyenPosPaymentService($client)
    {
        return new \Adyen\Service\PosPayment($client);
    }
1382

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    /**
     * @return \Adyen\Client
     * @throws \Adyen\AdyenException
     */
    private function createAdyenClient()
    {
        return new \Adyen\Client();
    }

    /**
     * Retrieve origin keys for platform's base url
     *
     * @return string
     * @throws \Adyen\AdyenException
     */
    public function getOriginKeyForBaseUrl()
    {
        $baseUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
        $parsed = parse_url($baseUrl);
        $domain = $parsed['scheme'] . "://" . $parsed['host'];
1403 1404
        $storeId = $this->storeManager->getStore()->getId();
        $cacheKey = 'Adyen_origin_key_for_' . $domain . '_' . $storeId;
1405

1406
        if (!$originKey = $this->cache->load($cacheKey)) {
1407
            if ($originKey = $this->getOriginKeyForUrl($domain, $storeId)) {
1408
                $this->cache->save($originKey, $cacheKey, array(), 60 * 60 * 24);
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
            }
        }

        return $originKey;
    }

    /**
     * Get origin key for a specific url using the adyen api library client
     *
     * @param $url
     * @param int|null $storeId
     * @return string
     * @throws \Adyen\AdyenException
     */
    private function getOriginKeyForUrl($url, $storeId = null)
    {
        $params = array(
            "originDomains" => array(
                $url
            )
        );

        $client = $this->initializeAdyenClient($storeId);
1432

1433
        try {
1434
            $service = $this->createAdyenCheckoutUtilityService($client);
1435
            $response = $service->originKeys($params);
1436
        } catch (\Exception $e) {
1437 1438
            $this->adyenLogger->error($e->getMessage());
        }
1439

1440
        $originKey = "";
attilak's avatar
attilak committed
1441 1442 1443

        if (!empty($response['originKeys'][$url])) {
            $originKey = $response['originKeys'][$url];
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
        }

        return $originKey;
    }

    /**
     * @param int|null $storeId
     * @return string
     */
    public function getCheckoutContextUrl($storeId = null)
    {
        if ($this->isDemoMode($storeId)) {
            return self::CHECKOUT_CONTEXT_URL_TEST;
        }

        return self::CHECKOUT_CONTEXT_URL_LIVE;
    }

    /**
1463
     * @param \Adyen\Client $client
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
     * @return \Adyen\Service\CheckoutUtility
     * @throws \Adyen\AdyenException
     */
    private function createAdyenCheckoutUtilityService($client)
    {
        return new \Adyen\Service\CheckoutUtility($client);
    }

    /**
     * @param int|null $storeId
     * @return string
     */
    public function getCheckoutCardComponentJs($storeId = null)
    {
        if ($this->isDemoMode($storeId)) {
            return self::CHECKOUT_COMPONENT_JS_TEST;
        }

        return self::CHECKOUT_COMPONENT_JS_LIVE;
    }

1485 1486 1487 1488
    /**
     * @param $order
     * @param $additionalData
     */
1489 1490 1491 1492 1493 1494
    public function createAdyenBillingAgreement($order, $additionalData)
    {
        if (!empty($additionalData['recurring.recurringDetailReference'])) {
            $listRecurringContracts = null;
            try {
                // Get or create billing agreement
1495
                /** @var \Adyen\Payment\Model\Billing\Agreement $billingAgreement */
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
                $billingAgreement = $this->billingAgreementFactory->create();
                $billingAgreement->load($additionalData['recurring.recurringDetailReference'], 'reference_id');

                // check if BA exists
                if (!($billingAgreement && $billingAgreement->getAgreementId() > 0 && $billingAgreement->isValid())) {
                    // create new BA
                    $this->adyenLogger->addAdyenDebug("Creating new Billing Agreement");
                    $billingAgreement = $this->billingAgreementFactory->create();
                    $billingAgreement->setStoreId($order->getStoreId());
                    $billingAgreement->importOrderPayment($order->getPayment());
1506 1507 1508
                    if ($billingAgreement->getCustomerId() === null) {
                        $billingAgreement->setCustomerId($this->getCustomerId($order));
                    }
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
                    $message = __('Created billing agreement #%1.',
                        $additionalData['recurring.recurringDetailReference']);
                } else {

                    $billingAgreement->setIsObjectChanged(true);
                    $message = __('Updated billing agreement #%1.',
                        $additionalData['recurring.recurringDetailReference']);
                }

                // Populate billing agreement data
1519 1520
                $storeOneClick = $order->getPayment()->getAdditionalInformation('store_cc');
                $billingAgreement->setCcBillingAgreement($additionalData, $storeOneClick);
1521 1522
                if ($billingAgreement->isValid()) {

1523 1524 1525 1526 1527 1528
                    if (!$this->agreementResourceModel->getOrderRelation($billingAgreement->getAgreementId(),
                        $order->getId())) {

                        // save into sales_billing_agreement_order
                        $billingAgreement->addOrderRelation($order);
                    }
1529 1530 1531
                    // add to order to save agreement
                    $order->addRelatedObject($billingAgreement);
                } else {
1532 1533
                    $message = __('Failed to create billing agreement for this order. Reason(s): ') . join(', ',
                            $billingAgreement->getErrors());
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
                    throw new \Exception($message);
                }

            } catch (\Exception $exception) {
                $message = $exception->getMessage();
                $this->adyenLogger->error("exception: " . $message);
            }

            $comment = $order->addStatusHistoryComment($message);

            $order->addRelatedObject($comment);
        }
    }

1548 1549 1550 1551 1552
    /**
     * Method can be used by interceptors to provide the customer ID in a different way.
     * @param \Magento\Sales\Model\Order $order
     * @return int|null
     */
1553 1554
    public function getCustomerId(\Magento\Sales\Model\Order $order)
    {
1555 1556 1557
        return $order->getCustomerId();
    }

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
    /**
     * For backwards compatibility get the recurringType used for HPP + current billing agreements
     *
     * @param null $storeId
     * @return null|string
     */
    public function getRecurringTypeFromOneclickRecurringSetting($storeId = null)
    {
        $enableOneclick = $this->getAdyenAbstractConfigData('enable_oneclick', $storeId);
        $enableRecurring = $this->getAdyenAbstractConfigData('enable_recurring', $storeId);

        if ($enableOneclick && $enableRecurring) {
            return \Adyen\Payment\Model\RecurringType::ONECLICK_RECURRING;
        } elseif ($enableOneclick && !$enableRecurring) {
            return \Adyen\Payment\Model\RecurringType::ONECLICK;
        } elseif (!$enableOneclick && $enableRecurring) {
            return \Adyen\Payment\Model\RecurringType::RECURRING;
        } else {
            return \Adyen\Payment\Model\RecurringType::NONE;
        }
    }
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599

    /**
     * Get icon from variant
     *
     * @param $variant
     * @return array
     */
    public function getVariantIcon($variant)
    {
        $asset = $this->createAsset(sprintf("Adyen_Payment::images/logos/%s_small.png", $variant));
        list($width, $height) = getimagesize($asset->getSourceFile());
        $icon = [
            'url' => $asset->getUrl(),
            'width' => $width,
            'height' => $height
        ];
        return $icon;
    }


    /**
attilak's avatar
attilak committed
1600 1601
     * Check if CreditCard vault is enabled
     *
1602 1603 1604 1605 1606 1607 1608 1609
     * @param int|null $storeId
     * @return mixed
     */
    public function isCreditCardVaultEnabled($storeId = null)
    {
        return $this->getAdyenCcVaultConfigDataFlag('active', $storeId);
    }

1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
    /**
     * Checks if the house number needs to be sent to the Adyen API separately or as it is in the street field
     *
     * @param $country
     * @return bool
     */
    public function isSeparateHouseNumberRequired($country)
    {
        $countryList = ["nl", "de", "se", "no", "at", "fi", "dk"];

        return in_array(strtolower($country), $countryList);
    }
1622
}