ApiClient.php 6.88 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
<?php
/**
 * @copyright  Vertex. All rights reserved.  https://www.vertexinc.com/
 * @author     Mediotype                     https://www.mediotype.com/
 */

namespace Vertex\Tax\Model;

use Magento\Sales\Api\Data\OrderInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
use Vertex\Tax\Api\ClientInterface;
use Vertex\Tax\Model\ApiClient\ObjectConverter;
use Vertex\Utility\SoapClientFactory;

/**
 * {@inheritdoc}
 * @deprecated
 */
class ApiClient implements ClientInterface
{
    const CONNECTION_TIMEOUT = 12; // seconds

    /** @var Config */
    private $config;

    /** @var ExceptionLogger */
    private $logger;

    /** @var ObjectConverter */
    private $objectConverter;

    /** @var RequestLogger */
    private $requestLogger;

    /** @var SoapClientFactory */
    private $soapClientFactory;

    /** @var StoreManagerInterface */
    private $storeManager;

    /**
     * @param ExceptionLogger $logger
     * @param Config $config
     * @param StoreManagerInterface $storeManager
     * @param SoapClientFactory $soapClientFactory
     * @param RequestLogger $requestLogger
     * @param ObjectConverter $objectConverter
     */
    public function __construct(
        ExceptionLogger $logger,
        Config $config,
        StoreManagerInterface $storeManager,
        SoapClientFactory $soapClientFactory,
        RequestLogger $requestLogger,
        ObjectConverter $objectConverter
    ) {
        $this->logger = $logger;
        $this->config = $config;
        $this->storeManager = $storeManager;
        $this->soapClientFactory = $soapClientFactory;
        $this->requestLogger = $requestLogger;
        $this->objectConverter = $objectConverter;
    }

    /**
     * {@inheritdoc}
     * @deprecated
     */
    public function sendApiRequest(array $request, $type, OrderInterface $order = null)
    {
        $scopeType = ScopeInterface::SCOPE_STORE;
        $scopeCode = $this->getStoreId($order);

        $apiUrl = $this->config->getVertexHost($scopeCode, $scopeType);
        if ($type === 'tax_area_lookup') {
            $apiUrl = $this->config->getVertexAddressHost($scopeCode, $scopeType);
        }

        $apiUrl = $this->getWsdlUrl($apiUrl);

        $client = null;
        try {
            $client = $this->createSoapClient($apiUrl);
            $taxResponse = $this->performSoapCall($client, $type, $request);
            $taxResponseArray = $this->objectConverter->convertToArray($taxResponse);
        } catch (\Exception $e) {
            $this->logException($e, $type, $client);
            return false;
        }

        $this->logRequest(
            $type,
            $client->__getLastRequest(),
            $client->__getLastResponse()
        );
        return $taxResponseArray;
    }

    /**
     * Create a SOAP client for use with the API
     *
     * Enforces TLSv1.2 with SHA2 on a SOAP 1.1 Call
     *
     * @param $apiUrl
     * @return \SoapClient
     */
    private function createSoapClient($apiUrl)
    {
        $soapParams = [
            'trace' => true,
            'soap_version' => SOAP_1_1
        ];

        $context = [
            'ssl_method' => SOAP_SSL_METHOD_TLS,
            'connection_timeout' => static::CONNECTION_TIMEOUT,
            'stream_context' => $this->createStreamContext(),
        ];

        $soapParams['stream_context'] = $context; // for TLS 1.2

        return $this->soapClientFactory->create($apiUrl, $soapParams);
    }

    /**
     * Create a communication context for the client.
     *
     * Returns context to properly negotiate on TLS 1.2.
     *
     * @return resource
     */
    private function createStreamContext()
    {
        return stream_context_create(
            [
                'ssl' => [
                    'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
                    'ciphers' => 'SHA2',
                ]
            ]
        );
    }

    /**
     * Retrieve the Store ID relevant to the request
     *
     * @param OrderInterface|null $order
     * @return int
     */
    private function getStoreId(OrderInterface $order = null)
    {
        return $order !== null ? $order->getStoreId() : $this->storeManager->getStore()->getId();
    }

    /**
     * Retrieve the total tax calculated from a response
     *
     * @param array $taxResponseArray
     * @return float
     */
    private function getTotalTax($taxResponseArray)
    {
        $totalTax = 0;

        if (isset($taxResponseArray['TotalTax'])) {
            $totalTax = $taxResponseArray['TotalTax'];
        }

        return $totalTax;
    }

    /**
     * Get the WSDL version of an API URL
     *
     * @param string $apiUrl
     * @return string
     */
    private function getWsdlUrl($apiUrl)
    {
        if (stripos($apiUrl, 'wsdl') === false) {
            $apiUrl .= '?wsdl';
        }
        return $apiUrl;
    }

    /**
     * Log an exception that occurred during an API request
     *
     * @param \Throwable $exception
     * @param string $type Request Type
     * @param \SoapClient|null $client
     */
    private function logException($exception, $type, \SoapClient $client = null)
    {
        $this->logger->critical($exception);
        $this->logRequest(
            $type,
            $client !== null ? $client->__getLastRequest() : '',
            $client !== null ? $client->__getLastResponse() : ''
        );
    }

    /**
     * Log an API Request
     *
     * @param string $type
     * @param string $requestXml
     * @param string $responseXml
     */
    private function logRequest($type, $requestXml, $responseXml)
    {
        try {
            $this->requestLogger->log(
                $type,
                $requestXml,
                $responseXml
            );
        } catch (\Exception $originalException) {
            // Logging Exception
            $exception = new \Exception('Failed to log Vertex Request', 0, $originalException);
            $this->logger->critical($exception);
        }
    }

    /**
     * Perform a SOAP Call given a client and request data and type
     *
     * Uses type to determine which function to call against SOAP
     *
     * @param \SoapClient $client
     * @param string $type
     * @param array $request
     * @param string $scopeType
     * @param string $scopeCode
     * @return mixed
     * @throws Exception
     * @throws \SoapFault
     */
    private function performSoapCall(
        \SoapClient $client,
        $type,
        $request
    ) {
        if ($type === 'tax_area_lookup') {
            $taxResponse = $client->LookupTaxAreas60($request);
        } elseif (in_array($type, ['quote', 'invoice', 'invoice_refund'])) {
            $taxResponse = $client->CalculateTax60($request);
        } else {
            throw new \Exception('Invalid request type');
        }
        if ($taxResponse instanceof \SoapFault) {
            throw $taxResponse;
        }

        return $taxResponse;
    }
}