We will be off on April 7th (Monday) for public holiday in our country

Result.php 9.54 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 25 26 27 28 29 30

namespace Adyen\Payment\Controller\Process;

use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;

class Result extends \Magento\Framework\App\Action\Action
{
31 32 33
    /**
     * @var \Adyen\Payment\Helper\Data
     */
34 35
    protected $_adyenHelper;

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

41 42 43
    /**
     * @var \Magento\Sales\Model\Order
     */
44 45 46 47 48 49 50
    protected $_order;

    /**
     * @var \Magento\Sales\Model\Order\Status\HistoryFactory
     */
    protected $_orderHistoryFactory;

51 52 53
    /**
     * @var \Magento\Checkout\Model\Session
     */
54 55
    protected $_session;

rikterbeek's avatar
rikterbeek committed
56 57 58 59 60
    /**
     * @var \Adyen\Payment\Logger\AdyenLogger
     */
    protected $_adyenLogger;

61 62
    /**
     * @param \Magento\Framework\App\Action\Context $context
63 64 65 66
     * @param \Adyen\Payment\Helper\Data $adyenHelper
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Sales\Model\Order\Status\HistoryFactory $orderHistoryFactory
     * @param \Magento\Checkout\Model\Session $session
rikterbeek's avatar
rikterbeek committed
67
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
68 69 70 71 72 73
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Adyen\Payment\Helper\Data $adyenHelper,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Sales\Model\Order\Status\HistoryFactory $orderHistoryFactory,
rikterbeek's avatar
rikterbeek committed
74 75
        \Magento\Checkout\Model\Session $session,
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger
76 77 78 79 80
    ) {
        $this->_adyenHelper = $adyenHelper;
        $this->_orderFactory = $orderFactory;
        $this->_orderHistoryFactory = $orderHistoryFactory;
        $this->_session = $session;
rikterbeek's avatar
rikterbeek committed
81
        $this->_adyenLogger = $adyenLogger;
82 83 84 85 86 87
        parent::__construct($context);
    }

    public function execute()
    {
        $response = $this->getRequest()->getParams();
88
        $this->_adyenLogger->addAdyenResult(print_r($response, true));
rikterbeek's avatar
rikterbeek committed
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        $result = $this->validateResponse($response);

        if ($result) {
            $session = $this->_session;
            $session->getQuote()->setIsActive(false)->save();
            $this->_redirect('checkout/onepage/success');
        } else {
            $this->_cancel($response);
            $this->_redirect('checkout/cart');
        }
    }

    protected function _cancel($response)
    {
        $session = $this->_session;

        // restore the quote
        $session->restoreQuote();

        $order = $this->_order;

111
        $this->_adyenHelper->cancelOrder($order);
112 113 114 115 116 117 118 119 120 121 122 123 124

        if(isset($response['authResult']) && $response['authResult'] == \Adyen\Payment\Model\Notification::CANCELLED) {
            $this->messageManager->addError(__('You have cancelled the order. Please try again'));
        } else {
            $this->messageManager->addError(__('Your payment failed, Please try again later'));
        }

    }

    protected function validateResponse($response)
    {
        $result = true;

125
        $this->_adyenLogger->addAdyenResult('Processing ResultUrl');
126 127 128
        $storeId = null;

        if (empty($response)) {
129
            $this->_adyenLogger->addAdyenResult('Response is empty, please check your webserver that the result url accepts parameters');
130 131 132 133
            throw new \Magento\Framework\Exception\LocalizedException(__('Response is empty, please check your webserver that the result url accepts parameters'));
        }

        // Log the results in log file and adyen_debug table
134
        $this->_adyenLogger->addAdyenResult($response);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168


        // authenticate result url
        $authStatus = $this->_authenticate($response);
        if (!$authStatus) {
            throw new \Magento\Framework\Exception\LocalizedException(__('ResultUrl authentification failure'));
        }

        $incrementId = $response['merchantReference'];

        if($incrementId) {
            $order = $this->_getOrder($incrementId);
            if ($order->getId()) {

                $this->_eventManager->dispatch('adyen_payment_process_resulturl_before', [
                    'order' => $order,
                    'adyen_response' => $response
                ]);
                if (isset($response['handled'])) {
                    return;
                }

                // set StoreId for retrieving debug log setting
                $storeId = $order->getStoreId();

                // update the order
                $result = $this->_validateUpdateOrder($order, $response);

                $this->_eventManager->dispatch('adyen_payment_process_resulturl_after', [
                    'order' => $order,
                    'adyen_response' => $response
                ]);

            } else {
169
                throw new \Magento\Framework\Exception\LocalizedException(__('Order does not exists with increment_id: %1', $incrementId));
170 171
            }
        } else {
rikterbeek's avatar
rikterbeek committed
172
            throw new \Magento\Framework\Exception\LocalizedException(__('Empty merchantReference'));
173 174 175 176 177 178 179 180 181 182 183 184
        }
        return $result;
    }

    /**
     * @param $order
     * @param $params
     */
    protected function _validateUpdateOrder($order, $response)
    {
        $result = false;

185
        $this->_adyenLogger->addAdyenResult('Updating the order');
186 187 188 189 190

        $authResult = $response['authResult'];
        $paymentMethod = isset($response['paymentMethod']) ? trim($response['paymentMethod']) : '';
        $pspReference = isset($response['pspReference']) ? trim($response['pspReference']) : '';

191
        $type = 'Adyen Result URL response:';
192 193 194 195 196 197 198 199 200 201 202
        $comment = __('%1 <br /> authResult: %2 <br /> pspReference: %3 <br /> paymentMethod: %4', $type, $authResult, $pspReference, $paymentMethod);

        $history = $this->_orderHistoryFactory->create()
            //->setStatus($status)
            ->setComment($comment)
            ->setEntityName('order')
            ->setOrder($order)
        ;

        $history->save();

203 204 205
        // needed  becuase then we need to save $order objects
        $order->setAdyenResulturlEventCode($authResult);

206 207 208 209 210 211 212

        switch ($authResult) {

            case \Adyen\Payment\Model\Notification::AUTHORISED:
            case \Adyen\Payment\Model\Notification::PENDING:
                // do nothing wait for the notification
                $result = true;
213
                $this->_adyenLogger->addAdyenResult('Do nothing wait for the notification');
214 215
                break;
            case \Adyen\Payment\Model\Notification::CANCELLED:
216
                $this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
217 218 219
                $result = false;
                break;
            case \Adyen\Payment\Model\Notification::REFUSED:
220 221
                // if refused there will be a AUTHORIZATION : FALSE notification send only exception is idea
                $this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
222 223 224 225
                $result = false;
                break;
            case \Adyen\Payment\Model\Notification::ERROR:
                //attempt to hold/cancel
226
                $this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
227 228 229
                $result = false;
                break;
            default:
230
                $this->_adyenLogger->addAdyenResult('This event is not supported: ' . $authResult);
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 257 258 259 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
                $result = false;
                break;
        }

        return $result;
    }


    /**
     * @desc Authenticate using sha1 Merchant signature
     * @see success Action during checkout
     * @param Varien_Object $response
     */
    protected function _authenticate($response) {

        $hmacKey = $this->_adyenHelper->getHmac();

        // do not include the merchantSig in the merchantSig calculation
        $merchantSigNotification = $response['merchantSig'];
        unset($response['merchantSig']);

        // Sort the array by key using SORT_STRING order
        ksort($response, SORT_STRING);

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

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


        if (strcmp($merchantSig, $merchantSigNotification) === 0) {
            return true;
        }
        return false;
    }

    /*
   * @desc The character escape function is called from the array_map function in _signRequestParams
   * $param $val
   * return string
   */
    protected function escapeString($val)
    {
        return str_replace(':','\\:',str_replace('\\','\\\\',$val));
    }

    protected function _getOrder($incrementId)
    {
        if (!$this->_order) {
            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
        }
        return $this->_order;
    }

}