We will work on Apr 26th (Saturday) and will be off from Apr 30th (Wednesday) until May 2nd (Friday) for public holiday in our country

Data.php 38 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 36
    const TEST = 'test';
    const LIVE = 'live';

37 38 39
    /**
     * @var \Magento\Framework\Encryption\EncryptorInterface
     */
40 41
    protected $_encryptor;

42 43 44 45
    /**
     * @var \Magento\Framework\Config\DataInterface
     */
    protected $_dataStorage;
46

rikterbeek's avatar
#40  
rikterbeek committed
47 48 49 50 51
    /**
     * @var \Magento\Directory\Model\Config\Source\Country
     */
    protected $_country;

rikterbeek's avatar
rikterbeek committed
52 53 54 55 56
    /**
     * @var \Magento\Framework\Module\ModuleListInterface
     */
    protected $_moduleList;

57
    /**
58
     * @var \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory
59 60 61 62 63 64 65 66 67 68 69 70 71
     */
    protected $_billingAgreementCollectionFactory;

    /**
     * @var Repository
     */
    protected $_assetRepo;

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

72 73 74 75 76
    /**
     * @var \Adyen\Payment\Model\ResourceModel\Notification\CollectionFactory
     */
    protected $_notificationFactory;

77 78 79 80 81 82 83 84 85 86
    /**
     * @var \Magento\Tax\Model\Config
     */
    protected $_taxConfig;

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

87 88 89 90 91 92 93 94 95 96
	/**
	 * @var \Magento\Framework\App\ProductMetadataInterface
	 */
    protected $productMetadata;

	/**
	 * @var \Adyen\Payment\Logger\AdyenLogger
	 */
    protected $adyenLogger;

97
    /**
98
     * Data constructor.
99
     *
100 101 102
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
     * @param \Magento\Framework\Config\DataInterface $dataStorage
103 104
     * @param \Magento\Directory\Model\Config\Source\Country $country
     * @param \Magento\Framework\Module\ModuleListInterface $moduleList
105
     * @param \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
106 107
     * @param \Magento\Framework\View\Asset\Repository $assetRepo
     * @param \Magento\Framework\View\Asset\Source $assetSource
108 109
	 * @param \Magento\Framework\App\ProductMetadataInterface $productMetadata
	 * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
110 111 112
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
113
        \Magento\Framework\Encryption\EncryptorInterface $encryptor,
rikterbeek's avatar
#40  
rikterbeek committed
114
        \Magento\Framework\Config\DataInterface $dataStorage,
rikterbeek's avatar
rikterbeek committed
115
        \Magento\Directory\Model\Config\Source\Country $country,
116
        \Magento\Framework\Module\ModuleListInterface $moduleList,
117
        \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory,
118
        \Magento\Framework\View\Asset\Repository $assetRepo,
119
        \Magento\Framework\View\Asset\Source $assetSource,
120 121
        \Adyen\Payment\Model\ResourceModel\Notification\CollectionFactory $notificationFactory,
        \Magento\Tax\Model\Config $taxConfig,
122 123 124 125
        \Magento\Tax\Model\Calculation $taxCalculation,
		\Magento\Framework\App\ProductMetadataInterface $productMetadata,
		\Adyen\Payment\Logger\AdyenLogger $adyenLogger

126
    ) {
127
        parent::__construct($context);
128
        $this->_encryptor = $encryptor;
129
        $this->_dataStorage = $dataStorage;
rikterbeek's avatar
#40  
rikterbeek committed
130
        $this->_country = $country;
rikterbeek's avatar
rikterbeek committed
131
        $this->_moduleList = $moduleList;
132 133 134
        $this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
        $this->_assetRepo = $assetRepo;
        $this->_assetSource = $assetSource;
135
        $this->_notificationFactory = $notificationFactory;
136 137
        $this->_taxConfig = $taxConfig;
        $this->_taxCalculation = $taxCalculation;
138 139
        $this->productMetadata = $productMetadata;
        $this->adyenLogger = $adyenLogger;
140 141
    }

142 143 144 145
    /**
     * @desc return recurring types for configuration setting
     * @return array
     */
146 147
    public function getRecurringTypes()
    {
rikterbeek's avatar
rikterbeek committed
148 149 150 151 152 153 154
        return [
            \Adyen\Payment\Model\RecurringType::ONECLICK => 'ONECLICK',
            \Adyen\Payment\Model\RecurringType::ONECLICK_RECURRING => 'ONECLICK,RECURRING',
            \Adyen\Payment\Model\RecurringType::RECURRING => 'RECURRING'
        ];
    }

155 156 157 158
    /**
     * @desc return recurring types for configuration setting
     * @return array
     */
159 160
    public function getModes()
    {
161 162 163 164 165 166
        return [
            '1' => 'Test Mode',
            '0' => 'Production Mode'
        ];
    }

167 168 169 170
    /**
     * @desc return recurring types for configuration setting
     * @return array
     */
171 172
    public function getCaptureModes()
    {
173 174 175 176 177 178
        return [
            'auto' => 'immediate',
            'manual' => 'manual'
        ];
    }

179 180 181 182
    /**
     * @desc return recurring types for configuration setting
     * @return array
     */
183 184
    public function getPaymentRoutines()
    {
185 186 187 188 189 190
        return [
            'single' => 'Single Page Payment Routine',
            'multi' => 'Multi-page Payment Routine'
        ];
    }

191

192 193 194 195 196 197 198 199
    /**
     * Return the formatted currency. Adyen accepts the currency in multiple formats.
     * @param $amount
     * @param $currency
     * @return string
     */
    public function formatAmount($amount, $currency)
    {
200
        switch ($currency) {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
            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;
        }

236 237 238 239 240 241 242 243 244 245 246 247 248
        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;
249 250
    }

251 252 253 254 255
    /**
     * @param $amount
     * @param $currency
     * @return float
     */
256 257 258
    public function originalAmount($amount, $currency)
    {
        // check the format
259
        switch ($currency) {
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            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);
    }

298 299 300 301 302 303 304
    /**
     * Street format
     * @param type $address
     * @return array
     */
    public function getStreet($address)
    {
305 306 307 308
        if (empty($address)) {
            return false;
        }

309 310 311
        $street = self::formatStreet($address->getStreet());
        $streetName = $street['0'];
        unset($street['0']);
312
        $streetNr = implode(' ', $street);
rikterbeek's avatar
rikterbeek committed
313
        return (['name' => trim($streetName), 'house_number' => $streetNr]);
314 315 316 317 318 319 320 321 322 323 324 325 326 327
    }

    /**
     * Fix this one string street + number
     * @example street + number
     * @param type $street
     * @return type $street
     */
    static public function formatStreet($street)
    {
        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);
328
        if (!empty($houseNumber['0'])) {
329 330
            $_houseNumber = trim($houseNumber['0']['0']);
            $position = $houseNumber['0']['1'];
331 332
            $streetName = trim(substr($street['0'], 0, $position));
            $street = [$streetName, $_houseNumber];
333 334 335 336 337
        }
        return $street;
    }


338 339 340 341 342 343
    /**
     * @desc gives back global configuration values
     * @param $field
     * @param null $storeId
     * @return mixed
     */
344 345 346 347 348
    public function getAdyenAbstractConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_abstract', $storeId);
    }

349 350 351 352 353 354
    /**
     * @desc gives back global configuration values as boolean
     * @param $field
     * @param null $storeId
     * @return mixed
     */
355 356 357 358 359
    public function getAdyenAbstractConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_abstract', $storeId, true);
    }

360 361 362 363 364 365
    /**
     * @desc Gives back adyen_cc configuration values
     * @param $field
     * @param null $storeId
     * @return mixed
     */
366 367 368 369 370
    public function getAdyenCcConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_cc', $storeId);
    }

371 372 373 374 375 376
    /**
     * @desc Gives back adyen_cc configuration values as flag
     * @param $field
     * @param null $storeId
     * @return mixed
     */
377 378 379 380 381
    public function getAdyenCcConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_cc', $storeId, true);
    }

382 383 384 385 386 387
    /**
     * @desc Gives back adyen_hpp configuration values
     * @param $field
     * @param null $storeId
     * @return mixed
     */
388 389 390 391 392
    public function getAdyenHppConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_hpp', $storeId);
    }

393 394 395 396 397 398
    /**
     * @desc Gives back adyen_hpp configuration values as flag
     * @param $field
     * @param null $storeId
     * @return mixed
     */
399 400 401 402 403
    public function getAdyenHppConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_hpp', $storeId, true);
    }

404
    /**
rikterbeek's avatar
rikterbeek committed
405
     * @desc Gives back adyen_oneclick configuration values
406 407 408 409 410 411 412 413 414 415
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenOneclickConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_oneclick', $storeId);
    }

    /**
rikterbeek's avatar
rikterbeek committed
416
     * @desc Gives back adyen_oneclick configuration values as flag
417 418 419 420 421 422 423 424 425
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenOneclickConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_oneclick', $storeId, true);
    }

rikterbeek's avatar
rikterbeek committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    /**
     * @desc Gives back adyen_pos configuration values
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenPosConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pos', $storeId);
    }

    /**
     * @desc Gives back adyen_pos configuration values as flag
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenPosConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pos', $storeId, true);
    }

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    /**
     * @param $field
     * @param null $storeId
     * @return bool|mixed
     */
    public function getAdyenPosCloudConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pos_cloud', $storeId);
    }

    /**
     * @param $field
     * @param null $storeId
     * @return bool|mixed
     */
    public function getAdyenPosCloudConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pos_cloud', $storeId, true);
    }

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    /**
     * @desc Gives back adyen_pay_by_mail configuration values
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenPayByMailConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pay_by_mail', $storeId);
    }

    /**
     * @desc Gives back adyen_pay_by_mail configuration values as flag
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenPayByMailConfigDataFlag($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_pay_by_mail', $storeId, true);
    }

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    /**
     * @desc Gives back adyen_boleto configuration values
     * @param $field
     * @param null $storeId
     * @return mixed
     */
    public function getAdyenBoletoConfigData($field, $storeId = null)
    {
        return $this->getConfigData($field, 'adyen_boleto', $storeId);
    }

    /**
     * @desc Gives back adyen_boleto configuration values as flag
     * @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
512 513 514 515 516 517 518 519 520 521
    /**
     * @desc Gives back adyen_apple_pay configuration values
     * @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
522

Alessio Zampatti's avatar
Alessio Zampatti committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    /**
     * @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);
        }
    }

551 552 553 554
    /**
     * @desc Retrieve decrypted hmac key
     * @return string
     */
555 556 557 558
    public function getHmac()
    {
        switch ($this->isDemoMode()) {
            case true:
559
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenHppConfigData('hmac_test')));
560 561 562
                break;
            default:
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenHppConfigData('hmac_live')));
563 564 565 566 567 568 569 570 571
                break;
        }
        return $secretWord;
    }

    public function getHmacPayByMail()
    {
        switch ($this->isDemoMode()) {
            case true:
572
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenPayByMailConfigData('hmac_test')));
573 574 575
                break;
            default:
                $secretWord = $this->_encryptor->decrypt(trim($this->getAdyenPayByMailConfigData('hmac_live')));
576 577 578 579 580
                break;
        }
        return $secretWord;
    }

581 582 583 584
    /**
     * @desc Check if configuration is set to demo mode
     * @return mixed
     */
585
    public function isDemoMode($storeId = null)
586
    {
587
        return $this->getAdyenAbstractConfigDataFlag('demo_mode', $storeId);
588 589
    }

590 591 592 593
    /**
     * @desc Retrieve the decrypted notification password
     * @return string
     */
594 595 596 597 598
    public function getNotificationPassword()
    {
        return $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('notification_password')));
    }

599 600 601 602
    /**
     * @desc Retrieve the webserver username
     * @return string
     */
603
    public function getWsUsername($storeId = null)
604
    {
605
        if ($this->isDemoMode($storeId)) {
606
            $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_test', $storeId));
607
        } else {
608
            $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_live', $storeId));
609 610 611 612 613 614 615 616
        }
        return $wsUsername;
    }

    /**
     * @desc Retrieve the webserver password
     * @return string
     */
617
    public function getWsPassword($storeId = null)
618
    {
619
        if ($this->isDemoMode($storeId)) {
620 621
            $wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_test',
                $storeId)));
622
        } else {
623 624
            $wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_live',
                $storeId)));
625 626 627 628 629 630 631 632
        }
        return $wsPassword;
    }

    /**
     * @desc Cancels the order
     * @param $order
     */
633 634 635 636 637 638 639 640 641 642 643 644
    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:
645
                if ($order->canCancel()) {
646 647 648 649 650 651
                    $order->cancel()->save();
                }
                break;
        }
    }

652 653 654 655 656 657 658 659 660 661
    /**
     * 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();

662
        if (isset($ccTypesMapper[$ccType])) {
663 664 665 666 667 668
            $ccType = $ccTypesMapper[$ccType]['code'];
        }

        return $ccType;
    }

669 670 671
    /**
     * @return array
     */
672 673
    public function getCcTypesAltData()
    {
674
        $adyenCcTypes = $this->getAdyenCcTypes();
675
        $types = [];
676 677
        foreach ($adyenCcTypes as $key => $data) {
            $types[$data['code_alt']] = $data;
678
            $types[$data['code_alt']]['code'] = $key;
679 680 681 682
        }
        return $types;
    }

683 684 685
    /**
     * @return mixed
     */
686 687 688 689 690
    public function getAdyenCcTypes()
    {
        return $this->_dataStorage->get('adyen_credit_cards');
    }

691
    /**
692 693 694 695 696 697
     * @desc Retrieve information from payment configuration
     * @param $field
     * @param $paymentMethodCode
     * @param $storeId
     * @param bool|false $flag
     * @return bool|mixed
698 699 700 701 702
     */
    public function getConfigData($field, $paymentMethodCode, $storeId, $flag = false)
    {
        $path = 'payment/' . $paymentMethodCode . '/' . $field;

703
        if (!$flag) {
704
            return $this->scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
705
        } else {
706
            return $this->scopeConfig->isSetFlag($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
707 708
        }
    }
rikterbeek's avatar
#40  
rikterbeek committed
709 710 711 712 713 714 715 716


    /**
     * @return array
     */
    public function getSepaCountries()
    {
        $sepaCountriesAllowed = [
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
            "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
755 756 757 758 759 760 761 762 763 764 765 766 767
        ];

        $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
768

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
	/**
	 * 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
784 785
    public function getModuleVersion()
    {
786
        return (string)$this->_moduleList->getOne("Adyen_Payment")['setup_version'];
rikterbeek's avatar
rikterbeek committed
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

    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'),
            ],
        ];
    }
814 815 816 817 818 819 820 821 822 823 824 825 826 827

    /**
     * @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);
828
        $baCollection->addFieldToFilter('store_id', $storeId);
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
        $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';
                    }

852 853
                    $data = [
                        'reference_id' => $billingAgreement->getReferenceId(),
854 855 856 857 858 859 860 861 862 863
                        'agreement_label' => $billingAgreement->getAgreementLabel(),
                        'agreement_data' => $agreementData
                    ];

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

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

865
                        $icon = null;
Rik ter Beek's avatar
Rik ter Beek committed
866
                        $placeholder = $this->_assetSource->findSource($asset);
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
                        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
890
                        $numberOfInstallments = [];
891 892 893 894

                        foreach ($installments as $ccTypeInstallment => $installment) {
                            if ($ccTypeInstallment == $ccType) {
                                foreach ($installment as $amount => $installments) {
Alessio Zampatti's avatar
Alessio Zampatti committed
895 896
                                    if ($grandTotal >= $amount) {
                                        array_push($numberOfInstallments, $installments);
897 898 899 900 901
                                    }
                                }
                            }
                        }
                        if ($numberOfInstallments) {
Alessio Zampatti's avatar
Alessio Zampatti committed
902
                            sort($numberOfInstallments);
903 904 905 906 907 908 909 910 911 912
                            $data['number_of_installments'] = $numberOfInstallments;
                        }
                    }
                    $billingAgreements[] = $data;
                }
            }
        }
        return $billingAgreements;
    }

913 914 915 916 917 918 919

    /**
     * @param $paymentMethod
     * @return bool
     */
    public function isPaymentMethodOpenInvoiceMethod($paymentMethod)
    {
920
        if (strpos($paymentMethod, 'afterpay') !== false) {
921
            return true;
922
        } elseif (strpos($paymentMethod, 'klarna') !== false) {
Rik ter Beek's avatar
Rik ter Beek committed
923
            return true;
924
        } elseif (strpos($paymentMethod, 'ratepay') !== false) {
925 926
            return true;
        }
Rik ter Beek's avatar
Rik ter Beek committed
927 928

        return false;
929 930
    }

931 932 933 934 935
    public function getRatePayId()
    {
        return $this->getAdyenHppConfigData("ratepay_id");
    }

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
    /**
     * 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;
    }
951

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    /**
     * @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);
    }

977 978
    public function getStoreLocale($storeId)
    {
979 980 981 982
        $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
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    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')
            ]
        ];
    }

1005 1006 1007 1008
    public function getUnprocessedNotifications()
    {
        $notifications = $this->_notificationFactory->create();
        $notifications->unprocessedNotificationsFilter();
Alessio Zampatti's avatar
Alessio Zampatti committed
1009
        return $notifications->getSize();;
1010 1011
    }

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    /**
     * @param $storeId
     * @return mixed
     */
    public function getLibraryToken($storeId = null)
    {
        if ($this->isDemoMode($storeId)) {
            $libraryToken = $this->getAdyenCcConfigData('cse_library_token_test', $storeId);
        } else {
            $libraryToken = $this->getAdyenCcConfigData('cse_library_token_live', $storeId);
        }
        return $libraryToken;
    }

    /**
     * Returns the hosted location of the client side encryption file
     *
     * @param null $storeId
     * @return string
     */
    public function getLibrarySource($storeId = null)
    {
        $environment = self::LIVE;
        if ($this->isDemoMode($storeId)) {
            $environment = self::TEST;
        }

        return "https://" . $environment . ".adyen.com/hpp/cse/js/" . $this->getLibraryToken($storeId) . ".shtml";
    }
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 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 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 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 1181 1182 1183 1184 1185

    /**
     * @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);

        $itemVatAmount = $this->getItemVatAmount($taxAmount,
            $priceInclTax, $price, $currency);

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

        return $this->getOpenInvoiceLineData($formFields, $count, $currency, $description,
            $itemAmount,
            $itemVatAmount, $itemVatPercentage, $numberOfItems, $payment);
    }

    /**
     * @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;

        return $this->getOpenInvoiceLineData($formFields, $count, $currency, $description,
            $itemAmount,
            $itemVatAmount, $itemVatPercentage, $numberOfItems, $payment);
    }

    /**
     * @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(
            \Adyen\Payment\Observer\AdyenHppDataAssignObserver::BRAND_CODE))
        ) {
            $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "High";
        } else {
            $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "None";
        }
        return $formFields;
    }
1186

stkams's avatar
stkams committed
1187 1188 1189 1190
    /**
     * @param integer|null $storeId
     * @return string the X API Key for the specified or current store
     */
1191
    public function getPosApiKey($storeId = null)
1192
    {
stkams's avatar
stkams committed
1193
        if ($this->isDemoMode($storeId)) {
1194
            $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenPosCloudConfigData('api_key_test', $storeId)));
stkams's avatar
stkams committed
1195
        } else {
1196
            $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenPosCloudConfigData('api_key_live', $storeId)));
1197 1198 1199 1200
        }
        return $apiKey;
    }

1201 1202 1203 1204 1205 1206 1207
    /**
     * Return the Terminal ID for the current store/mode
     *
     * @param int|null $storeId
     * @return mixed
     */
    public function getPoiId($storeId = null)
1208
    {
1209
        $poiId = $this->getAdyenPosCloudConfigData('pos_terminal_id', $storeId);
1210 1211 1212
        return $poiId;
    }

1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    /**
     * 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)
1223 1224 1225 1226
    {
        $merchantAccount = $this->getAdyenAbstractConfigData("merchant_account", $storeId);
        $merchantAccountPos = $this->getAdyenPosCloudConfigData('pos_merchant_account', $storeId);

1227
        if ($paymentMethod == 'adyen_pos_cloud' && !empty($merchantAccountPos)) {
1228 1229 1230 1231 1232
            return $merchantAccountPos;
        }
        return $merchantAccount;
    }

1233 1234 1235 1236 1237 1238 1239
    /**
     * 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
     */
1240 1241
    public function formatTerminalAPIReceipt($paymentReceipt)
    {
1242
        $formattedHtml = "<table class='terminal-api-receipt'>";
1243
        foreach ($paymentReceipt as $receipt) {
1244 1245 1246 1247
            if ($receipt['DocumentQualifier'] == "CustomerReceipt") {
                foreach ($receipt['OutputContent']['OutputText'] as $item) {
                    parse_str($item['Text'], $textParts);
                    $formattedHtml .= "<tr class='terminal-api-receipt'>";
1248
                    if (!empty($textParts['name'])) {
1249
                        $formattedHtml .= "<td class='terminal-api-receipt-name'>" . $textParts['name'] . "</td>";
1250
                    } else {
1251
                        $formattedHtml .= "<td class='terminal-api-receipt-name'>&nbsp;</td>";
1252 1253
                    }
                    if (!empty($textParts['value'])) {
1254
                        $formattedHtml .= "<td class='terminal-api-receipt-value' align='right'>" . $textParts['value'] . "</td>";
1255
                    } else {
1256
                        $formattedHtml .= "<td class='terminal-api-receipt-value' align='right'>&nbsp;</td>";
1257
                    }
1258
                    $formattedHtml .= "</tr>";
1259 1260 1261
                }
            }
        }
1262 1263
        $formattedHtml .= "</table>";
        return $formattedHtml;
1264 1265
    }

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
	/**
	 * Initializes and returns Adyen Client and sets the required parameters of it
	 *
	 * @param $storeId
	 * @return \Adyen\Client
	 * @throws \Adyen\AdyenException
	 */
    public function initializeAdyenClient($storeId = null)
	{
		// initialize client
attilak's avatar
attilak committed
1276 1277
		$webserviceUsername = $this->getWsUsername($storeId);
		$webservicePassword = $this->getWsPassword($storeId);
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

		$client = new \Adyen\Client();
		$client->setApplicationName("Magento 2 plugin");
		$client->setUsername($webserviceUsername);
		$client->setPassword($webservicePassword);

		$client->setAdyenPaymentSource($this->getModuleName(), $this->getModuleVersion());

		$client->setExternalPlatform($this->productMetadata->getName(), $this->productMetadata->getVersion());

		if ($this->isDemoMode($storeId)) {
			$client->setEnvironment(\Adyen\Environment::TEST);
		} else {
			$client->setEnvironment(\Adyen\Environment::LIVE);
		}

		$client->setLogger($this->adyenLogger);

		return $client;
	}
}