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.1 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
<?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;

use Magento\Payment\Gateway\Request\BuilderInterface;
use Adyen\Payment\Observer\AdyenHppDataAssignObserver;

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

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

    /**
Jeroen's avatar
Jeroen committed
42
     * @var \Magento\Quote\Api\CartRepositoryInterface
43
     */
Jeroen's avatar
Jeroen committed
44
    private $cartRepository;
45 46

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

    /**
     * @param \Adyen\Payment\Helper\Data $adyenHelper
53
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
Jeroen's avatar
Jeroen committed
54
     * @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
55
     * @param \Adyen\Payment\Model\Gender $gender
56
     */
57
    public function __construct(
Jeroen's avatar
Jeroen committed
58 59
        \Adyen\Payment\Helper\Data $adyenHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
60 61
        \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
        \Adyen\Payment\Model\Gender $gender
Jeroen's avatar
Jeroen committed
62
    ) {
63 64
        $this->adyenHelper = $adyenHelper;
        $this->storeManager = $storeManager;
Jeroen's avatar
Jeroen committed
65
        $this->cartRepository = $cartRepository;
66
        $this->gender = $gender;
67
    }
68

69 70 71 72 73 74 75 76 77 78 79 80
    /**
     * @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();
        $order = $payment->getOrder();
        $storeId = $order->getStoreId();
        $requestBody = [];
81

82 83
        // do not send email
        $order->setCanSendNewEmailFlag(false);
84

85 86 87
        $requestBodyPaymentMethod['type'] = $payment->getAdditionalInformation(
            AdyenHppDataAssignObserver::BRAND_CODE
        );
88

89 90
        // Additional data for payment methods with issuer list
        if ($payment->getAdditionalInformation(AdyenHppDataAssignObserver::ISSUER_ID)) {
91 92 93
            $requestBodyPaymentMethod['issuer'] = $payment->getAdditionalInformation(
                AdyenHppDataAssignObserver::ISSUER_ID
            );
94
        }
95

96 97 98
        $requestBody['returnUrl'] = $this->storeManager->getStore()->getBaseUrl(
                \Magento\Framework\UrlInterface::URL_TYPE_LINK
            ) . 'adyen/process/result';
99

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

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

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

113 114 115 116 117 118 119 120 121
        // Additional data for open invoice payment
        if ($payment->getAdditionalInformation("gender")) {
            $order->setCustomerGender(
                $this->gender->getMagentoGenderFromAdyenGender(
                    $payment->getAdditionalInformation("gender")
                )
            );
            $requestBodyPaymentMethod['personalDetails']['gender'] = $payment->getAdditionalInformation("gender");
        }
122

123 124
        if ($payment->getAdditionalInformation("dob")) {
            $order->setCustomerDob($payment->getAdditionalInformation("dob"));
125

126 127 128 129 130
            $requestBodyPaymentMethod['personalDetails']['dateOfBirth'] = $this->adyenHelper->formatDate(
                $payment->getAdditionalInformation("dob"),
                'Y-m-d'
            );
        }
131

132 133 134 135 136 137
        if ($payment->getAdditionalInformation("telephone")) {
            $order->getBillingAddress()->setTelephone($payment->getAdditionalInformation("telephone"));
            $requestBodyPaymentMethod['personalDetails']['telephoneNumber'] = $payment->getAdditionalInformation(
                "telephone"
            );
        }
138

139
        if ($payment->getAdditionalInformation("ssn")) {
140 141
            $requestBodyPaymentMethod['personalDetails']['socialSecurityNumber'] =
                $payment->getAdditionalInformation("ssn");
142 143
        }

144 145
        // Additional data for sepa direct debit
        if ($payment->getAdditionalInformation("ownerName")) {
146
            $requestBodyPaymentMethod['sepa.ownerName'] = $payment->getAdditionalInformation("ownerName");
147
        }
148

149
        if ($payment->getAdditionalInformation("ibanNumber")) {
150
            $requestBodyPaymentMethod['sepa.ibanNumber'] = $payment->getAdditionalInformation("ibanNumber");
151
        }
152

153 154 155 156 157
        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
158 159 160
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            )
        ) {
161
            $openInvoiceFields = $this->getOpenInvoiceData($order);
162
            $requestBody = array_merge($requestBody, $openInvoiceFields);
163
        }
164

165 166 167 168
        // Ratepay specific Fingerprint
        if ($payment->getAdditionalInformation("df_value") && $this->adyenHelper->isPaymentMethodRatepayMethod(
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            )) {
169
            $requestBody['deviceFingerprint'] = $payment->getAdditionalInformation("df_value");
170 171
        }

alexandros's avatar
alexandros committed
172 173
        //Boleto data
        if ($payment->getAdditionalInformation("social_security_number")) {
174
            $requestBody['socialSecurityNumber'] = $payment->getAdditionalInformation("social_security_number");
alexandros's avatar
alexandros committed
175 176 177
        }

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

181 182
        if ($payment->getAdditionalInformation("lastname")) {
            $requestBody['shopperName']['lastName'] = $payment->getAdditionalInformation("lastname");
alexandros's avatar
alexandros committed
183 184
        }

185
        if ($payment->getMethod() == \Adyen\Payment\Model\Ui\AdyenBoletoConfigProvider::CODE) {
alexandros's avatar
alexandros committed
186 187 188 189
            $boletoTypes = $this->adyenHelper->getAdyenBoletoConfigData('boletotypes');
            $boletoTypes = explode(',', $boletoTypes);

            if (count($boletoTypes) == 1) {
190
                $requestBody['selectedBrand'] = $boletoTypes[0];
191
                $requestBodyPaymentMethod['type'] = $boletoTypes[0];
alexandros's avatar
alexandros committed
192
            } else {
193
                $requestBody['selectedBrand'] = $payment->getAdditionalInformation("boleto_type");
194
                $requestBodyPaymentMethod['type'] = $payment->getAdditionalInformation("boleto_type");
alexandros's avatar
alexandros committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
            }

            $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")
                )
            );

211
            $requestBody['deliveryDate'] = $deliveryDate;
alexandros's avatar
alexandros committed
212

213 214
            $order->setCanSendNewEmailFlag(true);
        }
215

216
        $requestBody['paymentMethod'] = $requestBodyPaymentMethod;
217
        $request['body'] = $requestBody;
218

alexandros's avatar
alexandros committed
219 220
        return $request;
    }
221

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

Jeroen's avatar
Jeroen committed
235 236 237
        /** @var \Magento\Quote\Model\Quote $cart */
        $cart = $this->cartRepository->get($order->getQuoteId());
        $currency = $cart->getCurrency();
238
        $discountAmount = 0;
239

Jeroen's avatar
Jeroen committed
240
        foreach ($cart->getAllVisibleItems() as $item) {
attilak's avatar
attilak committed
241
            $numberOfItems = (int)$item->getQty();
242

243 244
            // Summarize the discount amount item by item
            $discountAmount += $item->getDiscountAmount();
245

attilak's avatar
attilak committed
246
            $formattedPriceExcludingTax = $this->adyenHelper->formatAmount($item->getPrice(), $currency);
247

attilak's avatar
attilak committed
248 249
            $taxAmount = $item->getPrice() * ($item->getTaxPercent() / 100);
            $formattedTaxAmount = $this->adyenHelper->formatAmount($taxAmount, $currency);
250
            $formattedTaxPercentage = $item->getTaxPercent() * 100;
251

252
            $formFields['lineItems'][] = [
attilak's avatar
attilak committed
253 254
                'id' => $item->getId(),
                'itemId' => $item->getId(),
attilak's avatar
attilak committed
255
                'amountExcludingTax' => $formattedPriceExcludingTax,
256
                'taxAmount' => $formattedTaxAmount,
257
                'description' => $item->getName(),
attilak's avatar
attilak committed
258
                'quantity' => $numberOfItems,
259
                'taxCategory' => $item->getProduct()->getAttributeText('tax_class_id'),
260
                'taxPercentage' => $formattedTaxPercentage
261 262
            ];
        }
263

264 265
        // Discount cost
        if ($discountAmount != 0) {
266 267
            $description = __('Discount');
            $itemAmount = -$this->adyenHelper->formatAmount($discountAmount, $currency);
268 269 270 271 272
            $itemVatAmount = "0";
            $itemVatPercentage = "0";
            $numberOfItems = 1;

            $formFields['lineItems'][] = [
273
                'id' => 'Discount',
274 275 276 277 278 279 280 281
                'amountExcludingTax' => $itemAmount,
                'taxAmount' => $itemVatAmount,
                'description' => $description,
                'quantity' => $numberOfItems,
                'taxCategory' => 'None',
                'taxPercentage' => $itemVatPercentage
            ];
        }
282

283
        // Shipping cost
284 285 286 287 288 289 290 291 292
        if ($cart->getShippingAddress()->getShippingAmount() > 0 || $cart->getShippingAddress()->getShippingTaxAmount(
            ) > 0) {
            $priceExcludingTax = $cart->getShippingAddress()->getShippingAmount() - $cart->getShippingAddress(
                )->getShippingTaxAmount();

            $formattedTaxAmount = $this->adyenHelper->formatAmount(
                $cart->getShippingAddress()->getShippingTaxAmount(),
                $currency
            );
293

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

296 297 298
            $formattedTaxPercentage = 0;

            if ($priceExcludingTax !== 0) {
299 300
                $formattedTaxPercentage = $cart->getShippingAddress()->getShippingTaxAmount(
                    ) / $priceExcludingTax * 100 * 100;
301
            }
302

303
            $formFields['lineItems'][] = [
attilak's avatar
attilak committed
304
                'itemId' => 'shippingCost',
attilak's avatar
attilak committed
305
                'amountExcludingTax' => $formattedPriceExcludingTax,
306
                'taxAmount' => $formattedTaxAmount,
307 308
                'description' => $order->getShippingDescription(),
                'quantity' => 1,
309
                'taxPercentage' => $formattedTaxPercentage
310 311
            ];
        }
312

313 314
        return $formFields;
    }
315
}