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

PaymentMethods.php 13.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
<?php
/**
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * 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>
 */

namespace Adyen\Payment\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

/**
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class PaymentMethods extends AbstractHelper
{
    /**
     * @var \Magento\Quote\Api\CartRepositoryInterface
     */
36
    protected $quoteRepository;
37 38 39 40

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface $config
     */
41
    protected $config;
42 43 44 45

    /**
     * @var \Adyen\Payment\Helper\Data
     */
46
    protected $adyenHelper;
47 48 49 50

    /**
     * @var \Magento\Checkout\Model\Session
     */
51
    protected $session;
52

53 54 55 56
    /**
     * @var \Magento\Framework\Locale\ResolverInterface
     */
    protected $localeResolver;
57 58 59 60

    /**
     * @var \Adyen\Payment\Logger\AdyenLogger
     */
61
    protected $adyenLogger;
62 63 64 65

    /**
     * @var Repository
     */
66
    protected $assetRepo;
67 68 69 70

    /**
     * @var RequestInterface
     */
71
    protected $request;
72 73 74 75

    /**
     * @var \Magento\Framework\View\Asset\Source
     */
76
    protected $assetSource;
77

78 79 80
    /**
     * @var \Magento\Framework\View\DesignInterface
     */
81
    protected $design;
82 83 84 85

    /**
     * @var \Magento\Framework\View\Design\Theme\ThemeProviderInterface
     */
86
    protected $themeProvider;
87

88 89 90 91 92
    /**
     * @var \Magento\Quote\Model\Quote
     */
    protected $quote;

93 94
    /**
     * PaymentMethods constructor.
Rik ter Beek's avatar
Rik ter Beek committed
95
     *
96 97 98 99
     * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
     * @param Data $adyenHelper
     * @param \Magento\Checkout\Model\Session $session
100
     * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
101 102 103 104
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
     * @param \Magento\Framework\View\Asset\Repository $assetRepo
     * @param \Magento\Framework\App\RequestInterface $request
     * @param \Magento\Framework\View\Asset\Source $assetSource
105 106
     * @param \Magento\Framework\View\DesignInterface $design
     * @param \Magento\Framework\View\Design\Theme\ThemeProviderInterface $themeProvider
107 108 109 110 111 112
     */
    public function __construct(
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
        \Magento\Framework\App\Config\ScopeConfigInterface $config,
        \Adyen\Payment\Helper\Data $adyenHelper,
        \Magento\Checkout\Model\Session $session,
113
        \Magento\Framework\Locale\ResolverInterface $localeResolver,
114 115 116
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
        \Magento\Framework\View\Asset\Repository $assetRepo,
        \Magento\Framework\App\RequestInterface $request,
117 118 119
        \Magento\Framework\View\Asset\Source $assetSource,
        \Magento\Framework\View\DesignInterface $design,
        \Magento\Framework\View\Design\Theme\ThemeProviderInterface $themeProvider
120
    ) {
121 122 123 124
        $this->quoteRepository = $quoteRepository;
        $this->config = $config;
        $this->adyenHelper = $adyenHelper;
        $this->session = $session;
125
        $this->localeResolver = $localeResolver;
126 127 128 129 130 131
        $this->adyenLogger = $adyenLogger;
        $this->assetRepo = $assetRepo;
        $this->request = $request;
        $this->assetSource = $assetSource;
        $this->design = $design;
        $this->themeProvider = $themeProvider;
132 133 134 135 136 137 138 139
    }

    /**
     * {@inheritDoc}
     */
    public function getPaymentMethods($quoteId, $country = null)
    {
        // get quote from quoteId
140 141
        $quote = $this->quoteRepository->getActive($quoteId);

142 143 144 145 146 147 148 149
        // If quote cannot be found early return the empty paymentMethods array
        if (empty($quote)) {
            return [];
        }

        $this->setQuote($quote);

        $paymentMethods = $this->fetchAlternativeMethods($country);
150 151 152 153
        return $paymentMethods;
    }

    /**
154
     * @param $country
155 156
     * @return array
     */
157
    protected function fetchAlternativeMethods($country)
158
    {
159 160 161 162
        $quote = $this->getQuote();
        $store = $quote->getStore();

        $merchantAccount = $this->adyenHelper->getAdyenAbstractConfigData('merchant_account', $store->getId());
163

164
        if (!$merchantAccount) {
165 166 167
            return [];
        }

168 169
        $currencyCode = $this->getCurrentCurrencyCode($store);

170
        $adyFields = [
171
            "channel" => "Web",
172
            "merchantAccount" => $merchantAccount,
173 174
            "countryCode" => $this->getCurrentCountryCode($store, $country),
            "amount" => [
175
                "currency" => $currencyCode,
176
                "value" => $this->adyenHelper->formatAmount(
177
                    $this->getCurrentPaymentAmount(),
178
                    $currencyCode
179 180 181
                ),
            ],
            "shopperReference" => $this->getCurrentShopperReference(),
182
            "shopperLocale" => $this->adyenHelper->getCurrentLocaleCode($store->getId())
183 184
        ];

185
        $billingAddress = $quote->getBillingAddress();
186 187 188 189 190 191 192 193

        if (!empty($billingAddress)) {
            if ($customerTelephone = trim($billingAddress->getTelephone())) {
                $adyFields['telephoneNumber'] = $customerTelephone;
            }
        }

        $responseData = $this->getPaymentMethodsResponse($adyFields, $store);
194 195 196 197

        $paymentMethods = [];
        if (isset($responseData['paymentMethods'])) {
            foreach ($responseData['paymentMethods'] as $paymentMethod) {
198 199
                $paymentMethodCode = $paymentMethod['type'];
                $paymentMethod = $this->fieldMapPaymentMethod($paymentMethod);
200 201 202

                // check if payment method is an openinvoice method
                $paymentMethod['isPaymentMethodOpenInvoiceMethod'] =
203
                    $this->adyenHelper->isPaymentMethodOpenInvoiceMethod($paymentMethodCode);
204

205
                // add icon location in result
206
                if ($this->adyenHelper->showLogos()) {
207 208 209 210
                    // Fix for MAGETWO-70402 https://github.com/magento/magento2/pull/7686
                    // Explicitly setting theme
                    $themeCode = "Magento/blank";

211
                    $themeId = $this->design->getConfigurationDesignTheme(\Magento\Framework\App\Area::AREA_FRONTEND);
212
                    if (!empty($themeId)) {
213
                        $theme = $this->themeProvider->getThemeById($themeId);
214
                        if ($theme && !empty($theme->getCode())) {
215 216 217
                            $themeCode = $theme->getCode();
                        }
                    }
218 219

                    $params = [];
220 221 222 223 224 225 226 227 228 229 230 231 232 233
                    $params = array_merge(
                        [
                            'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                            '_secure' => $this->request->isSecure(),
                            'theme' => $themeCode
                        ],
                        $params
                    );

                    $asset = $this->assetRepo->createAsset(
                        'Adyen_Payment::images/logos/' .
                        $paymentMethodCode . '.png',
                        $params
                    );
234

235
                    $placeholder = $this->assetSource->findSource($asset);
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

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

        return $paymentMethods;
    }

    /**
256
     * @return float
257
     */
258
    protected function getCurrentPaymentAmount()
259
    {
260 261 262 263 264 265 266 267 268 269 270 271 272 273
        $grandTotal = $this->getQuote()->getGrandTotal();

        if (!is_numeric($grandTotal)) {
            throw new \Exception(
                sprintf(
                    'Cannot retrieve a valid grand total from quote ID: `%s`. Expected a numeric value.',
                    $this->getQuote()->getEntityId()
                )
            );
        }

        $grandTotal = (float) $grandTotal;

        if ($grandTotal > 0) {
274 275
            return $grandTotal;
        }
276 277 278 279 280 281 282 283

        throw new \Exception(
            sprintf(
                'Cannot retrieve a valid grand total from quote ID: `%s`. Expected a float > `0`, got `%f`.',
                $this->getQuote()->getEntityId(),
                $grandTotal
            )
        );
284 285 286 287 288 289
    }

    /**
     * @param $store
     * @return mixed
     */
290
    protected function getCurrentCurrencyCode($store)
291
    {
292
        return $this->getQuote()->getQuoteCurrencyCode() ?: $store->getBaseCurrencyCode();
293 294 295 296 297 298
    }

    /**
     * @param $store
     * @return int|mixed|string
     */
299
    protected function getCurrentCountryCode($store, $country)
300 301
    {
        // if fixed countryCode is setup in config use this
302
        $countryCode = $this->adyenHelper->getAdyenHppConfigData('country_code', $store->getId());
303 304 305 306 307 308 309 310 311

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

        if ($country != null) {
            return $country;
        }

312
        if ($country = $this->getQuote()->getBillingAddress()->getCountry()) {
313 314 315
            return $country;
        }

316
        $defaultCountry = $this->config->getValue(
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            \Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORES,
            $store->getCode()
        );

        if ($defaultCountry) {
            return $defaultCountry;
        }

        return "";
    }

    /**
     * @var array
     */
332
    protected $fieldMapPaymentMethod = [
333 334 335 336 337 338 339
        'name' => 'title'
    ];

    /**
     * @param $paymentMethod
     * @return mixed
     */
340
    protected function fieldMapPaymentMethod($paymentMethod)
341
    {
342
        foreach ($this->fieldMapPaymentMethod as $field => $newField) {
343 344 345 346 347 348 349 350 351 352 353 354 355 356
            if (isset($paymentMethod[$field])) {
                $paymentMethod[$newField] = $paymentMethod[$field];
                unset($paymentMethod[$field]);
            }
        }
        return $paymentMethod;
    }

    /**
     * @param $requestParams
     * @param $store
     * @return array
     * @throws \Adyen\AdyenException
     */
357
    protected function getPaymentMethodsResponse($requestParams, $store)
358 359
    {
        // initialize the adyen client
360
        $client = $this->adyenHelper->initializeAdyenClient($store->getId());
361 362

        // initialize service
363
        $service = $this->adyenHelper->createAdyenCheckoutService($client);
364 365

        try {
366
            $responseData = $service->paymentMethods($requestParams);
367
        } catch (\Adyen\AdyenException $e) {
368 369
            $this->adyenLogger->error(
                "The Payment methods response is empty check your Adyen configuration in Magento."
370 371 372 373 374 375 376 377 378
            );
            // return empty result
            return [];
        }

        return $responseData;
    }

    /**
379
     * @return \Magento\Quote\Model\Quote
380
     */
381
    protected function getQuote()
382
    {
383 384 385 386 387 388 389 390 391
        return $this->quote;
    }

    /**
     * @param \Magento\Quote\Model\Quote $quote
     */
    protected function setQuote(\Magento\Quote\Model\Quote $quote)
    {
        $this->quote = $quote;
392 393 394
    }

    /**
395
     * @return int
396
     */
397
    protected function getCurrentShopperReference()
398
    {
399
        return $this->getQuote()->getCustomerId();
400
    }
attilak's avatar
attilak committed
401 402 403 404 405 406 407

    /**
     * @return array|mixed
     * @throws \Adyen\AdyenException
     */
    public function getConnectedTerminals()
    {
408
        $storeId = $this->session->getQuote()->getStoreId();
attilak's avatar
attilak committed
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

        // initialize the adyen client
        $client = $this->adyenHelper->initializeAdyenClient($storeId, $this->adyenHelper->getPosApiKey($storeId));

        // initialize service
        $service = $this->adyenHelper->createAdyenPosPaymentService($client);

        $requestParams = [
            "merchantAccount" => $this->adyenHelper->getAdyenMerchantAccount('adyen_pos_cloud', $storeId),
        ];

        // In case the POS store id is set, provide in the request
        if (!empty($this->adyenHelper->getPosStoreId($storeId))) {
            $requestParams['store'] = $this->adyenHelper->getPosStoreId($storeId);
        }

        try {
            $responseData = $service->getConnectedTerminals($requestParams);
        } catch (\Adyen\AdyenException $e) {
            $this->adyenLogger->error(
                "The getConnectedTerminals response is empty check your Adyen configuration in Magento."
            );
            // return empty result
            return [];
        }

        return $responseData;
    }
437
}