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

AdyenHppConfigProvider.php 13.2 KB
Newer Older
1 2
<?php
/**
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * 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>
22
 */
23

24 25 26 27
namespace Adyen\Payment\Model;

use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Payment\Helper\Data as PaymentHelper;
28
use Magento\Directory\Helper\Data;
29 30 31 32

class AdyenHppConfigProvider implements ConfigProviderInterface
{

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    /**
     * @var \Magento\Framework\App\State
     */
    protected $_appState;

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

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var PaymentHelper
     */
    protected $_paymentHelper;

    /**
     * @var \Magento\Framework\Locale\ResolverInterface
     */
    protected $_localeResolver;

    /**
     * @var \Adyen\Payment\Helper\Data
     */
    protected $_adyenHelper;

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

68 69 70 71 72
    /**
     * @var AdyenGenericConfig
     */
    protected $_genericConfig;

73
    /**
74
     * @var \Magento\Framework\App\Config\ScopeConfigInterface $config
75
     */
76
    protected $_config;
77 78 79 80 81 82 83 84 85 86 87 88 89 90

    /**
     * @var string[]
     */
    protected $methodCodes = [
        'adyen_hpp'
    ];

    /**
     * @var \Magento\Payment\Model\Method\AbstractMethod[]
     */
    protected $methods = [];

    /**
91 92 93
     * @param \Magento\Framework\Model\Context $context
     * @param \Magento\Checkout\Model\Session $session
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
94
     * @param PaymentHelper $paymentHelper
95 96
     * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
97
     * @param \Adyen\Payment\Helper\Data $adyenHelper
98 99
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
     * @param AdyenGenericConfig $genericConfig
100 101
     */
    public function __construct(
102 103 104 105 106 107 108
        \Magento\Framework\Model\Context $context,
        \Magento\Checkout\Model\Session $session,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        PaymentHelper $paymentHelper,
        \Magento\Framework\Locale\ResolverInterface $localeResolver,
        \Magento\Framework\App\Config\ScopeConfigInterface $config,
        \Adyen\Payment\Helper\Data $adyenHelper,
109 110
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
        \Adyen\Payment\Model\AdyenGenericConfig $genericConfig
111
    ) {
112 113 114 115 116 117 118 119
        $this->_appState = $context->getAppState();
        $this->_session = $session;
        $this->_storeManager = $storeManager;
        $this->_paymentHelper = $paymentHelper;
        $this->_localeResolver = $localeResolver;
        $this->_config = $config;
        $this->_adyenHelper = $adyenHelper;
        $this->_adyenLogger = $adyenLogger;
120
        $this->_genericConfig = $genericConfig;
121 122

        foreach ($this->methodCodes as $code) {
123
            $this->methods[$code] = $this->_paymentHelper->getMethodInstance($code);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        }
    }


    public function getConfig()
    {
        $config = [
            'payment' => [
                'adyenHpp' => [
                ]
            ]
        ];
        foreach ($this->methodCodes as $code) {
            if ($this->methods[$code]->isAvailable()) {
                $config['payment']['adyenHpp']['redirectUrl'][$code] = $this->getMethodRedirectUrl($code);
139 140

                // get payment methods
141

142
                $config['payment'] ['adyenHpp']['paymentMethods'] = $this->getAdyenHppPaymentMethods();
143 144
            }
        }
145 146 147 148

        $paymentMethodSelectionOnAdyen = $this->_adyenHelper->getAdyenHppConfigDataFlag('payment_selection_on_adyen');
        $config['payment'] ['adyenHpp']['isPaymentMethodSelectionOnAdyen'] = $paymentMethodSelectionOnAdyen;

149 150 151 152 153 154 155 156 157 158 159 160 161 162
        return $config;
    }

    /**
     * Return redirect URL for method
     *
     * @param string $code
     * @return mixed
     */
    protected function getMethodRedirectUrl($code)
    {
        return $this->methods[$code]->getCheckoutRedirectUrl();
    }

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

    public function getAdyenHppPaymentMethods()
    {
        $paymentMethods = null;

        // is admin?
        if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) {
            //retrieve storeId from quote
            $store = $this->_session->getQuote()->getStore();
        } else {
            $store = $this->_storeManager->getStore();
        }

        // is adyen HPP enabled ?
        $hppActive = $this->methods['adyen_hpp']->isAvailable();

        if($hppActive) {
            $paymentMethods = $this->_addHppMethodsToConfig($store);
        }

        return $paymentMethods;
    }

    protected function _addHppMethodsToConfig($store)
    {
        $paymentMethods = [];

190 191 192
        $ccEnabled = $this->_config->getValue('payment/'.\Adyen\Payment\Model\Method\Cc::METHOD_CODE.'/active');
        $ccTypes = array_keys($this->_adyenHelper->getCcTypesAltData());

193
        foreach ($this->_fetchHppMethods($store) as $methodCode => $methodData) {
194 195 196 197 198 199 200

            // skip payment methods if it is a creditcard that is enabled in adyen_cc
            if ($ccEnabled
                && in_array($methodCode, $ccTypes)) {
                continue;
            }

201 202 203 204 205 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
            $paymentMethods[$methodCode] = $methodData;
        }

        return $paymentMethods;
    }

    protected function _fetchHppMethods($store)
    {
        $skinCode = $this->_adyenHelper->getAdyenHppConfigData('skin_code');
        $merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData('merchant_account');

        if (!$skinCode || !$merchantAccount) {
            return array();
        }

        $adyFields = array(
            "paymentAmount"     => (int) $this->_adyenHelper->formatAmount($this->_getCurrentPaymentAmount(), $this->_getCurrentCurrencyCode($store)),
            "currencyCode"      => $this->_getCurrentCurrencyCode($store),
            "merchantReference" => "Get Payment methods",
            "skinCode"          => $skinCode,
            "merchantAccount"   => $merchantAccount,
            "sessionValidity"   => date(
                DATE_ATOM,
                mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y"))
            ),
            "countryCode"       => $this->_getCurrentCountryCode($store),
            "shopperLocale"     => $this->_getCurrentLocaleCode($store)
        );

        $responseData = $this->_getDirectoryLookupResponse($adyFields, $store);

        $paymentMethods = array();
        if(isset($responseData['paymentMethods'])) {
            foreach ($responseData['paymentMethods'] as $paymentMethod) {

                $paymentMethodCode = $paymentMethod['brandCode'];
                $paymentMethod = $this->_fieldMapPaymentMethod($paymentMethod);
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

                // add icon location in result
                if($this->_genericConfig->showLogos()) {
                    $asset = $this->_genericConfig->createAsset('Adyen_Payment::images/logos/' . $paymentMethodCode . '.png');

                    $placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset);

                    $icon = null;
                    if ($placeholder) {
                        list($width, $height) = getimagesize($asset->getSourceFile());
                        $icon = [
                            'url' => $asset->getUrl(),
                            'width' => $width,
                            'height' => $height
                        ];
                    }

                    $paymentMethod['icon'] = $icon;
                }

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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
                $paymentMethods[$paymentMethodCode] = $paymentMethod;
            }
        }

        return $paymentMethods;
    }

    /**
     * @return bool|int
     */
    protected function _getCurrentPaymentAmount()
    {
        if (($grandTotal = $this->_getQuote()->getGrandTotal()) > 0) {
            return $grandTotal;
        }
        return 10;
    }

    /**
     * @return string
     */
    protected function _getCurrentCurrencyCode($store)
    {
        return $this->_getQuote()->getQuoteCurrencyCode() ?: $store->getBaseCurrencyCode();
    }

    /**
     * @return string
     */
    protected function _getCurrentCountryCode($store)
    {

        // if fixed countryCode is setup in config use this
        $countryCode = $this->_adyenHelper->getAdyenHppConfigData('country_code', $store->getId());

        if($countryCode != "") {
            return $countryCode;
        }

        if ($country = $this->_getQuote()->getBillingAddress()->getCountry()) {
            return $country;
        }

        $defaultCountry = $this->_config->getValue(
            \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORES,
            $store->getCode()
        );

        if($defaultCountry) {
            return $defaultCountry;
        }
rikterbeek's avatar
rikterbeek committed
310 311

        return "";
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
    }

    /**
     * @return string
     */
    protected function _getCurrentLocaleCode($store)
    {
        $localeCode = $this->_adyenHelper->getAdyenAbstractConfigData('shopper_locale', $store->getId());
        if($localeCode != "") {
            return $localeCode;
        }

        $locale = $this->_localeResolver->getLocale();
        if($locale) {
            return $locale;
        }

        // should have the vulue if not fall back to default
        $localeCode = $this->_config->getValue(
            Data::XML_PATH_DEFAULT_LOCALE,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORES,
            $store->getCode()
        );

        return $localeCode;
    }

    protected $_fieldMapPaymentMethod = array(
        'name' => 'title'
    );

    protected function _fieldMapPaymentMethod($paymentMethod)
    {
        foreach ($this->_fieldMapPaymentMethod as $field => $newField) {
            if (isset($paymentMethod[$field])) {
                $paymentMethod[$newField] = $paymentMethod[$field];
                unset($paymentMethod[$field]);
            }
        }
        return $paymentMethod;
    }

    protected function _getDirectoryLookupResponse($requestParams, $store)
    {
        $cacheKey = $this->_getCacheKeyForRequest($requestParams, $store);

        // initialize the adyen client
        $client = new \Adyen\Client();

        if($this->_adyenHelper->isDemoMode()) {
362
            $client->setEnvironment(\Adyen\Environment::TEST);
363
        } else {
364
            $client->setEnvironment(\Adyen\Environment::LIVE);
365 366 367 368 369
        }

        // connect to magento log
        $client->setLogger($this->_adyenLogger);

rikterbeek's avatar
rikterbeek committed
370 371
        $hmacKey = $this->_adyenHelper->getHmac();

372 373 374
        // create and add signature
        $requestParams["merchantSig"] = \Adyen\Util\Util::calculateSha256Signature($hmacKey, $requestParams);

375
        // initialize service
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
        $service = new \Adyen\Service\DirectoryLookup($client);

        try {
            $responseData =  $service->directoryLookup($requestParams);
        }catch (Exception $e) {
            $this->_adyenLogger->error("The Directory Lookup response is empty check your Adyen configuration in Magento.");
            // return empty result
            return array();
        }

        // save result in cache
//        Mage::app()->getCache()->save(
//            serialize($responseData),
//            $cacheKey,
//            array(Mage_Core_Model_Config::CACHE_TAG),
//            60 * 60 * 6
//        );

        return $responseData;
    }

    protected $_cacheParams = array(
        'currencyCode',
        'merchantReference',
        'skinCode',
        'merchantAccount',
        'countryCode',
        'shopperLocale',
    );

    protected function _getCacheKeyForRequest($requestParams, $store)
    {
        $cacheParams = array();
        $cacheParams['store'] = $store->getId();
        foreach ($this->_cacheParams as $paramKey) {
            if (isset($requestParams[$paramKey])) {
                $cacheParams[$paramKey] = $requestParams[$paramKey];
            }
        }

        return md5(implode('|', $cacheParams));
    }

    protected function _getQuote()
    {
        return $this->_session->getQuote();
    }

424 425 426 427 428 429 430 431 432 433 434 435 436 437

    /**
     * Create a file asset that's subject of fallback system
     *
     * @param string $fileId
     * @param array $params
     * @return \Magento\Framework\View\Asset\File
     */
    protected function _createAsset($fileId, array $params = [])
    {
        $params = array_merge(['_secure' => $this->request->isSecure()], $params);
        return $this->assetRepo->createAsset($fileId, $params);
    }

438
}