Exemple #1
0
 /**
  * Post request into gateway
  *
  * @param DataObject $request
  * @param ConfigInterface $config
  *
  * @return DataObject
  * @throws \Zend_Http_Client_Exception
  */
 public function postRequest(DataObject $request, ConfigInterface $config)
 {
     $result = new DataObject();
     $clientConfig = ['maxredirects' => 5, 'timeout' => 30, 'verifypeer' => $config->getValue('verify_peer')];
     if ($config->getValue('use_proxy')) {
         $clientConfig['proxy'] = $config->getValue('proxy_host') . ':' . $config->getValue('proxy_port');
         $clientConfig['httpproxytunnel'] = true;
         $clientConfig['proxytype'] = CURLPROXY_HTTP;
     }
     /** @var ZendClient $client */
     $client = $this->httpClientFactory->create();
     $client->setUri((bool) $config->getValue('sandbox_flag') ? $config->getValue('transaction_url_test_mode') : $config->getValue('transaction_url'));
     $client->setConfig($clientConfig);
     $client->setMethod(\Zend_Http_Client::POST);
     $client->setParameterPost($request->getData());
     $client->setHeaders(['X-VPS-VIT-CLIENT-CERTIFICATION-ID' => '33baf5893fc2123d8b191d2d011b7fdc', 'X-VPS-Request-ID' => $this->mathRandom->getUniqueHash(), 'X-VPS-CLIENT-TIMEOUT' => 45]);
     $client->setUrlEncodeBody(false);
     try {
         $response = $client->request();
         $responseArray = [];
         parse_str(strstr($response->getBody(), 'RESULT'), $responseArray);
         $result->setData(array_change_key_case($responseArray, CASE_LOWER));
         $result->setData('result_code', $result->getData('result'));
     } catch (\Zend_Http_Client_Exception $e) {
         $result->addData(['response_code' => -1, 'response_reason_code' => $e->getCode(), 'response_reason_text' => $e->getMessage()]);
         throw $e;
     } finally {
         $this->logger->debug(['request' => $request->getData(), 'result' => $result->getData()], (array) $config->getValue('getDebugReplacePrivateDataKeys'), (bool) $config->getValue('debug'));
     }
     return $result;
 }
 public function testFetchRates()
 {
     $currencyFromList = ['USD'];
     $currencyToList = ['EUR', 'UAH'];
     $responseBody = '{"query":{"count":7,"created":"2016-04-05T16:46:55Z","lang":"en-US","results":{"rate":' . '[{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9022","Date":"4/5/2016"}]}}}';
     $expectedCurrencyRateList = ['USD' => ['EUR' => 0.9022, 'UAH' => null]];
     $message = "We can't retrieve a rate from http://query.yahooapis.com/v1/public/yql?format=json" . "&q=select+*+from+yahoo.finance.xchange+where+pair+in+%28%22USDEUR%22%2C%22USDUAH%22)" . "&env=store://datatables.org/alltableswithkeys for UAH.";
     /** @var \Magento\Directory\Model\Currency|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
     $currencyMock = $this->getMockBuilder('Magento\\Directory\\Model\\Currency')->disableOriginalConstructor()->setMethods([])->getMock();
     /** @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
     $httpClientMock = $this->getMockBuilder('Magento\\Framework\\HTTP\\ZendClient')->disableOriginalConstructor()->setMethods([])->getMock();
     /** @var \Zend_Http_Response|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
     $httpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->setMethods([])->getMock();
     $this->currencyFactoryMock->expects($this->any())->method('create')->willReturn($currencyMock);
     $currencyMock->expects($this->once())->method('getConfigBaseCurrencies')->willReturn($currencyFromList);
     $currencyMock->expects($this->once())->method('getConfigAllowCurrencies')->willReturn($currencyToList);
     $this->httpClientFactoryMock->expects($this->any())->method('create')->willReturn($httpClientMock);
     $httpClientMock->expects($this->atLeastOnce())->method('setUri')->willReturnSelf();
     $httpClientMock->expects($this->atLeastOnce())->method('setConfig')->willReturnSelf();
     $httpClientMock->expects($this->atLeastOnce())->method('request')->willReturn($httpResponseMock);
     $httpResponseMock->expects($this->any())->method('getBody')->willReturn($responseBody);
     $this->assertEquals($expectedCurrencyRateList, $this->model->fetchRates());
     $messages = $this->model->getMessages();
     $this->assertNotEmpty($messages);
     $this->assertTrue(is_array($messages));
     $this->assertEquals($message, (string) $messages[0]);
 }
 /**
  * Performs the request to make the deployment
  *
  * @param string $description
  * @param bool $change
  * @param bool $user
  *
  * @return bool|string
  */
 public function setDeployment($description, $change = false, $user = false)
 {
     $apiUrl = $this->config->getNewRelicApiUrl();
     if (empty($apiUrl)) {
         $this->logger->notice('New Relic API URL is blank, using fallback URL');
         $apiUrl = self::API_URL;
     }
     /** @var \Magento\Framework\HTTP\ZendClient $client */
     $client = $this->clientFactory->create();
     $client->setUri($apiUrl);
     $client->setMethod(ZendClient::POST);
     $client->setHeaders(['x-api-key' => $this->config->getNewRelicApiKey()]);
     $params = ['deployment[app_name]' => $this->config->getNewRelicAppName(), 'deployment[application_id]' => $this->config->getNewRelicAppId(), 'deployment[description]' => $description, 'deployment[changelog]' => $change, 'deployment[user]' => $user];
     $client->setParameterPost($params);
     try {
         $response = $client->request();
     } catch (\Zend_Http_Client_Exception $e) {
         $this->logger->critical($e);
         return false;
     }
     if ($response->getStatus() < 200 || $response->getStatus() > 210) {
         $this->logger->warning('Deployment marker request did not send a 200 status code.');
         return false;
     }
     return $response->getBody();
 }
Exemple #4
0
 /**
  * {inheritdoc}
  */
 public function placeRequest(TransferInterface $transferObject)
 {
     $log = ['request' => $transferObject->getBody(), 'request_uri' => $transferObject->getUri()];
     $result = [];
     /** @var ZendClient $client */
     $client = $this->clientFactory->create();
     $client->setConfig($transferObject->getClientConfig());
     $client->setMethod($transferObject->getMethod());
     switch ($transferObject->getMethod()) {
         case \Zend_Http_Client::GET:
             $client->setParameterGet($transferObject->getBody());
             break;
         case \Zend_Http_Client::POST:
             $client->setParameterPost($transferObject->getBody());
             break;
         default:
             throw new \LogicException(sprintf('Unsupported HTTP method %s', $transferObject->getMethod()));
     }
     $client->setHeaders($transferObject->getHeaders());
     $client->setUrlEncodeBody($transferObject->shouldEncode());
     $client->setUri($transferObject->getUri());
     try {
         $response = $client->request();
         $result = $this->converter ? $this->converter->convert($response->getBody()) : [$response->getBody()];
         $log['response'] = $result;
     } catch (\Zend_Http_Client_Exception $e) {
         throw new \Magento\Payment\Gateway\Http\ClientException(__($e->getMessage()));
     } catch (\Magento\Payment\Gateway\Http\ConverterException $e) {
         throw $e;
     } finally {
         $this->logger->debug($log);
     }
     return $result;
 }
 /**
  * Load transaction details
  *
  * @param \Magento\Authorizenet\Model\Authorizenet $context
  * @param string $transactionId
  * @return \Magento\Framework\Simplexml\Element
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function loadTransactionDetails(Authorizenet $context, $transactionId)
 {
     $requestBody = $this->getRequestBody($context->getConfigData('login'), $context->getConfigData('trans_key'), $transactionId);
     /** @var \Magento\Framework\HTTP\ZendClient $client */
     $client = $this->httpClientFactory->create();
     $url = $context->getConfigData('cgi_url_td') ?: self::CGI_URL_TD;
     $client->setUri($url);
     $client->setConfig(['timeout' => self::CONNECTION_TIMEOUT]);
     $client->setHeaders(['Content-Type: text/xml']);
     $client->setMethod(\Zend_Http_Client::POST);
     $client->setRawData($requestBody);
     $debugData = ['url' => $url, 'request' => $this->removePrivateDataFromXml($requestBody)];
     try {
         $responseBody = $client->request()->getBody();
         if (!$this->xmlSecurityHelper->scan($responseBody)) {
             $this->logger->critical('Attempt loading of external XML entities in response from Authorizenet.');
             throw new \Exception();
         }
         $debugData['response'] = $responseBody;
         libxml_use_internal_errors(true);
         $responseXmlDocument = new Element($responseBody);
         libxml_use_internal_errors(false);
     } catch (\Exception $e) {
         throw new LocalizedException(__('Unable to get transaction details. Try again later.'));
     } finally {
         $context->debugData($debugData);
     }
     if (!isset($responseXmlDocument->messages->resultCode) || $responseXmlDocument->messages->resultCode != static::PAYMENT_UPDATE_STATUS_CODE_SUCCESS) {
         throw new LocalizedException(__('Unable to get transaction details. Try again later.'));
     }
     $this->transactionDetails[$transactionId] = $responseXmlDocument;
     return $responseXmlDocument;
 }
 public function testFetchRates()
 {
     $currencyFromList = ['USD'];
     $currencyToList = ['EUR', 'UAH'];
     $responseBody = '{"base":"USD","date":"2015-10-07","rates":{"EUR":0.9022}}';
     $expectedCurrencyRateList = ['USD' => ['EUR' => 0.9022, 'UAH' => null]];
     $message = "We can't retrieve a rate from http://api.fixer.io/latest?base=USD&symbols=EUR,UAH for UAH.";
     /** @var \Magento\Directory\Model\Currency|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
     $currencyMock = $this->getMockBuilder('Magento\\Directory\\Model\\Currency')->disableOriginalConstructor()->setMethods([])->getMock();
     /** @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
     $httpClientMock = $this->getMockBuilder('Magento\\Framework\\HTTP\\ZendClient')->disableOriginalConstructor()->setMethods([])->getMock();
     /** @var \Zend_Http_Response|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
     $httpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->setMethods([])->getMock();
     $this->currencyFactoryMock->expects($this->any())->method('create')->willReturn($currencyMock);
     $currencyMock->expects($this->once())->method('getConfigBaseCurrencies')->willReturn($currencyFromList);
     $currencyMock->expects($this->once())->method('getConfigAllowCurrencies')->willReturn($currencyToList);
     $this->httpClientFactoryMock->expects($this->any())->method('create')->willReturn($httpClientMock);
     $httpClientMock->expects($this->atLeastOnce())->method('setUri')->willReturnSelf();
     $httpClientMock->expects($this->atLeastOnce())->method('setConfig')->willReturnSelf();
     $httpClientMock->expects($this->atLeastOnce())->method('request')->willReturn($httpResponseMock);
     $httpResponseMock->expects($this->any())->method('getBody')->willReturn($responseBody);
     $this->assertEquals($expectedCurrencyRateList, $this->model->fetchRates());
     $messages = $this->model->getMessages();
     $this->assertNotEmpty($messages);
     $this->assertTrue(is_array($messages));
     $this->assertEquals($message, (string) $messages[0]);
 }
 protected function setUp()
 {
     $this->httpClientFactoryMock = $this->getMockBuilder('\\Magento\\Framework\\HTTP\\ZendClientFactory')->setMethods(['create'])->disableOriginalConstructor()->getMock();
     $this->zendClientMock = $this->getMockBuilder('\\Magento\\Framework\\HTTP\\ZendClient')->setMethods(['request', 'setUri'])->disableOriginalConstructor()->getMock();
     $this->httpClientFactoryMock->expects($this->once())->method('create')->willReturn($this->zendClientMock);
     $this->mathRandomMock = $this->getMockBuilder('\\Magento\\Framework\\Math\\Random')->disableOriginalConstructor()->getMock();
     $this->loggerMock = $this->getMockBuilder('\\Magento\\Payment\\Model\\Method\\Logger')->setConstructorArgs([$this->getMockForAbstractClass('Psr\\Log\\LoggerInterface')])->setMethods(['debug'])->getMock();
     $this->object = new Gateway($this->httpClientFactoryMock, $this->mathRandomMock, $this->loggerMock);
 }
 protected function setUp()
 {
     $this->httpClientFactoryMock = $this->getMockBuilder(ZendClientFactory::class)->setMethods(['create'])->disableOriginalConstructor()->getMock();
     $this->zendClientMock = $this->getMockBuilder(ZendClient::class)->setMethods(['request', 'setUri'])->disableOriginalConstructor()->getMock();
     $this->httpClientFactoryMock->expects(static::once())->method('create')->willReturn($this->zendClientMock);
     $this->mathRandomMock = $this->getMockBuilder(Random::class)->disableOriginalConstructor()->getMock();
     $this->loggerMock = $this->getMockBuilder(Logger::class)->setConstructorArgs([$this->getMockForAbstractClass(LoggerInterface::class)])->setMethods(['debug'])->getMock();
     $this->object = new Gateway($this->httpClientFactoryMock, $this->mathRandomMock, $this->loggerMock);
 }
 /**
  * Returns HTTP request to events url
  *
  * @return \Magento\Framework\HTTP\ZendClient
  */
 protected function getRequest()
 {
     if (!isset($this->request)) {
         $this->request = $this->clientFactory->create();
         $this->request->setUri($this->getEventsUrl());
         $insertKey = $this->config->getInsightsInsertKey();
         $this->request->setMethod(ZendClient::POST);
         $this->request->setHeaders(['X-Insert-Key' => $insertKey, 'Content-Type' => 'application/json']);
     }
     return $this->request;
 }
Exemple #10
0
 /**
  * Tests failing response converting
  *
  * @expectedException  \Magento\Payment\Gateway\Http\ConverterException
  */
 public function testPlaceRequestConvertResponseFail()
 {
     $this->setClientTransferObjects();
     $responseBody = 'Response body content';
     $zendHttpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->getMock();
     $zendHttpResponseMock->expects($this->once())->method('getBody')->willReturn($responseBody);
     $this->clientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock);
     $this->converterMock->expects($this->once())->method('convert')->with($responseBody)->willThrowException(new \Magento\Payment\Gateway\Http\ConverterException(__()));
     $this->zendClientFactoryMock->expects($this->once())->method('create')->willReturn($this->clientMock);
     $this->model->placeRequest($this->transferObjectMock);
 }
 protected function _toHtml()
 {
     $client = $this->clientFactory->create(['uri' => self::SOURCE_URL]);
     try {
         $result = $client->request();
         $rates = json_decode($result->getBody(), true);
         if (isset($rates['rates']['EUR'])) {
             return sprintf('<div style="display: inline-block;color: red;">1 USD = %s EUR</div>', $rates['rates']['EUR']);
         }
     } catch (\Exception $e) {
         $this->_logger->critical($e);
     }
 }
 /**
  * Post request to gateway and return response
  *
  * @param \Magento\Authorizenet\Model\Request $request
  * @return \Magento\Authorizenet\Model\Response
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 protected function postRequest(\Magento\Authorizenet\Model\Request $request)
 {
     $result = $this->responseFactory->create();
     /** @var \Magento\Framework\HTTP\ZendClient $client */
     $client = $this->httpClientFactory->create();
     $url = $this->getConfigData('cgi_url') ?: self::CGI_URL;
     $debugData = ['url' => $url, 'request' => $request->getData()];
     $client->setUri($url);
     $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
     foreach ($request->getData() as $key => $value) {
         $request->setData($key, str_replace(self::RESPONSE_DELIM_CHAR, '', $value));
     }
     $request->setXDelimChar(self::RESPONSE_DELIM_CHAR);
     $client->setParameterPost($request->getData());
     $client->setMethod(\Zend_Http_Client::POST);
     try {
         $response = $client->request();
         $responseBody = $response->getBody();
         $debugData['response'] = $responseBody;
     } catch (\Exception $e) {
         $result->setXResponseCode(-1)->setXResponseReasonCode($e->getCode())->setXResponseReasonText($e->getMessage());
         throw new \Magento\Framework\Exception\LocalizedException($this->dataHelper->wrapGatewayError($e->getMessage()));
     } finally {
         $this->_debug($debugData);
     }
     $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody);
     if ($r) {
         $result->setXResponseCode((int) str_replace('"', '', $r[0]))->setXResponseReasonCode((int) str_replace('"', '', $r[2]))->setXResponseReasonText($r[3])->setXAvsCode($r[5])->setXTransId($r[6])->setXInvoiceNum($r[7])->setXAmount($r[9])->setXMethod($r[10])->setXType($r[11])->setData('x_MD5_Hash', $r[37])->setXAccountNumber($r[50]);
     } else {
         throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong in the payment gateway.'));
     }
     return $result;
 }
 /**
  * Tests client request with exception
  *
  * @return void
  */
 public function testSendRequestException()
 {
     $accId = '';
     $this->zendClientFactoryMock->expects($this->once())->method('create')->willReturn($this->zendClientMock);
     $this->configMock->expects($this->once())->method('getNewRelicAccountId')->willReturn($accId);
     $this->setExpectedException('Magento\\Framework\\Exception\\LocalizedException');
     $this->model->sendRequest();
 }
Exemple #14
0
 /**
  * Make a http request and return response body
  *
  * @param  string $url
  * @return string
  */
 protected function fetch($url)
 {
     $client = $this->httpClientFactory->create();
     $client->setUri($url);
     $client->setConfig(['maxredirects' => 5, 'timeout' => 30]);
     $client->setParameterGet('domain', $this->request->getHttpHost());
     return $client->request()->getBody();
 }
Exemple #15
0
 /**
  * Validate module using curl request
  *
  * @return boolean|array
  */
 public function validate()
 {
     if (!$this->canValidate()) {
         return true;
     }
     $key = trim($this->module->getIdentityKey());
     if (empty($key)) {
         return ['error' => ['Identity key is required']];
     }
     // key format is: encoded_site:secret_key:optional_suffix
     $parts = explode(':', $key);
     if (count($parts) < 3) {
         return ['error' => ['Identity key is not valid']];
     }
     list($site, $secret, $suffix) = explode(':', $key);
     try {
         $client = $this->httpClientFactory->create();
         $client->setUri($this->getUrl($site));
         $client->setConfig(['maxredirects' => 5, 'timeout' => 30]);
         $client->setParameterGet('key', $secret);
         $client->setParameterGet('suffix', $suffix);
         $purchaseCode = $this->module->getRemote()->getPurchaseCode();
         if (!$purchaseCode) {
             $purchaseCode = $this->module->getCode();
         }
         $client->setParameterGet('module', $purchaseCode);
         $client->setParameterGet('module_code', $this->module->getCode());
         if ($this->module->getConfigSection()) {
             $client->setParameterGet('config_section', $this->module->getConfigSection());
         }
         $client->setParameterGet('domain', $this->request->getHttpHost());
         $response = $client->request();
         $responseBody = $response->getBody();
     } catch (\Exception $e) {
         return ['error' => ['Response error: %1', $e->getMessage()], 'response' => $e->getTraceAsString()];
     }
     return $this->parseResponse($responseBody);
 }
 /**
  * Get Fixer.io service response
  *
  * @param string $url
  * @param int $retry
  * @return array
  */
 private function getServiceResponse($url, $retry = 0)
 {
     /** @var \Magento\Framework\HTTP\ZendClient $httpClient */
     $httpClient = $this->httpClientFactory->create();
     $response = [];
     try {
         $jsonResponse = $httpClient->setUri($url)->setConfig(['timeout' => $this->scopeConfig->getValue('currency/fixerio/timeout', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)])->request('GET')->getBody();
         $response = json_decode($jsonResponse, true);
     } catch (\Exception $e) {
         if ($retry == 0) {
             $response = $this->getServiceResponse($url, 1);
         }
     }
     return $response;
 }
 /**
  * Tests client request will fail
  */
 public function testSetDeploymentRequestFail()
 {
     $data = $this->getDataVariables();
     $this->zendClientMock->expects($this->once())->method('setUri')->with($data['uri'])->willReturnSelf();
     $this->zendClientMock->expects($this->once())->method('setMethod')->with($data['method'])->willReturnSelf();
     $this->zendClientMock->expects($this->once())->method('setHeaders')->with($data['headers'])->willReturnSelf();
     $this->zendClientMock->expects($this->once())->method('setParameterPost')->with($data['params'])->willReturnSelf();
     $this->configMock->expects($this->once())->method('getNewRelicApiUrl')->willReturn($data['uri']);
     $this->configMock->expects($this->once())->method('getNewRelicApiKey')->willReturn($data['api_key']);
     $this->configMock->expects($this->once())->method('getNewRelicAppName')->willReturn($data['app_name']);
     $this->configMock->expects($this->once())->method('getNewRelicAppId')->willReturn($data['app_id']);
     $this->zendClientMock->expects($this->once())->method('request')->willThrowException(new \Zend_Http_Client_Exception());
     $this->loggerMock->expects($this->once())->method('critical');
     $this->zendClientFactoryMock->expects($this->once())->method('create')->willReturn($this->zendClientMock);
     $this->assertInternalType('bool', $this->model->setDeployment($data['description'], $data['change'], $data['user']));
 }
 /**
  * @param $url
  * @param string $method
  * @param array $params
  * @return mixed
  * @throws Exception
  * @throws \Magento\Framework\Exception
  * @throws \Zend_Http_Client_Exception
  */
 protected function _httpRequest($url, $method = 'GET', $params = array())
 {
     $client = $this->_httpClientFactory->create();
     $client->setUri($url);
     switch ($method) {
         case 'GET':
             $client->setParameterGet($params);
             break;
         case 'POST':
             $client->setParameterPost($params);
             break;
         case 'DELETE':
             $client->setParameterGet($params);
             break;
         default:
             throw new \Magento\Framework\Exception(__('Required HTTP method is not supported.'));
     }
     $response = $client->request($method);
     $this->_helperData->log($response->getStatus() . ' - ' . $response->getBody());
     $decodedResponse = json_decode($response->getBody());
     /*
      * Per http://tools.ietf.org/html/draft-ietf-oauth-v2-27#section-5.1
      * Facebook should return data using the "application/json" media type.
      * Facebook violates OAuth2 specification and returns string. If this
      * ever gets fixed, following condition will not be used anymore.
      */
     if (empty($decodedResponse)) {
         $parsed_response = array();
         parse_str($response->getBody(), $parsed_response);
         $decodedResponse = json_decode(json_encode($parsed_response));
     }
     if ($response->isError()) {
         $status = $response->getStatus();
         if ($status == 400 || $status == 401) {
             if (isset($decodedResponse->error->message)) {
                 $message = $decodedResponse->error->message;
             } else {
                 $message = __('Unspecified OAuth error occurred.');
             }
             throw new \Inchoo\SocialConnect\Model\Facebook\Oauth2\Exception($message);
         } else {
             $message = sprintf(__('HTTP error %d occurred while issuing request.'), $status);
             throw new \Magento\Framework\Exception($message);
         }
     }
     return $decodedResponse;
 }
 /**
  * Get Fixer.io service response
  *
  * @param string $url
  * @param int $retry
  * @return array
  */
 private function getServiceResponse($url, $retry = 0)
 {
     /** @var \Magento\Framework\HTTP\ZendClient $httpClient */
     $httpClient = $this->httpClientFactory->create();
     $response = [];
     try {
         $jsonResponse = $httpClient->setUri($url)->setConfig(['timeout' => $this->scopeConfig->getValue($this->timeoutConfigPath, \Magento\Store\Model\ScopeInterface::SCOPE_STORE)])->request('GET')->getBody();
         $jsonResponse = json_decode($jsonResponse, true);
         if (!empty($jsonResponse['query']['results']['rate'])) {
             $response = array_column($jsonResponse['query']['results']['rate'], 'Rate', 'id');
         }
     } catch (\Exception $e) {
         if ($retry == 0) {
             $response = $this->getServiceResponse($url, 1);
         }
     }
     return $response;
 }
 public function getProperDimensionsPictureUrl($facebookId, $pictureUrl)
 {
     $url = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . '/inchoo/socialconnect/facebook/' . $facebookId;
     $filename = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $facebookId;
     $directory = dirname($filename);
     if (!file_exists($directory) || !is_dir($directory)) {
         if (!@mkdir($directory, 0777, true)) {
             return null;
         }
     }
     if (!file_exists($filename) || file_exists($filename) && time() - filemtime($filename) >= 3600) {
         $client = $this->_httpClientFactory->create($pictureUrl);
         $client->setStream();
         $response = $client->request('GET');
         stream_copy_to_stream($response->getStream(), fopen($filename, 'w'));
         $imageObj = $this->_imageFactory->create($filename);
         $imageObj->constrainOnly(true);
         $imageObj->keepAspectRatio(true);
         $imageObj->keepFrame(false);
         $imageObj->resize(150, 150);
         $imageObj->save($filename);
     }
     return $url;
 }
 /**
  * Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response
  *
  * @param \Magento\Framework\DataObject $request
  * @return \Magento\Framework\DataObject
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function _doShipmentRequest(\Magento\Framework\DataObject $request)
 {
     $this->_prepareShipmentRequest($request);
     $result = new \Magento\Framework\DataObject();
     $service = $this->getCode('service_to_code', $request->getShippingMethod());
     $recipientUSCountry = $this->_isUSCountry($request->getRecipientAddressCountryCode());
     if ($recipientUSCountry && $service == 'Priority Express') {
         $requestXml = $this->_formUsExpressShipmentRequest($request);
         $api = 'ExpressMailLabel';
     } else {
         if ($recipientUSCountry) {
             $requestXml = $this->_formUsSignatureConfirmationShipmentRequest($request, $service);
             if ($this->getConfigData('mode')) {
                 $api = 'SignatureConfirmationV3';
             } else {
                 $api = 'SignatureConfirmationCertifyV3';
             }
         } else {
             if ($service == 'First Class') {
                 $requestXml = $this->_formIntlShipmentRequest($request);
                 $api = 'FirstClassMailIntl';
             } else {
                 if ($service == 'Priority') {
                     $requestXml = $this->_formIntlShipmentRequest($request);
                     $api = 'PriorityMailIntl';
                 } else {
                     $requestXml = $this->_formIntlShipmentRequest($request);
                     $api = 'ExpressMailIntl';
                 }
             }
         }
     }
     $debugData = ['request' => $requestXml];
     $url = $this->getConfigData('gateway_secure_url');
     if (!$url) {
         $url = $this->_defaultGatewayUrl;
     }
     $client = $this->_httpClientFactory->create();
     $client->setUri($url);
     $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
     $client->setParameterGet('API', $api);
     $client->setParameterGet('XML', $requestXml);
     $response = $client->request()->getBody();
     $response = $this->parseXml($response);
     if ($response === false || $response->getName() == 'Error') {
         $debugData['result'] = ['error' => $response->Description, 'code' => $response->Number, 'xml' => $response->asXML()];
         $this->_debug($debugData);
         $result->setErrors($debugData['result']['error']);
     } else {
         if ($recipientUSCountry && $service == 'Priority Express') {
             $labelContent = base64_decode((string) $response->EMLabel);
             $trackingNumber = (string) $response->EMConfirmationNumber;
         } elseif ($recipientUSCountry) {
             $labelContent = base64_decode((string) $response->SignatureConfirmationLabel);
             $trackingNumber = (string) $response->SignatureConfirmationNumber;
         } else {
             $labelContent = base64_decode((string) $response->LabelImage);
             $trackingNumber = (string) $response->BarcodeNumber;
         }
         $result->setShippingLabelContent($labelContent);
         $result->setTrackingNumber($trackingNumber);
     }
     $result->setGatewayResponse($response);
     $debugData['result'] = $response;
     $this->_debug($debugData);
     return $result;
 }
Exemple #22
0
 /**
  * Do rate request and handle errors
  *
  * @return Result|\Magento\Framework\Object
  * @throws \Magento\Framework\Model\Exception
  */
 protected function _doRequest()
 {
     $rawRequest = $this->_request;
     $originRegion = $this->getCountryParams($this->_scopeConfig->getValue(Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $this->getStore()))->getRegion();
     if (!$originRegion) {
         throw new \Magento\Framework\Model\Exception(__('Wrong Region'));
     }
     if ($originRegion == 'AM') {
         $originRegion = '';
     }
     $xmlStr = '<?xml version="1.0" encoding="UTF-8"?>' . '<req:ShipmentValidateRequest' . $originRegion . ' xmlns:req="http://www.dhl.com"' . ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . ' xsi:schemaLocation="http://www.dhl.com ship-val-req' . ($originRegion ? '_' . $originRegion : '') . '.xsd" />';
     $xml = $this->_xmlElFactory->create(array('data' => $xmlStr));
     $nodeRequest = $xml->addChild('Request', '', '');
     $nodeServiceHeader = $nodeRequest->addChild('ServiceHeader');
     $nodeServiceHeader->addChild('SiteID', (string) $this->getConfigData('id'));
     $nodeServiceHeader->addChild('Password', (string) $this->getConfigData('password'));
     if (!$originRegion) {
         $xml->addChild('RequestedPickupTime', 'N', '');
     }
     $xml->addChild('NewShipper', 'N', '');
     $xml->addChild('LanguageCode', 'EN', '');
     $xml->addChild('PiecesEnabled', 'Y', '');
     /** Billing */
     $nodeBilling = $xml->addChild('Billing', '', '');
     $nodeBilling->addChild('ShipperAccountNumber', (string) $this->getConfigData('account'));
     /**
      * Method of Payment:
      * S (Shipper)
      * R (Receiver)
      * T (Third Party)
      */
     $nodeBilling->addChild('ShippingPaymentType', 'S');
     /**
      * Shipment bill to account – required if Shipping PaymentType is other than 'S'
      */
     $nodeBilling->addChild('BillingAccountNumber', (string) $this->getConfigData('account'));
     $nodeBilling->addChild('DutyPaymentType', 'S');
     $nodeBilling->addChild('DutyAccountNumber', (string) $this->getConfigData('account'));
     /** Receiver */
     $nodeConsignee = $xml->addChild('Consignee', '', '');
     $companyName = $rawRequest->getRecipientContactCompanyName() ? $rawRequest->getRecipientContactCompanyName() : $rawRequest->getRecipientContactPersonName();
     $nodeConsignee->addChild('CompanyName', substr($companyName, 0, 35));
     $address = $rawRequest->getRecipientAddressStreet1() . ' ' . $rawRequest->getRecipientAddressStreet2();
     $address = $this->string->split($address, 35, false, true);
     if (is_array($address)) {
         foreach ($address as $addressLine) {
             $nodeConsignee->addChild('AddressLine', $addressLine);
         }
     } else {
         $nodeConsignee->addChild('AddressLine', $address);
     }
     $nodeConsignee->addChild('City', $rawRequest->getRecipientAddressCity());
     $nodeConsignee->addChild('Division', $rawRequest->getRecipientAddressStateOrProvinceCode());
     $nodeConsignee->addChild('PostalCode', $rawRequest->getRecipientAddressPostalCode());
     $nodeConsignee->addChild('CountryCode', $rawRequest->getRecipientAddressCountryCode());
     $nodeConsignee->addChild('CountryName', $this->getCountryParams($rawRequest->getRecipientAddressCountryCode())->getName());
     $nodeContact = $nodeConsignee->addChild('Contact');
     $nodeContact->addChild('PersonName', substr($rawRequest->getRecipientContactPersonName(), 0, 34));
     $nodeContact->addChild('PhoneNumber', substr($rawRequest->getRecipientContactPhoneNumber(), 0, 24));
     /**
      * Commodity
      * The CommodityCode element contains commodity code for shipment contents. Its
      * value should lie in between 1 to 9999.This field is mandatory.
      */
     $nodeCommodity = $xml->addChild('Commodity', '', '');
     $nodeCommodity->addChild('CommodityCode', '1');
     $this->_checkDomesticStatus($rawRequest->getShipperAddressCountryCode(), $rawRequest->getRecipientAddressCountryCode());
     /** Dutiable */
     if ($this->getConfigData('content_type') == self::DHL_CONTENT_TYPE_NON_DOC && !$this->_isDomestic) {
         $nodeDutiable = $xml->addChild('Dutiable', '', '');
         $nodeDutiable->addChild('DeclaredValue', sprintf("%.2F", $rawRequest->getOrderShipment()->getOrder()->getSubtotal()));
         $baseCurrencyCode = $this->_storeManager->getWebsite($rawRequest->getWebsiteId())->getBaseCurrencyCode();
         $nodeDutiable->addChild('DeclaredCurrency', $baseCurrencyCode);
     }
     /**
      * Reference
      * This element identifies the reference information. It is an optional field in the
      * shipment validation request. Only the first reference will be taken currently.
      */
     $nodeReference = $xml->addChild('Reference', '', '');
     $nodeReference->addChild('ReferenceID', 'shipment reference');
     $nodeReference->addChild('ReferenceType', 'St');
     /** Shipment Details */
     $this->_shipmentDetails($xml, $rawRequest, $originRegion);
     /** Shipper */
     $nodeShipper = $xml->addChild('Shipper', '', '');
     $nodeShipper->addChild('ShipperID', (string) $this->getConfigData('account'));
     $nodeShipper->addChild('CompanyName', $rawRequest->getShipperContactCompanyName());
     $nodeShipper->addChild('RegisteredAccount', (string) $this->getConfigData('account'));
     $address = $rawRequest->getShipperAddressStreet1() . ' ' . $rawRequest->getShipperAddressStreet2();
     $address = $this->string->split($address, 35, false, true);
     if (is_array($address)) {
         foreach ($address as $addressLine) {
             $nodeShipper->addChild('AddressLine', $addressLine);
         }
     } else {
         $nodeShipper->addChild('AddressLine', $address);
     }
     $nodeShipper->addChild('City', $rawRequest->getShipperAddressCity());
     $nodeShipper->addChild('Division', $rawRequest->getShipperAddressStateOrProvinceCode());
     $nodeShipper->addChild('PostalCode', $rawRequest->getShipperAddressPostalCode());
     $nodeShipper->addChild('CountryCode', $rawRequest->getShipperAddressCountryCode());
     $nodeShipper->addChild('CountryName', $this->getCountryParams($rawRequest->getShipperAddressCountryCode())->getName());
     $nodeContact = $nodeShipper->addChild('Contact', '', '');
     $nodeContact->addChild('PersonName', substr($rawRequest->getShipperContactPersonName(), 0, 34));
     $nodeContact->addChild('PhoneNumber', substr($rawRequest->getShipperContactPhoneNumber(), 0, 24));
     $xml->addChild('LabelImageFormat', 'PDF', '');
     $request = $xml->asXML();
     if (!$request && !mb_detect_encoding($request) == 'UTF-8') {
         $request = utf8_encode($request);
     }
     $responseBody = $this->_getCachedQuotes($request);
     if ($responseBody === null) {
         $debugData = array('request' => $request);
         try {
             $client = $this->_httpClientFactory->create();
             $client->setUri((string) $this->getConfigData('gateway_url'));
             $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
             $client->setRawData($request);
             $responseBody = $client->request(\Magento\Framework\HTTP\ZendClient::POST)->getBody();
             $responseBody = utf8_decode($responseBody);
             $debugData['result'] = $responseBody;
             $this->_setCachedQuotes($request, $responseBody);
         } catch (\Exception $e) {
             $this->_errors[$e->getCode()] = $e->getMessage();
             $responseBody = '';
         }
         $this->_debug($debugData);
     }
     $this->_isShippingLabelFlag = true;
     return $this->_parseResponse($responseBody);
 }
Exemple #23
0
 /**
  * Post request to gateway and return response
  *
  * @param \Magento\Framework\Object $request
  * @return \Magento\Framework\Object
  * @throws \Exception
  */
 protected function _postRequest(\Magento\Framework\Object $request)
 {
     $debugData = array('request' => $request->getData());
     /** @var \Magento\Framework\HTTP\ZendClient $client */
     $client = $this->_httpClientFactory->create();
     $result = new \Magento\Framework\Object();
     $_config = array('maxredirects' => 5, 'timeout' => 30, 'verifypeer' => $this->getConfigData('verify_peer'));
     $_isProxy = $this->getConfigData('use_proxy', false);
     if ($_isProxy) {
         $_config['proxy'] = $this->getConfigData('proxy_host') . ':' . $this->getConfigData('proxy_port');
         //http://proxy.shr.secureserver.net:3128',
         $_config['httpproxytunnel'] = true;
         $_config['proxytype'] = CURLPROXY_HTTP;
     }
     $client->setUri($this->_getTransactionUrl())->setConfig($_config)->setMethod(\Zend_Http_Client::POST)->setParameterPost($request->getData())->setHeaders('X-VPS-VIT-CLIENT-CERTIFICATION-ID: 33baf5893fc2123d8b191d2d011b7fdc')->setHeaders('X-VPS-Request-ID: ' . $request->getRequestId())->setHeaders('X-VPS-CLIENT-TIMEOUT: ' . $this->_clientTimeout);
     try {
         /**
          * we are sending request to payflow pro without url encoding
          * so we set up _urlEncodeBody flag to false
          */
         $response = $client->setUrlEncodeBody(false)->request();
     } catch (\Exception $e) {
         $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage());
         $debugData['result'] = $result->getData();
         $this->_debug($debugData);
         throw $e;
     }
     $response = strstr($response->getBody(), 'RESULT');
     $valArray = explode('&', $response);
     foreach ($valArray as $val) {
         $valArray2 = explode('=', $val);
         $result->setData(strtolower($valArray2[0]), $valArray2[1]);
     }
     $result->setResultCode($result->getResult())->setRespmsg($result->getRespmsg());
     $debugData['result'] = $result->getData();
     $this->_debug($debugData);
     return $result;
 }