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

Redirect.php 21.3 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/**
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * 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
24
namespace Adyen\Payment\Block\Redirect;
25 26 27 28 29 30

use Symfony\Component\Config\Definition\Exception\Exception;

class Redirect extends \Magento\Payment\Block\Form
{

31 32 33
    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
34
    protected $_orderFactory;
35

36 37 38 39 40
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

41
    /**
42
     * @var  \Magento\Sales\Model\Order
43
     */
44 45
    protected $_order;

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    /**
     * @var \Adyen\Payment\Helper\Data
     */
    protected $_adyenHelper;

    /**
     * @var ResolverInterface
     */
    protected $_resolver;

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

61 62 63 64 65 66 67
    /**
     * @var \Magento\Tax\Model\Config
     */
    protected $_taxConfig;

    protected $_taxCalculation;

68
    /**
69 70
     * Redirect constructor.
     *
71
     * @param \Magento\Framework\View\Element\Template\Context $context
72
     * @param array $data
73 74
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Checkout\Model\Session $checkoutSession
75
     * @param \Adyen\Payment\Helper\Data $adyenHelper
76 77 78 79 80
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = [],
        \Magento\Sales\Model\OrderFactory $orderFactory,
81 82 83
        \Magento\Checkout\Model\Session $checkoutSession,
        \Adyen\Payment\Helper\Data $adyenHelper,
        \Magento\Framework\Locale\ResolverInterface $resolver,
84 85 86
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
        \Magento\Tax\Model\Config $taxConfig,
        \Magento\Tax\Model\Calculation $taxCalculation
87
    ) {
88 89 90
        $this->_orderFactory = $orderFactory;
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
91 92 93 94 95 96 97 98 99

        $this->_adyenHelper = $adyenHelper;
        $this->_resolver = $resolver;
        $this->_adyenLogger = $adyenLogger;

        if (!$this->_order) {
            $incrementId = $this->_getCheckout()->getLastRealOrderId();
            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
        }
100 101
        $this->_taxConfig = $taxConfig;
        $this->_taxCalculation = $taxCalculation;
102 103 104
    }


105 106 107
    /**
     * @return $this
     */
108 109 110 111 112
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

113 114 115
    /**
     * @return string
     */
116 117
    public function getFormUrl()
    {
118
        $url = "";
119
        try {
120 121 122 123 124 125 126 127
            if ($this->_order->getPayment()) {
                $paymentRoutine = $this->_adyenHelper->getAdyenHppConfigData('payment_routine');

                switch ($this->_adyenHelper->isDemoMode()) {
                    case true:
                        if ($paymentRoutine == 'single' && $this->getPaymentMethodSelectionOnAdyen()) {
                            $url = 'https://test.adyen.com/hpp/pay.shtml';
                        } else {
128
                            if ($this->getPaymentMethodSelectionOnAdyen()) {
129
                                $url = 'https://test.adyen.com/hpp/select.shtml';
130
                            } else {
131 132 133 134 135 136 137 138 139 140
                                if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod(
                                    $this->_order->getPayment()->getAdditionalInformation('brand_code')
                                ) || $this->_adyenHelper->isPaymentMethodMolpayMethod(
                                    $this->_order->getPayment()->getAdditionalInformation('brand_code')
                                )
                                ) {
                                    $url = "https://test.adyen.com/hpp/skipDetails.shtml";
                                } else {
                                    $url = "https://test.adyen.com/hpp/details.shtml";
                                }
141
                            }
142 143 144 145 146 147
                        }
                        break;
                    default:
                        if ($paymentRoutine == 'single' && $this->getPaymentMethodSelectionOnAdyen()) {
                            $url = 'https://live.adyen.com/hpp/pay.shtml';
                        } else {
148
                            if ($this->getPaymentMethodSelectionOnAdyen()) {
149
                                $url = 'https://live.adyen.com/hpp/select.shtml';
150
                            } else {
151 152 153 154 155 156 157 158 159 160
                                if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod(
                                    $this->_order->getPayment()->getAdditionalInformation('brand_code')
                                ) || $this->_adyenHelper->isPaymentMethodMolpayMethod(
                                    $this->_order->getPayment()->getAdditionalInformation('brand_code')
                                )
                                ) {
                                    $url = "https://live.adyen.com/hpp/skipDetails.shtml";
                                } else {
                                    $url = "https://live.adyen.com/hpp/details.shtml";
                                }
161
                            }
162 163 164
                        }
                        break;
                }
165
            }
166
        } catch (Exception $e) {
167
            // do nothing for now
168
            throw($e);
169 170
        }

171 172 173 174 175 176 177 178 179
        return $url;
    }

    /**
     * @return mixed
     */
    public function getPaymentMethodSelectionOnAdyen()
    {
        return $this->_adyenHelper->getAdyenHppConfigDataFlag('payment_selection_on_adyen');
180 181
    }

182 183 184
    /**
     * @return array
     */
185 186
    public function getFormFields()
    {
187
        $formFields = [];
188
        try {
189
            if ($this->_order->getPayment()) {
190
                $realOrderId = $this->_order->getRealOrderId();
191
                $orderCurrencyCode = $this->_order->getOrderCurrencyCode();
192 193
                $skinCode = trim($this->_adyenHelper->getAdyenHppConfigData('skin_code'));
                $amount = $this->_adyenHelper->formatAmount(
194 195
                    $this->_order->getGrandTotal(),
                    $orderCurrencyCode
196
                );
197
                $merchantAccount = trim($this->_adyenHelper->getAdyenAbstractConfigData('merchant_account', $this->_order->getStoreId()));
198 199 200 201 202 203 204 205 206
                $shopperEmail = $this->_order->getCustomerEmail();
                $customerId = $this->_order->getCustomerId();
                $shopperIP = $this->_order->getRemoteIp();
                $browserInfo = $_SERVER['HTTP_USER_AGENT'];
                $deliveryDays = $this->_adyenHelper->getAdyenHppConfigData('delivery_days');
                $shopperLocale = trim($this->_adyenHelper->getAdyenHppConfigData('shopper_locale'));
                $shopperLocale = (!empty($shopperLocale)) ? $shopperLocale : $this->_resolver->getLocale();
                $countryCode = trim($this->_adyenHelper->getAdyenHppConfigData('country_code'));
                $countryCode = (!empty($countryCode)) ? $countryCode : false;
207

208
                // if directory lookup is enabled use the billingaddress as countrycode
209 210
                if ($countryCode == false) {
                    if ($this->_order->getBillingAddress() &&
211 212
                        $this->_order->getBillingAddress()->getCountryId() != ""
                    ) {
213 214 215 216 217
                        $countryCode = $this->_order->getBillingAddress()->getCountryId();
                    }
                }

                $formFields = [];
218

219
                $formFields['merchantAccount'] = $merchantAccount;
220
                $formFields['merchantReference'] = $realOrderId;
221 222 223
                $formFields['paymentAmount'] = (int)$amount;
                $formFields['currencyCode'] = $orderCurrencyCode;
                $formFields['shipBeforeDate'] = date(
224 225 226
                    "Y-m-d",
                    mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y"))
                );
227 228 229 230 231 232
                $formFields['skinCode'] = $skinCode;
                $formFields['shopperLocale'] = $shopperLocale;
                $formFields['countryCode'] = $countryCode;
                $formFields['shopperIP'] = $shopperIP;
                $formFields['browserInfo'] = $browserInfo;
                $formFields['sessionValidity'] = date(
233 234 235
                    DATE_ATOM,
                    mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y"))
                );
236
                $formFields['shopperEmail'] = $shopperEmail;
237
                // recurring
238
                $recurringType = $this->_adyenHelper->getRecurringTypeFromOneclickRecurringSetting();
239
                $brandCode = $this->_order->getPayment()->getAdditionalInformation(
240 241
                    \Adyen\Payment\Observer\AdyenHppDataAssignObserver::BRAND_CODE
                );
242 243 244 245 246 247

                // Paypal does not allow ONECLICK,RECURRING only RECURRING
                if ($brandCode == "paypal" && $recurringType == 'ONECLICK,RECURRING') {
                    $recurringType = "RECURRING";
                }

248 249
                if ($customerId > 0) {
                    $formFields['recurringContract'] = $recurringType;
250
                    $formFields['shopperReference'] = $customerId;
251 252
                } else {
                    // required for openinvoice payment methods use unique id
253 254
                    $uniqueReference = "guest_" . $realOrderId . "_" . $this->_order->getStoreId();
                    $formFields['shopperReference'] = $uniqueReference;
255 256
                }

257
                //blocked methods
258
                $formFields['blockedMethods'] = "";
259 260 261 262

                $baseUrl = $this->_storeManager->getStore($this->getStore())
                    ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

263
                $formFields['resURL'] = $baseUrl . 'adyen/process/result';
264 265

                if ($brandCode) {
266
                    $formFields['brandCode'] = $brandCode;
267 268 269 270
                }

                $issuerId = $this->_order->getPayment()->getAdditionalInformation("issuer_id");
                if ($issuerId) {
271
                    $formFields['issuerId'] = $issuerId;
272 273
                }

274 275 276 277 278 279 280 281 282 283 284
                $formFields = $this->setBillingAddressData($formFields);
                $formFields = $this->setShippingAddressData($formFields);
                $formFields = $this->setOpenInvoiceData($formFields);

                $formFields['shopper.gender'] = $this->getGenderText($this->_order->getCustomerGender());
                $dob = $this->_order->getCustomerDob();
                if ($dob) {
                    $formFields['shopper.dateOfBirthDayOfMonth'] = trim($this->_getDate($dob, 'd'));
                    $formFields['shopper.dateOfBirthMonth'] = trim($this->_getDate($dob, 'm'));
                    $formFields['shopper.dateOfBirthYear'] = trim($this->_getDate($dob, 'Y'));
                }
285

286 287
                // For klarna acceptPrivacyPolicy to skip HPP page
                if ($brandCode == "klarna") {
288 289
                    $ssn = $this->_order->getPayment()->getAdditionalInformation('ssn');
                    if (!empty($ssn)) {
290
                        $formFields['shopper.socialSecurityNumber'] = $ssn;
291
                    }
292
                    //  // needed for DE and AT
293
                    $formFields['klarna.acceptPrivacyPolicy'] = 'true';
294 295 296
                }

                // OpenInvoice don't allow to edit billing and delivery items
297

298
                if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($brandCode)) {
299
                    // don't allow editable shipping/delivery address
300
                    $formFields['billingAddressType'] = "1";
301 302
                    $formFields['deliveryAddressType'] = "1";
                }
303 304 305 306 307

                if ($this->_order->getPayment()->getAdditionalInformation("df_value") != "") {
                    $formFields['dfValue'] = $this->_order->getPayment()->getAdditionalInformation("df_value");
                }

308 309 310
                // Sign request using secret key
                $hmacKey = $this->_adyenHelper->getHmac();
                $merchantSig = \Adyen\Util\Util::calculateSha256Signature($hmacKey, $formFields);
311
                $formFields['merchantSig'] = $merchantSig;
312 313

                $this->_adyenLogger->addAdyenDebug(print_r($formFields, true));
314
            }
315
        } catch (Exception $e) {
316 317
            // do nothing for now
        }
318
        return $formFields;
319
    }
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

    /**
     * Set Billing Address data
     *
     * @param $formFields
     */
    protected function setBillingAddressData($formFields)
    {
        $billingAddress = $this->_order->getBillingAddress();
        if ($billingAddress) {
            $formFields['shopper.firstName'] = trim($billingAddress->getFirstname());
            $middleName = trim($billingAddress->getMiddlename());
            if ($middleName != "") {
                $formFields['shopper.infix'] = trim($middleName);
            }

            $formFields['shopper.lastName'] = trim($billingAddress->getLastname());
            $formFields['shopper.telephoneNumber'] = trim($billingAddress->getTelephone());

339 340 341 342 343 344 345
            if ($this->_adyenHelper->isSeparateHouseNumberRequired($billingAddress->getCountryId())) {
                $this->_adyenLogger->addAdyenDebug("separate house number required");
                $street = $this->_adyenHelper->getStreet($billingAddress);

                if (isset($street['name']) && $street['name'] != "") {
                    $formFields['billingAddress.street'] = $street['name'];
                }
346

347 348 349 350 351
                if (isset($street['house_number']) && $street['house_number'] != "") {
                    $formFields['billingAddress.houseNumberOrName'] = $street['house_number'];
                } else {
                    $formFields['billingAddress.houseNumberOrName'] = "NA";
                }
352
            } else {
353 354
                $this->_adyenLogger->addAdyenDebug("separate house number NOT required");
                $formFields['billingAddress.street'] = implode(" ", $billingAddress->getStreet());
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
            }

            if (trim($billingAddress->getCity()) == "") {
                $formFields['billingAddress.city'] = "NA";
            } else {
                $formFields['billingAddress.city'] = trim($billingAddress->getCity());
            }

            if (trim($billingAddress->getPostcode()) == "") {
                $formFields['billingAddress.postalCode'] = "NA";
            } else {
                $formFields['billingAddress.postalCode'] = trim($billingAddress->getPostcode());
            }

            if (trim($billingAddress->getRegionCode()) == "") {
                $formFields['billingAddress.stateOrProvince'] = "NA";
            } else {
                $formFields['billingAddress.stateOrProvince'] = trim($billingAddress->getRegionCode());
            }

            if (trim($billingAddress->getCountryId()) == "") {
                $formFields['billingAddress.country'] = "NA";
            } else {
                $formFields['billingAddress.country'] = trim($billingAddress->getCountryId());
            }
        }
        return $formFields;
    }

    /**
     * Set Shipping Address data
     *
     * @param $formFields
     */
    protected function setShippingAddressData($formFields)
    {
        $shippingAddress = $this->_order->getShippingAddress();
392
        $this->_adyenLogger->addAdyenDebug($shippingAddress->getCountryId());
393
        if ($shippingAddress) {
394 395 396
            if ($this->_adyenHelper->isSeparateHouseNumberRequired($shippingAddress->getCountryId())) {
                $this->_adyenLogger->addAdyenDebug("separate house number required");
                $street = $this->_adyenHelper->getStreet($shippingAddress);
397

398 399 400
                if (isset($street['name']) && $street['name'] != "") {
                    $formFields['deliveryAddress.street'] = $street['name'];
                }
401

402 403 404 405 406
                if (isset($street['house_number']) && $street['house_number'] != "") {
                    $formFields['deliveryAddress.houseNumberOrName'] = $street['house_number'];
                } else {
                    $formFields['deliveryAddress.houseNumberOrName'] = "NA";
                }
407
            } else {
408 409
                $this->_adyenLogger->addAdyenDebug("separate house number NOT required");
                $formFields['deliveryAddress.street'] = implode(" ", $shippingAddress->getStreet());
410 411
            }

412

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
            if (trim($shippingAddress->getCity()) == "") {
                $formFields['deliveryAddress.city'] = "NA";
            } else {
                $formFields['deliveryAddress.city'] = trim($shippingAddress->getCity());
            }

            if (trim($shippingAddress->getPostcode()) == "") {
                $formFields['deliveryAddress.postalCode'] = "NA";
            } else {
                $formFields['deliveryAddress.postalCode'] = trim($shippingAddress->getPostcode());
            }

            if (trim($shippingAddress->getRegionCode()) == "") {
                $formFields['deliveryAddress.stateOrProvince'] = "NA";
            } else {
                $formFields['deliveryAddress.stateOrProvince'] = trim($shippingAddress->getRegionCode());
            }

            if (trim($shippingAddress->getCountryId()) == "") {
                $formFields['deliveryAddress.country'] = "NA";
            } else {
                $formFields['deliveryAddress.country'] = trim($shippingAddress->getCountryId());
            }
        }
437

438 439 440 441 442 443 444 445 446 447 448 449 450 451
        return $formFields;
    }

    /**
     * @param $formFields
     * @return mixed
     */
    protected function setOpenInvoiceData($formFields)
    {
        $count = 0;
        $currency = $this->_order->getOrderCurrencyCode();

        foreach ($this->_order->getAllVisibleItems() as $item) {
            ++$count;
452
            $numberOfItems = (int)$item->getQtyOrdered();
453

454 455 456 457 458 459 460 461 462 463 464 465
            $formFields = $this->_adyenHelper->createOpenInvoiceLineItem(
                $formFields,
                $count,
                $item->getName(),
                $item->getPrice(),
                $currency,
                $item->getTaxAmount(),
                $item->getPriceInclTax(),
                $item->getTaxPercent(),
                $numberOfItems,
                $this->_order->getPayment()
            );
466 467 468 469 470
        }

        // Discount cost
        if ($this->_order->getDiscountAmount() > 0 || $this->_order->getDiscountAmount() < 0) {
            ++$count;
471

472 473 474 475 476 477
            $description = __('Total Discount');
            $itemAmount = $this->_adyenHelper->formatAmount($this->_order->getDiscountAmount(), $currency);
            $itemVatAmount = "0";
            $itemVatPercentage = "0";
            $numberOfItems = 1;

478 479 480 481 482 483 484 485 486 487 488
            $formFields = $this->_adyenHelper->getOpenInvoiceLineData(
                $formFields,
                $count,
                $currency,
                $description,
                $itemAmount,
                $itemVatAmount,
                $itemVatPercentage,
                $numberOfItems,
                $this->_order->getPayment()
            );
489 490 491 492 493
        }

        // Shipping cost
        if ($this->_order->getShippingAmount() > 0 || $this->_order->getShippingTaxAmount() > 0) {
            ++$count;
494 495 496 497 498 499 500 501
            $formFields = $this->_adyenHelper->createOpenInvoiceLineShipping(
                $formFields,
                $count,
                $this->_order,
                $this->_order->getShippingAmount(),
                $this->_order->getShippingTaxAmount(),
                $currency,
                $this->_order->getPayment()
502
            );
503 504
        }

505
        $formFields['openinvoicedata.refundDescription'] = "Refund / Correction for " . $formFields['merchantReference'];
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
        $formFields['openinvoicedata.numberOfLines'] = $count;

        return $formFields;
    }

    /**
     * @param $genderId
     * @return string
     */
    protected function getGenderText($genderId)
    {
        $result = "";
        if ($genderId == '1') {
            $result = 'MALE';
        } elseif ($genderId == '2') {
            $result = 'FEMALE';
        }
        return $result;
    }

    /**
     * @param null $date
     * @param string $format
     * @return mixed
     */
    protected function _getDate($date = null, $format = 'Y-m-d H:i:s')
    {
        if (strlen($date) < 0) {
            $date = date('d-m-Y H:i:s');
        }
        $timeStamp = new \DateTime($date);
        return $timeStamp->format($format);
    }


541
    /**
542
     * The character escape function is called from the array_map function in _signRequestParams
543
     *
544 545
     * @param $val
     * @return mixed
546
     */
547
    protected function escapeString($val)
548
    {
549
        return str_replace(':', '\\:', str_replace('\\', '\\\\', $val));
550 551 552 553 554 555 556 557 558 559 560
    }

    /**
     * Get frontend checkout session object
     *
     * @return \Magento\Checkout\Model\Session
     */
    protected function _getCheckout()
    {
        return $this->_checkoutSession;
    }
561
}