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 15.2 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
use Adyen\AdyenException;
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
    /**
     * @var \Magento\Tax\Model\Config
     */
    protected $_taxConfig;

66 67 68
    /**
     * @var \Magento\Tax\Model\Calculation
     */
69 70
    protected $_taxCalculation;

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    /**
     * Request object
     */
    protected $_request;

    /**
     * Redirect constructor.
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param array $data
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Adyen\Payment\Helper\Data $adyenHelper
     * @param \Magento\Framework\Locale\ResolverInterface $resolver
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
     * @param \Magento\Tax\Model\Config $taxConfig
     * @param \Magento\Tax\Model\Calculation $taxCalculation
     */
89 90 91
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Model\OrderFactory $orderFactory,
92 93 94
        \Magento\Checkout\Model\Session $checkoutSession,
        \Adyen\Payment\Helper\Data $adyenHelper,
        \Magento\Framework\Locale\ResolverInterface $resolver,
95 96
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
        \Magento\Tax\Model\Config $taxConfig,
Imran Shakil's avatar
Imran Shakil committed
97 98
        \Magento\Tax\Model\Calculation $taxCalculation,
        array $data = []
99
    ) {
100 101 102
        $this->_orderFactory = $orderFactory;
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
103 104 105 106 107

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

108
        $this->_getOrder();
109 110
        $this->_taxConfig = $taxConfig;
        $this->_taxCalculation = $taxCalculation;
111
        $this->_request = $context->getRequest();
112 113
    }

114 115 116 117
    /**
     * @return mixed|string[]
     * @throws AdyenException
     */
118
    public function getRedirectMethod()
119 120 121 122 123 124 125
    {
        if ($redirectMethod = $this->getPayment()->getAdditionalInformation('redirectMethod')) {
            return $redirectMethod;
        }

        throw new AdyenException("No redirect method is provided.");
    }
126

127
    /**
128
     * @return Redirect
129
     */
130 131 132 133 134
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    /**
     * Retrieves redirect url for the flow of checkout API
     *
     * @return string[]
     * @throws AdyenException
     */
    public function getRedirectUrl()
    {
        if ($redirectUrl = $this->getPayment()->getAdditionalInformation('redirectUrl')) {
            return $redirectUrl;
        }

        throw new AdyenException("No redirect url is provided.");
    }

150 151 152
    /**
     * @return string
     */
153 154
    public function getFormUrl()
    {
155
        $url = "";
156
        try {
157 158 159
            if ($this->_order->getPayment()) {
                switch ($this->_adyenHelper->isDemoMode()) {
                    case true:
160
                        if ($this->_adyenHelper->doesPaymentMethodSkipDetails(
161 162
                            $this->_order->getPayment()->getAdditionalInformation('brand_code')
                        )
163 164
                        ) {
                            $url = "https://test.adyen.com/hpp/skipDetails.shtml";
165
                        } else {
166
                            $url = "https://test.adyen.com/hpp/details.shtml";
167 168 169
                        }
                        break;
                    default:
170
                        if ($this->_adyenHelper->doesPaymentMethodSkipDetails(
171 172
                            $this->_order->getPayment()->getAdditionalInformation('brand_code')
                        )
173 174
                        ) {
                            $url = "https://live.adyen.com/hpp/skipDetails.shtml";
175
                        } else {
176
                            $url = "https://live.adyen.com/hpp/details.shtml";
177 178 179
                        }
                        break;
                }
180
            }
181
        } catch (Exception $e) {
182
            // do nothing for now
183
            throw($e);
184 185
        }

186 187 188
        return $url;
    }

189 190 191 192 193 194 195
    /**
     * @return mixed
     */
    private function getBrandCode()
    {
        return $this->getPayment()->getAdditionalInformation('brand_code');
    }
196 197 198 199 200 201 202 203 204

    /**
     * Set Billing Address data
     *
     * @param $formFields
     */
    protected function setBillingAddressData($formFields)
    {
        $billingAddress = $this->_order->getBillingAddress();
205

206 207 208 209 210 211 212 213 214 215
        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());

216 217 218
            if ($this->_adyenHelper->isSeparateHouseNumberRequired($billingAddress->getCountryId())) {
                $street = $this->_adyenHelper->getStreet($billingAddress);

219
                if (!empty($street['name'])) {
220 221
                    $formFields['billingAddress.street'] = $street['name'];
                }
222

223
                if (!empty($street['house_number'])) {
224 225 226 227
                    $formFields['billingAddress.houseNumberOrName'] = $street['house_number'];
                } else {
                    $formFields['billingAddress.houseNumberOrName'] = "NA";
                }
228
            } else {
229
                $formFields['billingAddress.street'] = implode(" ", $billingAddress->getStreet());
230 231 232 233 234 235 236 237 238
            }

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

            if (trim($billingAddress->getPostcode()) == "") {
239
                $formFields['billingAddress.postalCode'] = "";
240 241 242 243 244
            } else {
                $formFields['billingAddress.postalCode'] = trim($billingAddress->getPostcode());
            }

            if (trim($billingAddress->getRegionCode()) == "") {
245
                $formFields['billingAddress.stateOrProvince'] = "";
246 247 248 249 250
            } else {
                $formFields['billingAddress.stateOrProvince'] = trim($billingAddress->getRegionCode());
            }

            if (trim($billingAddress->getCountryId()) == "") {
251
                $formFields['billingAddress.country'] = "ZZ";
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
            } else {
                $formFields['billingAddress.country'] = trim($billingAddress->getCountryId());
            }
        }
        return $formFields;
    }

    /**
     * Set Shipping Address data
     *
     * @param $formFields
     */
    protected function setShippingAddressData($formFields)
    {
        $shippingAddress = $this->_order->getShippingAddress();
attilak's avatar
attilak committed
267

268
        if ($shippingAddress) {
269 270
            if ($this->_adyenHelper->isSeparateHouseNumberRequired($shippingAddress->getCountryId())) {
                $street = $this->_adyenHelper->getStreet($shippingAddress);
271

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

276 277 278 279 280
                if (isset($street['house_number']) && $street['house_number'] != "") {
                    $formFields['deliveryAddress.houseNumberOrName'] = $street['house_number'];
                } else {
                    $formFields['deliveryAddress.houseNumberOrName'] = "NA";
                }
281
            } else {
282
                $formFields['deliveryAddress.street'] = implode(" ", $shippingAddress->getStreet());
283 284 285 286 287 288 289 290 291
            }

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

            if (trim($shippingAddress->getPostcode()) == "") {
292
                $formFields['deliveryAddress.postalCode'] = "";
293 294 295 296 297
            } else {
                $formFields['deliveryAddress.postalCode'] = trim($shippingAddress->getPostcode());
            }

            if (trim($shippingAddress->getRegionCode()) == "") {
298
                $formFields['deliveryAddress.stateOrProvince'] = "";
299 300 301 302 303
            } else {
                $formFields['deliveryAddress.stateOrProvince'] = trim($shippingAddress->getRegionCode());
            }

            if (trim($shippingAddress->getCountryId()) == "") {
304
                $formFields['deliveryAddress.country'] = "ZZ";
305 306 307 308
            } else {
                $formFields['deliveryAddress.country'] = trim($shippingAddress->getCountryId());
            }
        }
309

310 311 312 313 314 315 316 317 318 319 320 321 322
        return $formFields;
    }

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

        foreach ($this->_order->getAllVisibleItems() as $item) {
323
            /** @var $item \Magento\Sales\Model\Order\Item */
324
            ++$count;
325
            $numberOfItems = (int)$item->getQtyOrdered();
326

327 328 329 330 331 332 333 334 335 336
            $formFields = $this->_adyenHelper->createOpenInvoiceLineItem(
                $formFields,
                $count,
                $item->getName(),
                $item->getPrice(),
                $currency,
                $item->getTaxAmount(),
                $item->getPriceInclTax(),
                $item->getTaxPercent(),
                $numberOfItems,
337 338
                $this->_order->getPayment(),
                $item->getId()
339
            );
340 341 342 343 344
        }

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

346 347 348 349 350 351
            $description = __('Total Discount');
            $itemAmount = $this->_adyenHelper->formatAmount($this->_order->getDiscountAmount(), $currency);
            $itemVatAmount = "0";
            $itemVatPercentage = "0";
            $numberOfItems = 1;

352 353 354 355 356 357 358 359 360
            $formFields = $this->_adyenHelper->getOpenInvoiceLineData(
                $formFields,
                $count,
                $currency,
                $description,
                $itemAmount,
                $itemVatAmount,
                $itemVatPercentage,
                $numberOfItems,
361
                $this->_order->getPayment(),
362
                "totalDiscount"
363
            );
364 365 366 367 368
        }

        // Shipping cost
        if ($this->_order->getShippingAmount() > 0 || $this->_order->getShippingTaxAmount() > 0) {
            ++$count;
369 370 371 372 373 374 375 376
            $formFields = $this->_adyenHelper->createOpenInvoiceLineShipping(
                $formFields,
                $count,
                $this->_order,
                $this->_order->getShippingAmount(),
                $this->_order->getShippingTaxAmount(),
                $currency,
                $this->_order->getPayment()
377
            );
378 379
        }

380 381
        $formFields['openinvoicedata.refundDescription'] = "Refund / Correction for " .
            $formFields['merchantReference'];
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        $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;
    }

402
    /**
403
     * The character escape function is called from the array_map function in _signRequestParams
404
     *
405 406
     * @param $val
     * @return mixed
407
     */
408
    protected function escapeString($val)
409
    {
410
        return str_replace(':', '\\:', str_replace('\\', '\\\\', $val));
411 412 413 414 415 416 417 418 419 420 421
    }

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

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    /**
     * Retrieve request object
     *
     * @return \Magento\Framework\App\RequestInterface
     */
    protected function _getRequest()
    {
        return $this->_request;
    }

    /**
     * Get order object
     *
     * @return \Magento\Sales\Model\Order
     */
    protected function _getOrder()
    {
        if (!$this->_order) {
            $incrementId = $this->_getCheckout()->getLastRealOrderId();
            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
        }
        return $this->_order;
    }

    /**
     * @return mixed
     */
    public function getPaReq()
    {
        if ($paReq = $this->getPayment()->getAdditionalInformation('paRequest')) {
            return $paReq;
        }

        throw new AdyenException("No paRequest is provided.");
    }

    /**
     * @return string[]
     * @throws AdyenException
     */
    public function getMd()
    {
        if ($md = $this->getPayment()->getAdditionalInformation('md')) {
            return $md;
        }

        throw new AdyenException("No MD is provided.");
    }

    /**
473
     * @return mixed
474 475 476
     */
    public function getTermUrl()
    {
477
        return $this->getUrl('adyen/transparent/redirect', ['_secure' => $this->_getRequest()->isSecure()]);
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    }

    /**
     * Retrieve payment object if available
     *
     * @return \Magento\Framework\DataObject|\Magento\Sales\Api\Data\OrderPaymentInterface|mixed|null
     * @throws AdyenException
     */
    private function getPayment()
    {
        try {
            $paymentObject = $this->_order->getPayment();
            if (!empty($paymentObject)) {
                return $paymentObject;
            }
        } catch (Exception $e) {
            // do nothing for now
            throw($e);
        }

        throw new AdyenException("No payment object is found.");
    }
500
}