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

CheckoutDataBuilder.php 12.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
<?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\Gateway\Request;

26

27
use Adyen\Payment\Helper\ChargedCurrency;
28
use Adyen\Payment\Observer\AdyenCcDataAssignObserver;
29 30 31 32 33
use Magento\Payment\Gateway\Request\BuilderInterface;
use Adyen\Payment\Observer\AdyenHppDataAssignObserver;

class CheckoutDataBuilder implements BuilderInterface
{
34 35 36 37 38 39 40 41 42 43 44
    /**
     * @var \Adyen\Payment\Helper\Data
     */
    private $adyenHelper;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    /**
Jeroen's avatar
Jeroen committed
45
     * @var \Magento\Quote\Api\CartRepositoryInterface
46
     */
Jeroen's avatar
Jeroen committed
47
    private $cartRepository;
48 49

    /**
50 51 52 53
     * @var \Adyen\Payment\Model\Gender
     */
    private $gender;

54 55 56 57 58
    /**
     * @var ChargedCurrency
     */
    private $chargedCurrency;

59 60
    /**
     * @param \Adyen\Payment\Helper\Data $adyenHelper
61
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
Jeroen's avatar
Jeroen committed
62
     * @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
63
     * @param \Adyen\Payment\Model\Gender $gender
64
     */
65
    public function __construct(
Jeroen's avatar
Jeroen committed
66 67
        \Adyen\Payment\Helper\Data $adyenHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
68
        \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
69 70
        \Adyen\Payment\Model\Gender $gender,
        ChargedCurrency $chargedCurrency
Jeroen's avatar
Jeroen committed
71
    ) {
72 73
        $this->adyenHelper = $adyenHelper;
        $this->storeManager = $storeManager;
Jeroen's avatar
Jeroen committed
74
        $this->cartRepository = $cartRepository;
75
        $this->gender = $gender;
76
        $this->chargedCurrency = $chargedCurrency;
77
    }
78

79 80 81 82 83 84 85 86 87
    /**
     * @param array $buildSubject
     * @return mixed
     */
    public function build(array $buildSubject)
    {
        /** @var \Magento\Payment\Gateway\Data\PaymentDataObject $paymentDataObject */
        $paymentDataObject = \Magento\Payment\Gateway\Helper\SubjectReader::readPayment($buildSubject);
        $payment = $paymentDataObject->getPayment();
88
        /** @var \Magento\Sales\Model\Order $order */
89 90
        $order = $payment->getOrder();
        $storeId = $order->getStoreId();
91 92 93

        // Initialize the request body with the validated state data
        $requestBody = $payment->getAdditionalInformation(AdyenCcDataAssignObserver::STATE_DATA);
94

95 96
        // do not send email
        $order->setCanSendNewEmailFlag(false);
97

98 99
        $requestBody['returnUrl'] = $this->storeManager->getStore()->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_LINK
100
            ) . 'adyen/transparent/redirect?merchantReference=' . $order->getIncrementId();
101

attilak's avatar
typo  
attilak committed
102
        // Additional data for ACH
attilak's avatar
attilak committed
103
        if ($payment->getAdditionalInformation("bankAccountNumber")) {
104
            $requestBody['bankAccount']['bankAccountNumber'] = $payment->getAdditionalInformation("bankAccountNumber");
attilak's avatar
attilak committed
105 106 107
        }

        if ($payment->getAdditionalInformation("bankLocationId")) {
108
            $requestBody['bankAccount']['bankLocationId'] = $payment->getAdditionalInformation("bankLocationId");
attilak's avatar
attilak committed
109 110 111
        }

        if ($payment->getAdditionalInformation("bankAccountOwnerName")) {
112
            $requestBody['bankAccount']['ownerName'] = $payment->getAdditionalInformation("bankAccountOwnerName");
attilak's avatar
attilak committed
113 114
        }

115 116 117 118 119
        if ($this->adyenHelper->isPaymentMethodOpenInvoiceMethod(
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            ) || $this->adyenHelper->isPaymentMethodAfterpayTouchMethod(
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            ) || $this->adyenHelper->isPaymentMethodOneyMethod(
attilak's avatar
attilak committed
120 121 122
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            )
        ) {
123
            $openInvoiceFields = $this->getOpenInvoiceData($order);
124
            $requestBody = array_merge($requestBody, $openInvoiceFields);
125
        }
126

127 128 129 130
        // Ratepay specific Fingerprint
        if ($payment->getAdditionalInformation("df_value") && $this->adyenHelper->isPaymentMethodRatepayMethod(
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            )) {
131
            $requestBody['deviceFingerprint'] = $payment->getAdditionalInformation("df_value");
132 133
        }

alexandros's avatar
alexandros committed
134 135
        //Boleto data
        if ($payment->getAdditionalInformation("social_security_number")) {
136
            $requestBody['socialSecurityNumber'] = $payment->getAdditionalInformation("social_security_number");
alexandros's avatar
alexandros committed
137 138 139
        }

        if ($payment->getAdditionalInformation("firstname")) {
140
            $requestBody['shopperName']['firstName'] = $payment->getAdditionalInformation("firstname");
alexandros's avatar
alexandros committed
141 142
        }

143 144
        if ($payment->getAdditionalInformation("lastname")) {
            $requestBody['shopperName']['lastName'] = $payment->getAdditionalInformation("lastname");
alexandros's avatar
alexandros committed
145 146
        }

147
        if ($payment->getMethod() == \Adyen\Payment\Model\Ui\AdyenBoletoConfigProvider::CODE) {
alexandros's avatar
alexandros committed
148 149 150 151
            $boletoTypes = $this->adyenHelper->getAdyenBoletoConfigData('boletotypes');
            $boletoTypes = explode(',', $boletoTypes);

            if (count($boletoTypes) == 1) {
152
                $requestBody['selectedBrand'] = $boletoTypes[0];
153
                $requestBodyPaymentMethod['type'] = $boletoTypes[0];
alexandros's avatar
alexandros committed
154
            } else {
155
                $requestBody['selectedBrand'] = $payment->getAdditionalInformation("boleto_type");
156
                $requestBodyPaymentMethod['type'] = $payment->getAdditionalInformation("boleto_type");
alexandros's avatar
alexandros committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
            }

            $deliveryDays = (int)$this->adyenHelper->getAdyenBoletoConfigData("delivery_days", $storeId);
            $deliveryDays = (!empty($deliveryDays)) ? $deliveryDays : 5;
            $deliveryDate = date(
                "Y-m-d\TH:i:s ",
                mktime(
                    date("H"),
                    date("i"),
                    date("s"),
                    date("m"),
                    date("j") + $deliveryDays,
                    date("Y")
                )
            );

173
            $requestBody['deliveryDate'] = $deliveryDate;
alexandros's avatar
alexandros committed
174

175 176
            $order->setCanSendNewEmailFlag(true);
        }
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
        // if installments is set and card type is credit card add it into the request
        $numberOfInstallments = $payment->getAdditionalInformation(
            AdyenCcDataAssignObserver::NUMBER_OF_INSTALLMENTS
        ) ?: 0;
        $comboCardType = $payment->getAdditionalInformation(AdyenCcDataAssignObserver::COMBO_CARD_TYPE) ?: 'credit';
        if ($numberOfInstallments > 0) {
            $requestBody['installments']['value'] = $numberOfInstallments;
        }
        // if card type is debit then change the issuer type and unset the installments field
        if ($comboCardType == 'debit') {
            if ($selectedDebitBrand = $this->getSelectedDebitBrand($payment->getAdditionalInformation('cc_type'))) {
                $requestBody['additionalData']['overwriteBrand'] = true;
                $requestBody['selectedBrand'] = $selectedDebitBrand;
                $requestBody['paymentMethod']['type'] = $selectedDebitBrand;
            }
            unset($requestBody['installments']);
        }

        if ($this->adyenHelper->isCreditCardThreeDS2Enabled($storeId)) {
            $requestBody['additionalData']['allow3DS2'] = true;
        }

        $requestBody['origin'] = $this->adyenHelper->getOrigin($storeId);
        $requestBody['channel'] = 'web';

        if (isset($requestBodyPaymentMethod)) {
            $requestBody['paymentMethod'] = $requestBodyPaymentMethod;
        }

207
        $request['body'] = $requestBody;
208

alexandros's avatar
alexandros committed
209 210
        return $request;
    }
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    /**
     * @param string $brand
     * @return string
     */
    private function getSelectedDebitBrand($brand)
    {
        if ($brand == 'VI') {
            return 'electron';
        }
        if ($brand == 'MC') {
            return 'maestro';
        }
        return null;
    }

227
    /**
Jeroen's avatar
Jeroen committed
228 229
     * @param \Magento\Sales\Model\Order $order
     *
230
     * @return array
Jeroen's avatar
Jeroen committed
231 232
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     *
233
     */
Jeroen's avatar
Jeroen committed
234
    protected function getOpenInvoiceData($order): array
235 236 237 238
    {
        $formFields = [
            'lineItems' => []
        ];
239

Jeroen's avatar
Jeroen committed
240 241
        /** @var \Magento\Quote\Model\Quote $cart */
        $cart = $this->cartRepository->get($order->getQuoteId());
242 243
        $amountCurrency = $this->chargedCurrency->getOrderAmountCurrency($order);
        $currency = $amountCurrency->getCurrencyCode();
244
        $discountAmount = 0;
245

Jeroen's avatar
Jeroen committed
246
        foreach ($cart->getAllVisibleItems() as $item) {
attilak's avatar
attilak committed
247
            $numberOfItems = (int)$item->getQty();
248

249 250
            $itemAmountCurrency = $this->chargedCurrency->getQuoteItemAmountCurrency($item);

251
            // Summarize the discount amount item by item
252
            $discountAmount += $itemAmountCurrency->getDiscountAmount();
253

254 255 256 257
            $formattedPriceExcludingTax = $this->adyenHelper->formatAmount(
                $itemAmountCurrency->getAmount(),
                $itemAmountCurrency->getCurrencyCode()
            );
258

259 260 261 262
            $formattedTaxAmount = $this->adyenHelper->formatAmount(
                $itemAmountCurrency->getTaxAmount(),
                $itemAmountCurrency->getCurrencyCode()
            );
263
            $formattedTaxPercentage = $item->getTaxPercent() * 100;
264

265
            $formFields['lineItems'][] = [
attilak's avatar
attilak committed
266
                'id' => $item->getId(),
attilak's avatar
attilak committed
267
                'amountExcludingTax' => $formattedPriceExcludingTax,
268
                'taxAmount' => $formattedTaxAmount,
269
                'description' => $item->getName(),
attilak's avatar
attilak committed
270
                'quantity' => $numberOfItems,
271
                'taxCategory' => $item->getProduct()->getAttributeText('tax_class_id'),
272
                'taxPercentage' => $formattedTaxPercentage
273 274
            ];
        }
275

276 277
        // Discount cost
        if ($discountAmount != 0) {
278
            $description = __('Discount');
279
            $itemAmount = -$this->adyenHelper->formatAmount($discountAmount, $itemAmountCurrency->getCurrencyCode());
280 281 282 283 284
            $itemVatAmount = "0";
            $itemVatPercentage = "0";
            $numberOfItems = 1;

            $formFields['lineItems'][] = [
285
                'id' => 'Discount',
286 287 288 289 290 291 292 293
                'amountExcludingTax' => $itemAmount,
                'taxAmount' => $itemVatAmount,
                'description' => $description,
                'quantity' => $numberOfItems,
                'taxCategory' => 'None',
                'taxPercentage' => $itemVatPercentage
            ];
        }
294

295
        // Shipping cost
296 297 298 299 300 301
        if ($cart->getShippingAddress()->getShippingAmount() > 0 ||
            $cart->getShippingAddress()->getShippingTaxAmount() > 0
        ) {
            $shippingAmountCurrency = $this->chargedCurrency->getQuoteShippingAmountCurrency($cart);

            $priceExcludingTax = $shippingAmountCurrency->getAmount();
302 303

            $formattedTaxAmount = $this->adyenHelper->formatAmount(
304
                $shippingAmountCurrency->getTaxAmount(),
305 306
                $currency
            );
307

attilak's avatar
attilak committed
308
            $formattedPriceExcludingTax = $this->adyenHelper->formatAmount($priceExcludingTax, $currency);
309

310 311 312
            $formattedTaxPercentage = 0;

            if ($priceExcludingTax !== 0) {
313
                $formattedTaxPercentage = $shippingAmountCurrency->getTaxAmount() / $priceExcludingTax * 100 * 100;
314
            }
315

316
            $formFields['lineItems'][] = [
317
                'id' => 'shippingCost',
attilak's avatar
attilak committed
318
                'amountExcludingTax' => $formattedPriceExcludingTax,
319
                'taxAmount' => $formattedTaxAmount,
320 321
                'description' => $order->getShippingDescription(),
                'quantity' => 1,
322
                'taxPercentage' => $formattedTaxPercentage
323 324
            ];
        }
325

326 327
        return $formFields;
    }
328
}