Redirect.php 14.6 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
/**
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * 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>
 */
23 24

namespace Adyen\Payment\Controller\Process;
25

26 27 28 29 30 31 32
use Magento\Framework\App\Request\Http as Http;
use Magento\Vault\Api\Data\PaymentTokenInterface;
use Magento\Vault\Api\Data\PaymentTokenFactoryInterface;
use Magento\Sales\Api\Data\OrderPaymentExtensionInterface;
use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory;
use Magento\Sales\Model\ResourceModel\Order\Payment as OrderPaymentResource;
use Magento\Payment\Model\InfoInterface;
33 34 35 36 37 38 39 40 41 42 43 44 45 46

class Redirect extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Quote\Model\Quote
     */
    protected $_quote = false;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;

    /**
47
     * @var \Magento\Sales\Model\Order
48 49 50 51 52 53 54 55
     */
    protected $_order;

    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    protected $_orderFactory;

56 57 58 59
    /**
     * @var \Adyen\Payment\Logger\AdyenLogger
     */
    protected $_adyenLogger;
60

61 62 63 64
    /**
     * @var \Adyen\Payment\Helper\Data
     */
    protected $_adyenHelper;
65

66 67 68 69
    /**
     * @var \Adyen\Payment\Model\Api\PaymentRequest
     */
    protected $_paymentRequest;
70

71 72 73 74
    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    protected $_orderRepository;
75 76

    /**
77
     * @var PaymentTokenFactoryInterface
78
     */
79
    private $paymentTokenFactory;
marcoss's avatar
marcoss committed
80

81
    /**
82
     * @var OrderPaymentExtensionInterfaceFactory
83
     */
84
    private $paymentExtensionFactory;
marcoss's avatar
marcoss committed
85

86
    /**
87
     * @var OrderPaymentResource
88
     */
89 90
    private $orderPaymentResource;

marcoss's avatar
marcoss committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    /**
     * @var \Magento\Framework\Serialize\SerializerInterface
     */
    private $serializer;

    /**
     * Redirect constructor.
     *
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
     * @param \Adyen\Payment\Helper\Data $adyenHelper
     * @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
     * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
     * @param PaymentTokenFactoryInterface $paymentTokenFactory
     * @param OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory
     * @param OrderPaymentResource $orderPaymentResource
     * @param \Magento\Framework\Serialize\SerializerInterface $serializer
     */
109 110
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
111 112 113 114
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
        \Adyen\Payment\Helper\Data $adyenHelper,
        \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
115 116
        PaymentTokenFactoryInterface $paymentTokenFactory,
        OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory,
marcoss's avatar
marcoss committed
117 118
        OrderPaymentResource $orderPaymentResource,
        \Magento\Framework\Serialize\SerializerInterface $serializer
119 120
    ) {
        parent::__construct($context);
121 122 123 124
        $this->_adyenLogger = $adyenLogger;
        $this->_adyenHelper = $adyenHelper;
        $this->_paymentRequest = $paymentRequest;
        $this->_orderRepository = $orderRepository;
125 126 127
        $this->paymentTokenFactory = $paymentTokenFactory;
        $this->paymentExtensionFactory = $paymentExtensionFactory;
        $this->orderPaymentResource = $orderPaymentResource;
marcoss's avatar
marcoss committed
128
        $this->serializer = $serializer;
129
        if (interface_exists(\Magento\Framework\App\CsrfAwareActionInterface::class)) {
130 131 132
            $request = $this->getRequest();
            if ($request instanceof Http && $request->isPost()) {
                $request->setParam('isAjax', true);
133
                $request->getHeaders()->addHeaderLine('X_REQUESTED_WITH', 'XMLHttpRequest');
134
            }
135 136 137
        }
    }

138 139 140 141 142 143
    /**
     * Validate 3D secure payment
     */
    public function execute()
    {
        $active = null;
144

145 146
        // check if 3d is active
        $order = $this->_getOrder();
147

148 149 150 151 152
        if ($order->getPayment()) {
            $active = $order->getPayment()->getAdditionalInformation('3dActive');
            $success = $order->getPayment()->getAdditionalInformation('3dSuccess');
            $checkoutAPM = $order->getPayment()->getAdditionalInformation('checkoutAPM');
        }
153

154 155 156
        // check if 3D secure is active. If not just go to success page
        if ($active && $success != true) {
            $this->_adyenLogger->addAdyenResult("3D secure is active");
157

Ángel Campos's avatar
Ángel Campos committed
158 159
            // check if the GET request contains the required 3DS params
            if ($this->getRequest()->getParam('PaRes') && $this->getRequest()->getParam('MD')) {
160
                $this->_adyenLogger->addAdyenResult("Process 3D secure payment");
Ángel Campos's avatar
Ángel Campos committed
161 162 163 164 165 166
                $requestMD = $this->getRequest()->getParam('MD');
                $requestPaRes = $this->getRequest()->getParam('PaRes');

                //Reset the payment's additional info to the new MD and PaRes
                $order->getPayment()->setAdditionalInformation('md', $requestMD);
                $order->getPayment()->setAdditionalInformation('paRequest', $requestPaRes);
167

Ángel Campos's avatar
Ángel Campos committed
168 169 170 171 172 173 174 175 176 177 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                $order->getPayment()->setAdditionalInformation('paResponse', $requestPaRes);

                try {
                    $result = $this->_authorise3d($order->getPayment());
                    $responseCode = $result['resultCode'];
                } catch (\Exception $e) {
                    $this->_adyenLogger->addAdyenResult("Process 3D secure payment was refused");
                    $responseCode = 'Refused';
                }

                $this->_adyenLogger->addAdyenResult("Process 3D secure payment result is: " . $responseCode);

                // check if authorise3d was successful
                if ($responseCode == 'Authorised') {
                    $order->addStatusHistoryComment(__('3D-secure validation was successful'))->save();
                    // set back to false so when pressed back button on the success page
                    // it will reactivate 3D secure
                    $order->getPayment()->setAdditionalInformation('3dActive', '');
                    $order->getPayment()->setAdditionalInformation('3dSuccess', true);

                    if (!$this->_adyenHelper->isCreditCardVaultEnabled() &&
                        !empty($result['additionalData']['recurring.recurringDetailReference'])) {
                        $this->_adyenHelper->createAdyenBillingAgreement($order, $result['additionalData']);
                    } elseif (!empty($result['additionalData']['recurring.recurringDetailReference'])
                    ) {
                        try {
                            $additionalData = $result['additionalData'];
                            $token = $additionalData['recurring.recurringDetailReference'];
                            $expirationDate = $additionalData['expiryDate'];
                            $cardType = $additionalData['paymentMethod'];
                            $cardSummary = $additionalData['cardSummary'];
                            /** @var PaymentTokenInterface $paymentToken */
                            $paymentToken = $this->paymentTokenFactory->create(
                                PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD
                            );
                            $paymentToken->setGatewayToken($token);
                            $paymentToken->setExpiresAt($this->getExpirationDate($expirationDate));
                            $details = [
                                'type' => $cardType,
                                'maskedCC' => $cardSummary,
                                'expirationDate' => $expirationDate
                            ];
                            $paymentToken->setTokenDetails(json_encode($details));
                            $extensionAttributes = $this->getExtensionAttributes($order->getPayment());
                            $extensionAttributes->setVaultPaymentToken($paymentToken);
                            $orderPayment = $order->getPayment()->setExtensionAttributes($extensionAttributes);
                            $add = $this->serializer->unserialize($orderPayment->getAdditionalData());
                            $add['force_save'] = true;
                            $orderPayment->setAdditionalData($this->serializer->serialize($add));
                            $this->orderPaymentResource->save($orderPayment);
                        } catch (\Exception $e) {
                            $this->_adyenLogger->error((string)$e->getMessage());
220
                        }
Ángel Campos's avatar
Ángel Campos committed
221
                    }
222

Ángel Campos's avatar
Ángel Campos committed
223 224 225 226 227 228 229 230 231 232 233 234 235
                    $this->_orderRepository->save($order);

                    $this->_redirect('checkout/onepage/success', ['_query' => ['utm_nooverride' => '1']]);
                } else {
                    /*
                     * Since responseCode!='Authorised' the order could be cancelled immediately,
                     * but redirect payments can have multiple conflicting responses.
                     * The order will be cancelled if an Authorization
                     * Success=False notification is processed instead
                    */
                    $order->addStatusHistoryComment(
                        __(
                            '3D-secure validation was unsuccessful. This order will be cancelled when the related 
236
                                notification has been processed.'
Ángel Campos's avatar
Ángel Campos committed
237 238
                        )
                    )->save();
239

Ángel Campos's avatar
Ángel Campos committed
240
                    $this->messageManager->addErrorMessage("3D-secure validation was unsuccessful");
241

Ángel Campos's avatar
Ángel Campos committed
242 243
                    // reactivate the quote
                    $session = $this->_getCheckout();
244

Ángel Campos's avatar
Ángel Campos committed
245 246
                    // restore the quote
                    $session->restoreQuote();
247

Ángel Campos's avatar
Ángel Campos committed
248
                    $this->_redirect($this->_adyenHelper->getAdyenAbstractConfigData('return_path'));
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
                }
            } else {
                $this->_adyenLogger->addAdyenResult("Customer was redirected to bank for 3D-secure validation.");
                $order->addStatusHistoryComment(
                    __(
                        'Customer was redirected to bank for 3D-secure validation. Once the shopper authenticated, 
                        the order status will be updated accordingly. 
                        <br />Make sure that your notifications are being processed! 
                        <br />If the order is stuck on this status, the shopper abandoned the session. 
                        The payment can be seen as unsuccessful. 
                        <br />The order can be automatically cancelled based on the OFFER_CLOSED notification. 
                        Please contact Adyen Support to enable this.'
                    )
                )->save();
                $this->_view->loadLayout();
                $this->_view->getLayout()->initMessages();
                $this->_view->renderLayout();
            }
        } elseif (!empty($checkoutAPM)) {
            $this->_view->loadLayout();
            $this->_view->getLayout()->initMessages();
            $this->_view->renderLayout();
        } else {
            $this->_redirect('checkout/onepage/success', ['_query' => ['utm_nooverride' => '1']]);
        }
    }
275

276 277 278 279 280 281 282 283 284
    /**
     * Return checkout session object
     *
     * @return \Magento\Checkout\Model\Session
     */
    protected function _getCheckoutSession()
    {
        return $this->_checkoutSession;
    }
285

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    /**
     * Get order object
     *
     * @return \Magento\Sales\Model\Order
     */
    protected function _getOrder()
    {
        if (!$this->_order) {
            $incrementId = $this->_getCheckout()->getLastRealOrderId();
            $this->_orderFactory = $this->_objectManager->get(\Magento\Sales\Model\OrderFactory::class);
            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
        }
        return $this->_order;
    }

    /**
     * @return \Magento\Checkout\Model\Session
     */
    protected function _getCheckout()
    {
        return $this->_objectManager->get(\Magento\Checkout\Model\Session::class);
    }

    /**
     * @return mixed
     */
    protected function _getQuote()
    {
        return $this->_objectManager->get(\Magento\Quote\Model\Quote::class);
    }

    /**
     * @return mixed
     */
    protected function _getQuoteManagement()
    {
        return $this->_objectManager->get(\Magento\Quote\Model\QuoteManagement::class);
    }

    /**
     * Called by redirect controller when cc payment has 3D secure
     *
     * @param $payment
     * @return mixed
     * @throws \Exception
     */
    protected function _authorise3d($payment)
    {
        try {
            $response = $this->_paymentRequest->authorise3d($payment);
        } catch (\Exception $e) {
            throw $e;
        }

        return $response;
    }
342

343
    /**
344 345
     * @param $expirationDate
     * @return string
346
     */
347
    private function getExpirationDate($expirationDate)
348
    {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        $expirationDate = explode('/', $expirationDate);
        //add leading zero to month
        $month = sprintf("%02d", $expirationDate[0]);
        $expDate = new \DateTime(
            $expirationDate[1]
            . '-'
            . $month
            . '-'
            . '01'
            . ' '
            . '00:00:00',
            new \DateTimeZone('UTC')
        );
        // add one month
        $expDate->add(new \DateInterval('P1M'));
        return $expDate->format('Y-m-d 00:00:00');
365 366
    }

367
    /**
368
     * Get payment extension attributes
369
     *
370 371
     * @param InfoInterface $payment
     * @return OrderPaymentExtensionInterface
372
     */
373
    private function getExtensionAttributes(InfoInterface $payment)
374
    {
375 376 377 378 379 380
        $extensionAttributes = $payment->getExtensionAttributes();
        if (null === $extensionAttributes) {
            $extensionAttributes = $this->paymentExtensionFactory->create();
            $payment->setExtensionAttributes($extensionAttributes);
        }
        return $extensionAttributes;
381
    }
382
}