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 11.4 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

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

	/**
	 * @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();
alexandros's avatar
alexandros committed
71
		$storeId = $order->getStoreId();
72
		$requestBody = [];
73

74 75
        // do not send email
        $order->setCanSendNewEmailFlag(false);
76

77
        $requestBody['paymentMethod']['type'] = $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE);
78

79 80
        // Additional data for payment methods with issuer list
        if ($payment->getAdditionalInformation(AdyenHppDataAssignObserver::ISSUER_ID)) {
81
            $requestBody['paymentMethod']['issuer'] = $payment->getAdditionalInformation(AdyenHppDataAssignObserver::ISSUER_ID);
82
        }
83

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

attilak's avatar
typo  
attilak committed
86
        // Additional data for ACH
attilak's avatar
attilak committed
87
        if ($payment->getAdditionalInformation("bankAccountNumber")) {
88
            $requestBody['bankAccount']['bankAccountNumber'] = $payment->getAdditionalInformation("bankAccountNumber");
attilak's avatar
attilak committed
89 90 91
        }

        if ($payment->getAdditionalInformation("bankLocationId")) {
92
            $requestBody['bankAccount']['bankLocationId'] = $payment->getAdditionalInformation("bankLocationId");
attilak's avatar
attilak committed
93 94 95
        }

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

99 100 101 102 103
		// Additional data for open invoice payment
		if ($payment->getAdditionalInformation("gender")) {
			$order->setCustomerGender(\Adyen\Payment\Model\Gender::getMagentoGenderFromAdyenGender(
				$payment->getAdditionalInformation("gender"))
			);
104
            $requestBody['paymentMethod']['personalDetails']['gender'] = $payment->getAdditionalInformation("gender");
105 106
		}

107 108
        if ($payment->getAdditionalInformation("dob")) {
            $order->setCustomerDob($payment->getAdditionalInformation("dob"));
109

110
            $requestBody['paymentMethod']['personalDetails']['dateOfBirth']= $this->adyenHelper->formatDate($payment->getAdditionalInformation("dob"), 'Y-m-d') ;
111 112 113 114
		}

		if ($payment->getAdditionalInformation("telephone")) {
			$order->getBillingAddress()->setTelephone($payment->getAdditionalInformation("telephone"));
115
            $requestBody['paymentMethod']['personalDetails']['telephoneNumber']= $payment->getAdditionalInformation("telephone");
116 117
		}

118
        if ($payment->getAdditionalInformation("ssn")) {
119
            $requestBody['paymentMethod']['personalDetails']['socialSecurityNumber']= $payment->getAdditionalInformation("ssn");
120 121
        }

122 123
        // Additional data for sepa direct debit
        if ($payment->getAdditionalInformation("ownerName")) {
124
            $requestBody['paymentMethod']['sepa.ownerName'] = $payment->getAdditionalInformation("ownerName");
125
        }
126

127
        if ($payment->getAdditionalInformation("ibanNumber")) {
128
            $requestBody['paymentMethod']['sepa.ibanNumber'] = $payment->getAdditionalInformation("ibanNumber");
129
        }
130 131

		if ($this->adyenHelper->isPaymentMethodOpenInvoiceMethod(
attilak's avatar
attilak committed
132 133
			    $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
		    ) || $this->adyenHelper->isPaymentMethodAfterpayTouchMethod(
134
				$payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
attilak's avatar
attilak committed
135 136 137 138
			) || $this->adyenHelper->isPaymentMethodOneyMethod(
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            )
        ) {
139
			$openInvoiceFields = $this->getOpenInvoiceData($order);
140
            $requestBody = array_merge($requestBody, $openInvoiceFields);
141 142
		}

143 144 145 146
        // Ratepay specific Fingerprint
        if ($payment->getAdditionalInformation("df_value") && $this->adyenHelper->isPaymentMethodRatepayMethod(
                $payment->getAdditionalInformation(AdyenHppDataAssignObserver::BRAND_CODE)
            )) {
147
            $requestBody['deviceFingerprint'] = $payment->getAdditionalInformation("df_value");
148 149
        }

alexandros's avatar
alexandros committed
150 151
        //Boleto data
        if ($payment->getAdditionalInformation("social_security_number")) {
152
            $requestBody['socialSecurityNumber'] = $payment->getAdditionalInformation("social_security_number");
alexandros's avatar
alexandros committed
153 154 155
        }

        if ($payment->getAdditionalInformation("firstname")) {
156
            $requestBody['shopperName']['firstName'] = $payment->getAdditionalInformation("firstname");
alexandros's avatar
alexandros committed
157 158 159
        }

        if ($payment->getAdditionalInformation("lastName")) {
160
            $requestBody['shopperName']['lastName'] = $payment->getAdditionalInformation("lastName");
alexandros's avatar
alexandros committed
161 162
        }

163
        if ($payment->getMethod() == \Adyen\Payment\Model\Ui\AdyenBoletoConfigProvider::CODE) {
alexandros's avatar
alexandros committed
164 165 166 167
            $boletoTypes = $this->adyenHelper->getAdyenBoletoConfigData('boletotypes');
            $boletoTypes = explode(',', $boletoTypes);

            if (count($boletoTypes) == 1) {
168 169
                $requestBody['selectedBrand'] = $boletoTypes[0];
                $requestBody['paymentMethod']['type'] = $boletoTypes[0];
alexandros's avatar
alexandros committed
170
            } else {
171 172
                $requestBody['selectedBrand'] = $payment->getAdditionalInformation("boleto_type");
                $requestBody['paymentMethod']['type'] = $payment->getAdditionalInformation("boleto_type");
alexandros's avatar
alexandros committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
            }

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

189
            $requestBody['deliveryDate'] = $deliveryDate;
alexandros's avatar
alexandros committed
190

191 192
            $order->setCanSendNewEmailFlag(true);
        }
193 194

        $request['body'] = $requestBody;
195

alexandros's avatar
alexandros committed
196 197
        return $request;
    }
198

199
    /**
Jeroen's avatar
Jeroen committed
200 201 202 203 204
     * @param \Magento\Sales\Model\Order $order
     *
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     *
     * @return array
205
     */
Jeroen's avatar
Jeroen committed
206
    protected function getOpenInvoiceData($order): array
207 208 209 210
    {
        $formFields = [
            'lineItems' => []
        ];
211

Jeroen's avatar
Jeroen committed
212 213 214
        /** @var \Magento\Quote\Model\Quote $cart */
        $cart = $this->cartRepository->get($order->getQuoteId());
        $currency = $cart->getCurrency();
215
        $discountAmount = 0;
216

Jeroen's avatar
Jeroen committed
217
        foreach ($cart->getAllVisibleItems() as $item) {
attilak's avatar
attilak committed
218
            $numberOfItems = (int)$item->getQty();
219

220 221
            // Summarize the discount amount item by item
            $discountAmount += $item->getDiscountAmount();
222

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

attilak's avatar
attilak committed
225 226
            $taxAmount = $item->getPrice() * ($item->getTaxPercent() / 100);
            $formattedTaxAmount = $this->adyenHelper->formatAmount($taxAmount, $currency);
227
            $formattedTaxPercentage = $item->getTaxPercent() * 100;
228

229
            $formFields['lineItems'][] = [
attilak's avatar
attilak committed
230 231
                'id' => $item->getId(),
                'itemId' => $item->getId(),
attilak's avatar
attilak committed
232
                'amountExcludingTax' => $formattedPriceExcludingTax,
233
                'taxAmount' => $formattedTaxAmount,
234
                'description' => $item->getName(),
attilak's avatar
attilak committed
235
                'quantity' => $numberOfItems,
236
                'taxCategory' => $item->getProduct()->getAttributeText('tax_class_id'),
237
                'taxPercentage' => $formattedTaxPercentage
238 239
            ];
        }
240

241 242 243
        // Discount cost
        if ($discountAmount != 0) {

244 245
            $description = __('Discount');
            $itemAmount = -$this->adyenHelper->formatAmount($discountAmount, $currency);
246 247 248 249 250
            $itemVatAmount = "0";
            $itemVatPercentage = "0";
            $numberOfItems = 1;

            $formFields['lineItems'][] = [
251
                'id' => 'Discount',
252 253 254 255 256 257 258 259
                'amountExcludingTax' => $itemAmount,
                'taxAmount' => $itemVatAmount,
                'description' => $description,
                'quantity' => $numberOfItems,
                'taxCategory' => 'None',
                'taxPercentage' => $itemVatPercentage
            ];
        }
260

261
        // Shipping cost
Jeroen's avatar
Jeroen committed
262
        if ($cart->getShippingAddress()->getShippingAmount() > 0 || $cart->getShippingAddress()->getShippingTaxAmount() > 0) {
263

Jeroen's avatar
Jeroen committed
264
            $priceExcludingTax = $cart->getShippingAddress()->getShippingAmount() - $cart->getShippingAddress()->getShippingTaxAmount();
265

Jeroen's avatar
Jeroen committed
266
            $formattedTaxAmount = $this->adyenHelper->formatAmount($cart->getShippingAddress()->getShippingTaxAmount(), $currency);
267

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

270 271 272
            $formattedTaxPercentage = 0;

            if ($priceExcludingTax !== 0) {
Jeroen's avatar
Jeroen committed
273
                $formattedTaxPercentage = $cart->getShippingAddress()->getShippingTaxAmount() / $priceExcludingTax * 100 * 100;
274
            }
275

276
            $formFields['lineItems'][] = [
attilak's avatar
attilak committed
277
                'itemId' => 'shippingCost',
attilak's avatar
attilak committed
278
                'amountExcludingTax' => $formattedPriceExcludingTax,
279
                'taxAmount' => $formattedTaxAmount,
280 281
                'description' => $order->getShippingDescription(),
                'quantity' => 1,
282
                'taxPercentage' => $formattedTaxPercentage
283 284
            ];
        }
285

286 287
        return $formFields;
    }
288
}