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 19.5 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 34 35
    /**
     * quest prefix
     */
    const GUEST_ID = 'customer_';

36 37 38
    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
39
    protected $_orderFactory;
40

41 42 43 44 45
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

46
    /**
47
     * @var  \Magento\Sales\Model\Order
48
     */
49 50
    protected $_order;

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    /**
     * @var \Adyen\Payment\Helper\Data
     */
    protected $_adyenHelper;

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

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

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

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

        if (!$this->_order) {
            $incrementId = $this->_getCheckout()->getLastRealOrderId();
            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
        }
96 97 98
    }


99 100 101
    /**
     * @return $this
     */
102 103 104 105 106
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

107 108 109
    /**
     * @return string
     */
110 111
    public function getFormUrl()
    {
112
        $url = "";
113
        try {
114 115 116 117 118 119 120 121
            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 {
122 123 124 125

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

160 161 162 163 164 165 166 167 168
        return $url;
    }

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

171 172 173
    /**
     * @return array
     */
174 175
    public function getFormFields()
    {
176
        $formFields = [];
177
        try {
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
            if ($this->_order->getPayment()) {

                $realOrderId       = $this->_order->getRealOrderId();
                $orderCurrencyCode = $this->_order->getOrderCurrencyCode();
                $skinCode          = trim($this->_adyenHelper->getAdyenHppConfigData('skin_code'));
                $amount            = $this->_adyenHelper->formatAmount(
                    $this->_order->getGrandTotal(), $orderCurrencyCode
                );
                $merchantAccount   = trim($this->_adyenHelper->getAdyenAbstractConfigData('merchant_account'));
                $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;

                // if directory lookup is enabled use the billingadress as countrycode
                if ($countryCode == false) {
                    if ($this->_order->getBillingAddress() &&
                        $this->_order->getBillingAddress()->getCountryId() != "") {
                        $countryCode = $this->_order->getBillingAddress()->getCountryId();
                    }
                }

                $formFields = [];
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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
                $formFields['merchantAccount']   = $merchantAccount;
                $formFields['merchantReference'] = $realOrderId;
                $formFields['paymentAmount']     = (int)$amount;
                $formFields['currencyCode']      = $orderCurrencyCode;
                $formFields['shipBeforeDate']    = date(
                    "Y-m-d",
                    mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y"))
                );
                $formFields['skinCode']          = $skinCode;
                $formFields['shopperLocale']     = $shopperLocale;
                $formFields['countryCode']       = $countryCode;
                $formFields['shopperIP']         = $shopperIP;
                $formFields['browserInfo']       = $browserInfo;
                $formFields['sessionValidity']   = date(
                    DATE_ATOM,
                    mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y"))
                );
                $formFields['shopperEmail']      = $shopperEmail;
                // recurring
                $recurringType                   = trim($this->_adyenHelper->getAdyenAbstractConfigData(
                    'recurring_type')
                );
                $brandCode                       = $this->_order->getPayment()->getAdditionalInformation("brand_code");

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

                $formFields['recurringContract'] = $recurringType;
                $formFields['shopperReference']  = (!empty($customerId)) ? $customerId : self::GUEST_ID . $realOrderId;
                //blocked methods
                $formFields['blockedMethods']    = "";

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

                $formFields['resURL']            = $baseUrl . 'adyen/process/result';
                $hmacKey                         = $this->_adyenHelper->getHmac();


                if ($brandCode) {
                    $formFields['brandCode']     = $brandCode;
                }

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

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
                $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'));
                }
                
                if ($this->_order->getPayment()->getAdditionalInformation(
                        \Adyen\Payment\Observer\AdyenHppDataAssignObserver::BRAND_CODE) == "klarna"
                ) {
274 275 276 277

                    //  // needed for DE and AT
                    $formFields['klarna.acceptPrivacyPolicy']   = 'true';

278 279 280 281 282 283 284 285
                    // don't allow editable shipping/delivery address
                    $formFields['billingAddressType']  = "1";
                    $formFields['deliveryAddressType'] = "1";

                    // make setting to make this optional
                    $adyFields['shopperType'] = "1";
                }
                
286 287 288 289 290 291 292 293 294 295 296 297
                // Sort the array by key using SORT_STRING order
                ksort($formFields, SORT_STRING);

                // Generate the signing data string
                $signData = implode(":", array_map([$this, 'escapeString'],
                    array_merge(array_keys($formFields), array_values($formFields))));

                $merchantSig = base64_encode(hash_hmac('sha256', $signData, pack("H*", $hmacKey), true));

                $formFields['merchantSig']      = $merchantSig;

                $this->_adyenLogger->addAdyenDebug(print_r($formFields, true));
298 299 300 301 302
            }

        } catch(Exception $e) {
            // do nothing for now
        }
303
        return $formFields;
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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 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 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 437 438 439 440 441 442 443

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

            $street = $this->_adyenHelper->getStreet($billingAddress);

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

            if (isset($street['house_number']) && $street['house_number'] != "") {
                $formFields['billingAddress.houseNumberOrName'] = $street['house_number'];
            } else {
                $formFields['billingAddress.houseNumberOrName'] = "NA";
            }

            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();

        if ($shippingAddress) {

            $street = $this->_adyenHelper->getStreet($shippingAddress);

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

            if (isset($street['house_number']) && $street['house_number'] != "") {
                $formFields['deliveryAddress.houseNumberOrName'] = $street['house_number'];
            } else {
                $formFields['deliveryAddress.houseNumberOrName'] = "NA";
            }

            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());
            }
        }
        return $formFields;
    }

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

        foreach ($this->_order->getAllVisibleItems() as $item) {

            ++$count;
            $linename = "line".$count;
            $formFields['openinvoicedata.' . $linename . '.currencyCode'] = $currency;
            $formFields['openinvoicedata.' . $linename . '.description'] =
                str_replace("\n", '', trim($item->getName()));

            $formFields['openinvoicedata.' . $linename . '.itemAmount'] =
                $this->_adyenHelper->formatAmount($item->getPrice(), $currency);

            $formFields['openinvoicedata.' . $linename . '.itemVatAmount'] =
                ($item->getTaxAmount() > 0 && $item->getPriceInclTax() > 0) ?
                    $this->_adyenHelper->formatAmount(
                        $item->getPriceInclTax(),
                        $currency
                    ) -  $this->_adyenHelper->formatAmount(
                        $item->getPrice(),
                        $currency
                    ) : $this->_adyenHelper->formatAmount($item->getTaxAmount(), $currency);
444
            
445 446 447 448 449 450 451 452 453 454 455 456
            // Calculate vat percentage
            $percentageMinorUnits = $this->_adyenHelper->getMinorUnitTaxPercent($item->getTaxPercent());
            $formFields['openinvoicedata.' . $linename . '.itemVatPercentage'] = $percentageMinorUnits;
            $formFields['openinvoicedata.' . $linename . '.numberOfItems'] = (int) $item->getQtyOrdered();

            if ($this->_order->getPayment()->getAdditionalInformation(
                    \Adyen\Payment\Observer\AdyenHppDataAssignObserver::BRAND_CODE) == "klarna"
            ) {
                $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "High";
            } else {
                $formFields['openinvoicedata.' . $linename . '.vatCategory'] = "None";
            }
457 458 459 460 461

            if ($item->getSku() != "") {
                $formFields['openinvoicedata.' . $linename . '.itemId'] = $item->getSku();
            }

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        }

        $formFields['openinvoicedata.refundDescription'] = "Refund / Correction for ".$formFields['merchantReference'];
        $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);
    }


500
    /**
501
     * The character escape function is called from the array_map function in _signRequestParams
502
     *
503 504
     * @param $val
     * @return mixed
505
     */
506
    protected function escapeString($val)
507
    {
508
        return str_replace(':', '\\:', str_replace('\\', '\\\\', $val));
509 510 511 512 513 514 515 516 517 518 519 520
    }

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