How to get eBay item URL based on item ID - php

I would like to get the item URL based on the item ID. After searching, I found that I can use GetSingleItem to achieve my goal. However, I got an error:
eBay returned the following error(s):
2 : Unsupported API call.
The API call "GetSingleItem" is invalid or not supported in this release.
Here is my code (all configuration are correct because I can use GetOrders by using these configs):
$subverb = "GetSingleItem";
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetSingleItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= "<ItemID>111986554711</ItemID>";
$requestXmlBody .= '</GetSingleItemRequest>';
//Create a new eBay session with all details pulled in from included keys.php
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $subverb);
//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');
$response = simplexml_import_dom($responseDoc);
$entries = $response->PaginationResult->TotalNumberOfEntries;
//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(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
//if there is a long message (ie ErrorLevel=1), display it
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
} else { //If there are no errors, continue
if (isset($_GET['debug'])) {
header("Content-type: text/xml");
print_r($responseXml);
} else {
print("\n; 111986554711: " . $response->Item->ViewItemURLForNaturalSearch);
}
}
Any suggestion? Thank you .

As you discovered, you don't need the API to construct a simple eBay view item landing page URL.
The URL format you discovered works, but it's very old and might not be supported in full or for much longer.
Here's a simple URL format that is pretty current that you can use:
http://www.ebay.com/itm/122225724269

I got an answer without using api. Here is the answer: after I got item ID, I can use "http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=".$item_id to show my product on ebay.
I found this uri by using GetOrders API.
OrderArray.Order .TransactionArray.Transaction .Variation .VariationViewItemURL
Tip: "not optimized for natural search"
If anyone has any idea about "GetSingleItem", I am willing to know why my code doesn't work.

Related

PHP eBay GetOrders API (Unable To fetch Any Data)

I am Trying to fetch ebay orders by using getOrders API, when i execute ebay PHP SDK it print:
"Sorry No entries found in the Time period requested. Change CreateTimeFrom/CreateTimeTo and Try again"
Please Help me...
Official ebay PHP SDK code :
<?php
/* © 2013 eBay Inc., All Rights Reserved */
/* Licensed under CDDL 1.0 - http://opensource.org/licenses/cddl1.php */
?>
<?php require_once('get-common/keys.php') ; //include keys file for auth token and other credentials ?>
<?php require_once('get-common/eBaySession.php') ; //include session file for curl operations ?>
<?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 = 0;
//the call being made:
$verb = 'GetOrders';
//Time with respect to GMT
//by default retreive orders in last 30 minutes
$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-(2*40*24*60*60)); //current time minus 80 Days
//echo "</br>";
$CreateTimeTo = gmdate("Y-m-d\TH:i:s");
//If you want to hard code From and To timings, Follow the below format in "GMT".
//$CreateTimeFrom = YYYY-MM-DDTHH:MM:SS; //GMT
//$CreateTimeTo = YYYY-MM-DDTHH:MM:SS; //GMT
///Build the request Xml string
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
$requestXmlBody .= "<CreateTimeFrom>".$CreateTimeFrom."</CreateTimeFrom><CreateTimeTo>".$CreateTimeTo."</CreateTimeTo>";
$requestXmlBody .= '<OrderRole>Seller</OrderRole><OrderStatus>All</OrderStatus>';
$requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
$requestXmlBody.="<WarningLevel>High</WarningLevel>";
$requestXmlBody .= '</GetOrdersRequest>';
//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');
//echo "<pre>";
//var_dump($responseXml);
//die;
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
//get any error nodes
$errors = $responseDoc->getElementsByTagName('Errors');
$response = simplexml_import_dom($responseDoc);
$entries = $response->PaginationResult->TotalNumberOfEntries;
//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(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
//if there is a long message (ie ErrorLevel=1), display it
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
}else { //If there are no errors, continue
if(isset($_GET['debug']))
{
header("Content-type: text/xml");
print_r($responseXml);
}else
{ //$responseXml is parsed in view.php
include_once 'view.php';
}
}
?>
I would recommend the ebay-sdk-php from devbay.net :
https://github.com/davidtsadler/ebay-sdk-php
https://github.com/davidtsadler/ebay-sdk-examples
As for the date, I could be wrong, but I think it requires DateTime. Something like
CreateTimeFrom = new DateTime('02-10-2016');
CreateTimeTo = new DateTime('02-11-2016');
But I think you will have an easier time with the ebay-sdk-php
edit:
Actually I've been messing around with this more lately.
The default works for me
$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-1800); //current time minus 30 minutes
$CreateTimeTo = gmdate("Y-m-d\TH:i:s");
or you can hardcode your range like the following:
//If you want to hard code From and To timings, Follow the below format in "GMT".
//$CreateTimeFrom = YYYY-MM-DDTHH:MM:SS; //GMT
//$CreateTimeTo = YYYY-MM-DDTHH:MM:SS; //GMT
such as the following:
$CreateTimeFrom = '2017-03-20T00:00:00Z'; //GMT
$CreateTimeTo = '2017-03-22T00:00:00Z'; //GMT
Alternatively, you can just simply not use CreatedTimeTo and CreatedTimeFrom and use NumberOfDays instead
which is basically just commenting out CreatedTimeTo and CreatedTimeFrom
//$requestXmlBody .= "<CreateTimeFrom>$CreateTimeFrom</CreateTimeFrom><CreateTimeTo>$CreateTimeTo</CreateTimeTo>";
and directly underneath it use NumberOfDays
$requestXmlBody .= "<NumberOfDays>2</NumberOfDays>";

Get all items with all details in XML format

I am trying to get all items using the ebay API in XML format.
See the below code for the same.
require_once('config/ebay_config.php');
require_once('helpers/eBaySession.php');
session_start();
//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 = 0;
//the call being made:
$verb = 'GetSellerList';
///Build the request Xml string
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetSellerListRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= '<EndTimeFrom>2015-12-12T11:36:06.487Z</EndTimeFrom>';
$requestXmlBody .= '<EndTimeTo>2016-03-12T11:36:06.487Z</EndTimeTo>';
$requestXmlBody .= '<RequesterCredentials><eBayAuthToken>' . $userToken . '</eBayAuthToken></RequesterCredentials>';
$requestXmlBody .= '<UserID>****</UserID>';
$requestXmlBody .= '<DetailLevel>ItemReturnDescription</DetailLevel>';
$requestXmlBody .= '<Pagination><EntriesPerPage>200</EntriesPerPage><PageNumber>1</PageNumber></Pagination>';
$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);
$errors = $responseDoc->getElementsByTagName('Errors');
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');
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
echo '<BR/>User Session ID: ' . $_COOKIE["eBaySession"] . '';
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
}
else { //no errors
//get the nodes needed
$sellerNode = $responseDoc->getElementsByTagName('Seller');
if ($sellerNode->length > 0) {
echo '<P><B>Seller</B>';
$userIDNode = $sellerNode->item(0)->getElementsByTagName('UserID');
$scoreNode = $sellerNode->item(0)->getElementsByTagName('FeedbackScore');
$regDateNode = $sellerNode->item(0)->getElementsByTagName('RegistrationDate');
echo '<BR>UserID: ', $userIDNode->item(0)->nodeValue;
echo '<BR>Feedback Score: ', $scoreNode->item(0)->nodeValue;
echo '<BR>Registration Date: ', $regDateNode->item(0)->nodeValue;
}
}
It just returns seller info, but give advice for the get all items with all details.
And also one more thing, I'm done with login ebay API, and also get a success message on ebay site from below URL but I want to throw on a particular PHP page with userid.
https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RuName=<?php echo $RuName; ?>&SessID=<?php echo $sessionID; ?>
Presuming that when you say 'All Items' you mean that you want to retrieve all seller listings:
You need to change your DetailLevel node in your initial request to 'ReturnAll'. See the following API page for details. Please note, it is not technically recommended to use the ReturnAll DetailLevel, so you may want to find precisely what you need and only return that level of detail.
eBay GetSellerList
If you are looking for All Items in a category or something (ie not associated with your seller account) you need to use the finding API if I recall correctly.. I originally said advertising but that's not eBay =p

PayPal DoVoid function is not voiding

I have a dovoid function I've taken from various tutorials for the classic api (the rest of our site uses the classic api, so I'm stuck using it until i can gut the thing and use the better apis). The function appears to execute and I am not getting error messages, but I am not seeing the transactions voided in the sandbox.
Here is the dovoid function:
public function DoVoid($auth_id,$note)
{
$xml = '<?xml version="1.0" encoding="UTF-8"?>'.
ENV:Envelope
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
'.
'<SOAP-ENV:Header>
'.
'<RequesterCredentials
xmlns="urn:ebay:api:PayPalAPI"
SOAP-ENV:mustUnderstand="1">
'.
'<Credentials xmlns="urn:ebay:apis:eBLBaseComponents">
'.
'<Username>'.utf8_encode($PayPalApiUsername).'</Username> '.
'<Password>'.utf8_encode($PayPalApiPassword).'</Password> '.
'<Subject>'.utf8_encode("Voiding Transaction").'</Subject>'.
'
</Credentials>'.
'
</RequesterCredentials>'.
'
</SOAP-ENV:Header>'.
'<SOAP-ENV:Body>
'.
'<DoVoidReq xmlns="urn:ebay:api:PayPalAPI">
'.
'<DoVoidRequest xmlns="urn:ebay:api:PayPalAPI">
'.
'<Version xmlns="urn:ebay:apis:eBLBaseComponents"
xsi:type="xsd:string">60.0</Version>'.
'<AuthorizationID>'.utf8_encode($auth_id).'</AuthorizationID>'.
'<Note>'.utf8_encode($note).'</Note>'.
'
</DoVoidRequest>'.
'
</DoVoidReq>'.
'
</SOAP-ENV:Body>'.
'
</SOAP-ENV:Envelope>';
//send query
$response = $this->sendQuery($xml);
if ($response)
{
//check XML response data
if (isset($response["SOAP-ENV:Envelope"][0]["SOAP-ENV:Body"][0]["DoVoidResponse"][0]))
{
$a = $response["SOAP-ENV:Envelope"][0]["SOAP-ENV:Body"][0]["DoVoidResponse"][0];
//check is there transaction error
if (isset($a["Errors"]))
{
$this->is_error = true;
foreach ($a["Errors"] as $key=>$value)
{
$this->error_messages[] = $value["ShortMessage"][0].(trim($value["ShortMessage"][0])!=trim($value["LongMessage"][0])?(" - ".$value["LongMessage"][0]):"");
}
return $this->error_messages;
}
//potentially all is good
else
{
$this->PaymentAction = $a;
//check tocken is the same as sent
if ($a["Ack"][0] == "Success")
{
if (isset($a["AuthorizationID"][0]))
{
//return payment data
return $a["AuthorizationID"][0];
}
}
else
{
$this->is_error = true;
$this->error_messages[] = "Incorrect transaction status";
return false;
}
}
}
}
}
Now one thing I am not sure of (since I just started using this API) is what the authorization ID should look like. Currently, the ones I am pulling from elsewhere in our system start with "ec_" which I don't think is correct. What should these authorization ids look like for voiding?
What I am trying to do is void an authorization when the order's values change, as we have had a lot of trouble with people getting multiple pending transactions because they change their order, reauthorize, and our system gets confused. While I am trying to fix the larger structural problems, I need this as a short term fix so we only have one active authorization per order.
In order to void an authorization you will need to reference it's transaction ID. The string that begins with "EC" is the secure token. A PayPal transaction ID contains 16 alphanumeric characters, for example 5DE44868BF3911546.

How to put XML into my SoapClient Call using a Method

I have generated some XML which is saved to a file.
Dummy_Order.xml
In the following code I wanted to open the XML and use it in the method 'ImpOrders'
Here is my code
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$proxy = new SoapClient('http://soapclient/wsdl/Web?wsdl', array ('trace' => 1));
if (file_exists('Dummy_Order.xml')) {
$xml = file_get_contents('Dummy_Order.xml');
} else {
exit('Failed to open XML.');
}
$xmlstring = new SimpleXMLElement($xml);
$result = $proxy->ImportOrders($xmlstring);
var_dump($result);
echo "REQUEST:\n" . $proxy->__getLastRequest() . "\n";
?>
I am getting a response in $result of 0 imported 0 skipped. So i then did getLastRequest() and it's adding the code from the Method but not adding my XML. It wants my XML in a string - which it current is in and isnt moaning about that (It does moan if i use it ->asXML).
I have tried
$result = $proxy->ImportOrders();
and
$result = $proxy->ImportOrders($xmlstring);
And both show the same result in _getLastRequest, which led me to believe that my string isn't being plugged in.
When I check the functions using _getFunctions it provides the information of this...
ImportResult ImportOrders(string $Orders)
Any help would be awesome!
Ok so i resolved it. All i needed to do was wrap my answer in <<
Like below.
$teststring = <<<XML
$xml
XML;
$result = $proxy->ImportOrders($teststring);
Hope this helps out anyone else using PHP, SoapClient and XML.

PHP - RSS builder

I have a old website that generate its own RSS everytime a new post is created. Everything worked when I was on a server with PHP 4 but now that the host change to PHP 5, I always have a "bad formed XML". I was using xml_parser_create() and xml_parse(...) and fwrite(..) to save everything.
Here is the example when saving (I read before save to append old RSS line of course).
function SaveXml()
{
if (!is_file($this->getFileName()))
{
//Création du fichier
$file_handler = fopen($this->getFileName(),"w");
fwrite($file_handler,"");
fclose($file_handler);
}//Fin du if
//Header xml version="1.0" encoding="utf-8"
$strFileData = '<?xml version="1.0" encoding="iso-8859-1" ?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>'.$this->getProjectName().'</title><link>http://www.mywebsite.com</link><description>My description</description><lastBuildDate>' . date("r"). '</lastBuildDate>';
//Data
reset($this->arrData);
foreach($this->arrData as $i => $value)
{
$strFileData .= '<item>';
$strFileData .= '<title>'. $this->GetNews($i,0) . '</title>';
$strFileData .= '<pubDate>'. $this->GetNews($i,1) . '</pubDate>';
$strFileData .= '<dc:creator>'. $this->GetNews($i,2) . '</dc:creator>';
$strFileData .= '<description><![CDATA['. $this->GetNews($i,3) . ']]> </description>';
$strFileData .= '<link><![CDATA['. $this->GetNews($i,4) . ']]></link>';
$strFileData .= '<guid>'. $this->GetNews($i,4) . '</guid>';
//$strFileData .= '<category>'. $this->GetNews($i,5) . '</category>';
$strFileData .= '<category>Mycategory</category>';
$strFileData .= '</item>';
}//Fin du for i
$strFileData .= '</channel></rss>';
if (file_exists($this->getFileName()))//Détruit le fichier
unlink($this->getFileName());
$file_handler = fopen($this->getFileName(),"w");
fwrite($file_handler,$strFileData);
fclose($file_handler);
}//Fin de SaveXml
My question is : how do you create and fill up your RSS in PHP?
At swcombine.com we use Feedcreator. Use that one and your problem will be gone. :)
Here is the PHP code to use it once installed:
function feed_simnews() {
$objRSS = new UniversalFeedCreator();
$objRSS->title = 'My News';
$objRSS->link = 'http://link.to/news.php';
$objRSS->description = 'daily news from me';
$objRSS->xsl = 'http://link.to/feeds/feedxsl.xsl';
$objRSS->language = 'en';
$objRSS->copyright = 'Copyright: Mine!';
$objRSS->webmaster = 'webmaster#somewhere.com';
$objRSS->syndicationURL = 'http://link.to/news/simnews.php';
$objRSS->ttl = 180;
$objImage = new FeedImage();
$objImage->title = 'my logo';
$objImage->url = 'http://link.to/feeds/logo.jpg';
$objImage->link = 'http://link.to';
$objImage->description = 'Feed provided by link.to. Click to visit.';
$objImage->width = 120;
$objImage->height = 60;
$objRSS->image = $objImage;
//Function retrieving an array of your news from date start to last week
$colNews = getYourNews(array('start_date' => 'Last week'));
foreach($colNews as $p) {
$objItem = new FeedItem();
$objItem->title = $p->title;
$objItem->description = $p->body;
$objItem->link = $p->link;
$objItem->date = $p->date;
$objItem->author = $p->author;
$objItem->guid = $p->guid;
$objRSS->addItem($objItem);
}
$objRSS->saveFeed('RSS2.0', 'http://link.to/feeds/news.xml', false);
};
Quite KISS. :)
I would use simpleXML to create the required structure and export the XML. Then I'd cache it to disk with file_put_contents().
I've used this LGPL-licensed feedcreator class in the past and it worked quite well for the very simple use I had for it.
Not a full answer, but you don't have to parse your own XML. It will hurt performance and reliability.
But definitely make sure it is well-formed. It shouldn't be very hard if you generate it by hand or using general-purpose tools. Or maybe your included HTML ruins it?
There are lots of things that can make XML malformed. It might be a problem with character entities (a '<', '>', or '&' in the data between the XML tags). Try running anything output from a database through htmlentities() when you concatenate the string. Do you have an example of the generated XML for us to look at so we can see where the problem is?
PHP5 now comes with the SimpleXML extension, it's a pretty quick way to build valid XML if your needs aren't complicated.
However, the problem you're suggesting doesn't seem to an issue of implementation more a problem of syntax. Perhaps you could update your question with a code example, or, a copy of the XML that is produced.

Categories