Request.php 8.84 KB
Newer Older
Ketan's avatar
Ketan committed
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 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 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 190 191 192 193 194 195 196 197 198 199 200 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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 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 310 311 312 313 314 315 316 317 318 319 320 321 322 323
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Paypal\Model\Hostedpro;

use Magento\Customer\Helper\Address;
use Magento\Framework\DataObject;
use Magento\Framework\Locale\Resolver;
use Magento\Payment\Helper\Formatter;
use Magento\Paypal\Model\Hostedpro;
use Magento\Sales\Model\Order;
use Magento\Tax\Helper\Data;

/**
 *  Website Payments Pro Hosted Solution request model to get token.
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Request extends DataObject
{
    use Formatter;

    /**
     * Request's order model
     *
     * @var \Magento\Sales\Model\Order
     */
    protected $order;

    /**
     * Request's Hosted Pro payment method model
     *
     * @var \Magento\Paypal\Model\Hostedpro
     */
    protected $paymentMethod;

    /**
     * Name format for button variables
     *
     * @var string
     */
    protected $buttonVarFormat = 'L_BUTTONVAR%d';

    /**
     * Request Parameters which dont have to wrap as button vars
     *
     * @var string[]
     */
    protected $notButtonVars = ['METHOD', 'BUTTONCODE', 'BUTTONTYPE'];

    /**
     * Customer address
     *
     * @var \Magento\Customer\Helper\Address
     */
    protected $customerAddress = null;

    /**
     * Tax data
     *
     * @var \Magento\Tax\Helper\Data
     */
    protected $taxData;

    /**
     * Locale Resolver
     *
     * @var \Magento\Framework\Locale\Resolver
     */
    protected $localeResolver;

    /**
     * @param \Magento\Framework\Locale\Resolver $localeResolver
     * @param \Magento\Customer\Helper\Address $customerAddress
     * @param \Magento\Tax\Helper\Data $taxData
     * @param array $data
     */
    public function __construct(
        Resolver $localeResolver,
        Address $customerAddress,
        Data $taxData,
        array $data = []
    ) {
        $this->customerAddress = $customerAddress;
        $this->localeResolver = $localeResolver;
        $this->taxData = $taxData;
        parent::__construct($data);
    }

    /**
     * Build and return request array from object data
     *
     * @return array
     */
    public function getRequestData()
    {
        $requestData = [];
        if (!empty($this->_data)) {
            // insert params to request as additional button variables,
            // except special params from _notButtonVars list
            $i = 0;
            foreach ($this->_data as $key => $value) {
                if (in_array($key, $this->notButtonVars)) {
                    $requestData[$key] = $value;
                } else {
                    $varKey = sprintf($this->buttonVarFormat, $i);
                    $requestData[$varKey] = $key . '=' . $value;
                    $i++;
                }
            }
        }

        return $requestData;
    }

    /**
     * Append payment data to request
     *
     * @param \Magento\Paypal\Model\Hostedpro $paymentMethod
     * @return $this
     */
    public function setPaymentMethod($paymentMethod)
    {
        $this->paymentMethod = $paymentMethod;
        $requestData = $this->getPaymentData($paymentMethod);
        $this->addData($requestData);

        return $this;
    }

    /**
     * Append order data to request
     *
     * @param \Magento\Sales\Model\Order $order
     * @return $this
     */
    public function setOrder(Order $order)
    {
        $this->order = $order;
        $requestData = $this->getOrderData($order);
        $this->addData($requestData);

        return $this;
    }

    /**
     * Add amount data to request
     *
     * @access public
     * @param \Magento\Sales\Model\Order $order
     * @return $this
     */
    public function setAmount(Order $order)
    {
        $this->addData($this->getAmountData($order));
        return $this;
    }

    /**
     * Calculate amount for order
     * @param \Magento\Sales\Model\Order $order
     * @return array
     * @throws \Exception
     */
    protected function getAmountData(Order $order)
    {
        // if tax is included - need add to request only total amount
        if ($this->taxData->getConfig()->priceIncludesTax()) {
            return $this->getTaxableAmount($order);
        } else {
            return $this->getNonTaxableAmount($order);
        }
    }

    /**
     * Get payment amount data with excluded tax
     * @param \Magento\Sales\Model\Order $order
     * @return array
     */
    private function getNonTaxableAmount(Order $order)
    {
        // PayPal denied transaction with 0 amount
        $subtotal = $order->getBaseSubtotal() ? : $order->getPayment()->getBaseAmountAuthorized();

        return [
            'subtotal' => $this->formatPrice($subtotal),
            'total' => $this->formatPrice($order->getPayment()->getBaseAmountAuthorized()),
            'tax' => $this->formatPrice($order->getBaseTaxAmount()),
            'shipping' => $this->formatPrice($order->getBaseShippingAmount()),
            'discount' => $this->formatPrice(abs($order->getBaseDiscountAmount()))
        ];
    }

    /**
     * Get order amount data with included tax
     * @param \Magento\Sales\Model\Order $order
     * @return array
     */
    private function getTaxableAmount(Order $order)
    {
        $amount = $this->formatPrice($order->getPayment()->getBaseAmountAuthorized());

        return [
            'amount' => $amount,
            'subtotal' => $amount // subtotal always is required
        ];
    }

    /**
     * Get payment request data as array
     *
     * @param \Magento\Paypal\Model\Hostedpro $paymentMethod
     * @return array
     */
    protected function getPaymentData(Hostedpro $paymentMethod)
    {
        $request = [
            'paymentaction' => strtolower($paymentMethod->getConfigData('payment_action')),
            'notify_url' => $paymentMethod->getNotifyUrl(),
            'cancel_return' => $paymentMethod->getCancelUrl(),
            'return' => $paymentMethod->getReturnUrl(),
            'lc' => \Locale::getRegion($this->localeResolver->getLocale()),
            'template' => 'mobile-iframe',
            'showBillingAddress' => 'false',
            'showShippingAddress' => 'true',
            'showBillingEmail' => 'false',
            'showBillingPhone' => 'false',
            'showCustomerName' => 'false',
            'showCardInfo' => 'true',
            'showHostedThankyouPage' => 'false',
        ];

        return $request;
    }

    /**
     * Get order request data as array
     *
     * @param \Magento\Sales\Model\Order $order
     * @return array
     */
    protected function getOrderData(Order $order)
    {
        $request = [
            'invoice' => $order->getIncrementId(),
            'address_override' => 'true',
            'currency_code' => $order->getBaseCurrencyCode(),
            'buyer_email' => $order->getCustomerEmail(),
        ];

        // append to request billing address data
        if ($billingAddress = $order->getBillingAddress()) {
            $request = array_merge($request, $this->getAddress($billingAddress, 'billing'));
        }

        // append to request shipping address data
        if ($shippingAddress = $order->getShippingAddress()) {
            $request = array_merge($request, $this->getAddress($shippingAddress));
        }

        return $request;
    }

    /**
     * Export address data to request
     *
     * @param DataObject $address
     * @param string $type
     * @return array
     */
    protected function getAddress(DataObject $address, $type = '')
    {
        $type = !empty($type) ? $type . '_' : '';
        $request = [
            $type . 'first_name' => $address->getFirstname(),
            $type . 'last_name' => $address->getLastname(),
            $type . 'city' => $address->getCity(),
            $type . 'state' => $this->getRegion($address),
            $type . 'zip' => $address->getPostcode(),
            $type . 'country' => $address->getCountryId(),
        ];

        $streets = $this->getAddressStreets($address);
        $request[$type . 'address1'] = $streets[0];
        $request[$type . 'address2'] = $streets[1];

        return $request;
    }

    /**
     * Export region code from address data
     *
     * @param DataObject $address
     * @return string
     */
    protected function getRegion(DataObject $address)
    {
        // get region code, otherwise - region, otherwise - city
        return $address->getRegionCode() ?: ($address->getRegion() ?: $address->getCity());
    }

    /**
     * Export streets from address data
     *
     * @param DataObject $address
     * @return array
     */
    protected function getAddressStreets(DataObject $address)
    {
        $street1 = '';
        $street2 = '';
        $data = $this->customerAddress->convertStreetLines($address->getStreet(), 2);
        if (!empty($data[0])) {
            $street1 = $data[0];
        }
        if (!empty($data[1])) {
            $street2 = $data[1];
        }
        return [$street1, $street2];
    }
}