2013-08-16 3 views
0

У меня есть это приложение, которое обменивается данными с eBay Trading API с использованием PHP/XML. Он работает нормально 3 недели, но со вчерашнего дня мне больше не удалось подключиться.eBay Trading API - Не подключается - Время ожидания

Для простоты я создал очень простой скрипт для проверки связи, но я все еще придерживаюсь той же проблемы.

//show all errors - useful whilst developing 
error_reporting(E_ALL); 

// these keys can be obtained by registering at http://developer.ebay.com 

$production = true; // toggle to true if going against production 
$compatabilityLevel = 833; // eBay API version 
$siteID = 3;       // siteID needed in request - US=0, UK=3, DE=77... 

if ($production) { 
    $devID = '[devID]'; // these prod keys are different from sandbox keys 
    $appID = '[appID]'; 
    $certID = '[certID]'; 

    //set the Server to use (Sandbox or Production) 
    $serverUrl = 'https://api.ebay.com/ws/api.dll';  // server URL different for prod and sandbox 
    //the token representing the eBay user to assign the call with 
    $userToken = '[my_token]'; 
} 

class eBaySession { 

    private $requestToken; 
    private $devID; 
    private $appID; 
    private $certID; 
    private $serverUrl; 
    private $compatLevel; 
    private $siteID; 
    private $verb; 

    /**  __construct 
     Constructor to make a new instance of eBaySession with the details needed to make a call 
     Input: $userRequestToken - the authentication token fir the user making the call 
     $developerID - Developer key obtained when registered at http://developer.ebay.com 
     $applicationID - Application key obtained when registered at http://developer.ebay.com 
     $certificateID - Certificate key obtained when registered at http://developer.ebay.com 
     $useTestServer - Boolean, if true then Sandbox server is used, otherwise production server is used 
     $compatabilityLevel - API version this is compatable with 
     $siteToUseID - the Id of the eBay site to associate the call iwht (0 = US, 2 = Canada, 3 = UK, ...) 
     $callName - The name of the call being made (e.g. 'GeteBayOfficialTime') 
     Output: Response string returned by the server 
    */ 
    public function __construct($userRequestToken, $developerID, $applicationID, $certificateID, $serverUrl, $compatabilityLevel, $siteToUseID, $callName) { 
     $this->requestToken = $userRequestToken; 
     $this->devID = $developerID; 
     $this->appID = $applicationID; 
     $this->certID = $certificateID; 
     $this->compatLevel = $compatabilityLevel; 
     $this->siteID = $siteToUseID; 
     $this->verb = $callName; 
     $this->serverUrl = $serverUrl; 
    } 

    /**  sendHttpRequest 
     Sends a HTTP request to the server for this session 
     Input: $requestBody 
     Output: The HTTP Response as a String 
    */ 
    public function sendHttpRequest($requestBody) { 
     //build eBay headers using variables passed via constructor 
     $headers = $this->buildEbayHeaders(); 

     //initialise a CURL session 
     $connection = curl_init(); 
     //set the server we are using (could be Sandbox or Production server) 
     curl_setopt($connection, CURLOPT_URL, $this->serverUrl); 

     //stop CURL from verifying the peer's certificate 
     curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0); 
     curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0); 

     curl_setopt($connection, CURLOPT_VERBOSE, TRUE); 
     curl_setopt($connection, CURLOPT_TIMEOUT, 30); 

     //set the headers using the array of headers 
     curl_setopt($connection, CURLOPT_HTTPHEADER, $headers); 

     //set method as POST 
     curl_setopt($connection, CURLOPT_POST, 1); 

     //set the XML body of the request 
     curl_setopt($connection, CURLOPT_POSTFIELDS, $requestBody); 

     //set it to return the transfer as a string from curl_exec 
     curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1); 

     //Send the Request 
     $response = curl_exec($connection); 

     //close the connection 
     curl_close($connection); 

     //return the response 
     return $response; 
    } 

    /**  buildEbayHeaders 
     Generates an array of string to be used as the headers for the HTTP request to eBay 
     Output: String Array of Headers applicable for this call 
    */ 
    private function buildEbayHeaders() { 
     $headers = array(
      //Regulates versioning of the XML interface for the API 
      'X-EBAY-API-COMPATIBILITY-LEVEL: ' . $this->compatLevel, 
      //set the keys 
      'X-EBAY-API-DEV-NAME: ' . $this->devID, 
      'X-EBAY-API-APP-NAME: ' . $this->appID, 
      'X-EBAY-API-CERT-NAME: ' . $this->certID, 
      //the name of the call we are requesting 
      'X-EBAY-API-CALL-NAME: ' . $this->verb, 
      //SiteID must also be set in the Request's XML 
      //SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, .... 
      //SiteID Indicates the eBay site to associate the call with 
      'X-EBAY-API-SITEID: ' . $this->siteID, 
     ); 

     return $headers; 
    } 

} 
?> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<HTML> 
    <HEAD> 
     <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
     <TITLE>GeteBayOfficialTime</TITLE> 
    </HEAD> 
    <BODY> 

<?php 
//SiteID must also be set in the Request's XML 
//SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, .... 
//SiteID Indicates the eBay site to associate the call with 
$siteID = 3; 
//the call being made: 
$verb = 'GeteBayOfficialTime'; 
//Level/amount of data for the call to return (default = 0) 
$detailLevel = 0; 

///Build the request Xml string 
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>'; 
$requestXmlBody .= '<GeteBayOfficialTimeRequest xmlns="urn:ebay:apis:eBLBaseComponents">'; 
$requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>"; 
$requestXmlBody .= '</GeteBayOfficialTimeRequest>'; 

//Create a new eBay session with all details pulled in from included keys.php 
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb); 
//send the request and get response 
$responseXml = $session->sendHttpRequest($requestXmlBody); 
if (stristr($responseXml, 'HTTP 404') || $responseXml == '') 
    die('<P>Error sending request'); 

//Xml string is parsed and creates a DOM Document object 
$responseDoc = new DomDocument(); 
$responseDoc->loadXML($responseXml); 


//get any error nodes 
$errors = $responseDoc->getElementsByTagName('Errors'); 

//if there are error nodes 
if ($errors->length > 0) { 
    echo '<P><B>eBay returned the following error(s):</B>'; 
    //display each error 
    //Get error code, ShortMesaage and LongMessage 
    $code = $errors->item(0)->getElementsByTagName('ErrorCode'); 
    $shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage'); 
    $longMsg = $errors->item(0)->getElementsByTagName('LongMessage'); 
    //Display code and shortmessage 
    echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", "&gt;", str_replace("<", "&lt;", $shortMsg->item(0)->nodeValue)); 
    //if there is a long message (ie ErrorLevel=1), display it 
    if (count($longMsg) > 0) 
     echo '<BR>', str_replace(">", "&gt;", str_replace("<", "&lt;", $longMsg->item(0)->nodeValue)); 
} 
else { //no errors 
    //get the node containing the time and display its contents 
    $eBayTime = $responseDoc->getElementsByTagName('Timestamp'); 
    echo '<P><B>The Official eBay Time is ', $eBayTime->item(0)->nodeValue, ' GMT</B>'; 
} 
?> 

    </BODY> 
</HTML> 

Это выход:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<HTML> 
    <HEAD> 
     <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
     <TITLE>GeteBayOfficialTime</TITLE> 
    </HEAD> 
    <BODY> 

* About to connect() to api.ebay.com port 443 (#0) 
* Trying 66.135.211.100... * Timeout 
* Trying 66.135.211.140... * Timeout 
* Trying 66.211.179.150... * Timeout 
* Trying 66.211.179.180... * Timeout 
* Trying 66.135.211.101... * Timeout 
* Trying 66.211.179.148... * Timeout 
* connect() timed out! 
* Closing connection #0 
<P>Error sending request 

Факты:

  1. Я тестировал этот скрипт в 2-х совершенно разных серверах.
  2. Я сделал тот же звонок в eBay Online Testing Tool, и он отлично работает с моими eBay-ключами.
  3. Ничего не изменилось с кодом, так как проблема возникла.

Любой, у кого были подобные проблемы? Есть идеи?

Спасибо!

+0

Я новичок здесь, но я понял, что при попытке попробовать на двух разных серверах (например, в Бразилии и Великобритании) идентификатор сайта будет отличаться для двух разных стран: проблема? как для США это 0, а для Германии это 77 .... Я не знаю, если это проблема ... но мысль –

+0

Привет, на самом деле проблема была между моим хостингом (1 и 1) и eBay , Они (1 и 1) сказали мне, что eBay все время блокирует некоторые IP-адреса для подключения к ним API. Поэтому мне потребовалось пару дней, чтобы иметь возможность подключиться к API eBay, но ничего не случилось с приложением. :) – Pakeski

ответ

0

Я вижу ту же проблему со вчерашнего дня, но только на двух серверах (один в США, а другой в AU), а не на других.

Чтобы воспроизвести его на этих серверах, он даже не должен быть действительным запросом - просто отправка HTTP-запроса GET на https://api.ebay.com/wsapi?callname=GeteBayOfficialTime&siteid=0, который должен возвращать ошибку в формате XML, с той же ошибкой connect() timed out!, которую вы получили.

Что происходит, когда вы запускаете тот же код на другом сервере или на вашем локальном компьютере? Может быть, eBay начал блокировать запросы от некоторых IP-адресов?

Displaimer: Я знаю, что это не ответ, но я не могу добавить комментариев, и это может помочь найти модель ...

+0

Спасибо Мату, это интересно узнать. Я попытался запросить у двух разных серверов (Бразилия и Великобритания), так что это не должно быть проблемой блокировки IP-адресов. Использование HTTP GET-запроса, по крайней мере, я получаю ответ с ошибкой аутентификации. Я сделаю еще несколько тестов. Вы нашли обходное решение для серверов в США и Австралии, или вы все еще не подключаетесь? Приветствия! – Pakeski

+0

Странно, потому что на этих серверах, независимо от того, что я отправляю (GET или POST) на https://api.ebay.com, я всегда получаю сообщение об ошибке connect(). На серверах, где все работает, я получаю статус HTTP 500, но тело содержит ErrorCode 37, завернутый во множество XML. Так может быть, это не та же проблема? Но началось в то же время? Это становится странным ... – Matt

+0

Итак, теперь вы не можете подключиться к любому серверу? Это действительно странно. Теперь я могу подключиться к eBay с моего локального хоста, но не с любого другого сервера. И мне нужно использовать пакет EbatNs (пока не найду то, что отсутствует в моем коде). Я пробовал использовать все образцы eBay с нуля, но никто больше не работает. – Pakeski

1

Просто обновить: Проблемы была между моей службой хостинга (1 & 1) и eBay. Они (1 & 1) сказали мне, что eBay время от времени блокирует некоторые IP-адреса для подключения к ним API. Поэтому мне потребовалось пару дней, чтобы иметь возможность подключиться к API eBay, но ничего не случилось с приложением. Итак, иногда стоит проверить с вашим сервером хостинг-провайдера, поскольку они могут быть заблокированы моим eBay.

Смежные вопросы