PHP eBay GetOrders API (Unable To fetch Any Data) - php

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>";

Related

How to get eBay item URL based on item ID

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.

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

How to conect php with tally?

I want to connect php with tally and I want to store ledger in tally with php any idea?
I got reference from different site like :
1) http://www.tallysolutions.com/website/html/tallydeveloper/integration-capabilities.php
2)http://stackoverflow.com/questions/15717941/how-to-insert-data-into-tally-using-php
But it doesn't fulfill my requirement.
Thanks in advance
It's may help you
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
$envelope = $doc->appendChild($doc->createElement('ENVELOPE'));
//Header Section
$header = $envelope->appendChild($doc->createElement('HEADER'));
$version = $header->appendChild($doc->createElement('VERSION','6.3'));
$import = $header->appendChild($doc->createElement('TALLYREQUEST','Import'));
$type = $header->appendChild($doc->createElement('TYPE','Data'));
$id = $header->appendChild($doc->createElement('ID','All Masters'));
//End Header Section
//Body Section
$body = $envelope->appendChild($doc->createElement('BODY'));
$desc = $body->appendChild($doc->createElement('DESC'));
$static_var = $desc->appendChild($doc->createElement('STATICVARIABLES'));
$dup_combine = $static_var->appendChild($doc->createElement('IMPORTDUPS','##DUPCOMBINE'));
$data = $body->appendChild($doc->createElement('DATA'));
$tally_msg = $data->appendChild($doc->createElement('TALLYMESSAGE'));
//Ledger Data
foreach($contacts_data as $key => $value){
$ledger = $tally_msg->appendChild($doc->createElement('LEDGER'));
$parent=$ledger->appendChild($doc->createElement('PARENT',($value['contacts_types_id']=='1')?'Sundry Debtors':'Sundry Creditors'));
$name=$ledger->appendChild($doc->createElement('NAME',trim(str_replace( "&"," AND ",$value['name']))));
$address=$ledger->appendChild($doc->createElement('ADDRESS',trim(str_replace( "&"," AND ",$value['address']))));
$state=$ledger->appendChild($doc->createElement('STATENAME',trim(str_replace( "&"," AND ",$value['state_name']))));
$pincode=$ledger->appendChild($doc->createElement('PINCODE',$value['pincode']));
/*$ledger_contact=$ledger->appendChild($doc->createElement('LEDGERCONTACT',trim(str_replace( "&"," AND ",$value['contact_person']))));
$phone=$ledger->appendChild($doc->createElement('LEDGERPHONE',$value['phone']));
$fax=$ledger->appendChild($doc->createElement('LEDGERFAX',$value['fax']));
$mobile_no=$ledger->appendChild($doc->createElement('MOBILENO',$value['mobile_no']));
$sales_tax_no=$ledger->appendChild($doc->createElement('SALESTAXNO','23456789'));
$pan_no=$ledger->appendChild($doc->createElement('PANNO','453456789'));*/
$o['contacts_id'][]=$value['id'];
}
//End Ledger and Body Section
//Write the XML nodes
$fp = fopen(public_path()."/xml/import_tally/ledger.xml","wb");
if(fwrite($fp,$doc->saveXML())){
$o['tally_rslt']= shell_exec("curl -X POST tally_server_ip:port --data #".public_path()."/xml/import_tally/ledger.xml");
$o['modified_result']=strpos(preg_replace('/[0-9]+/', '', $o['tally_rslt']),'exists');
}
fclose($fp);
return $o;

Set a reminder for a Google Calendar event using PHP

I am developing a site to add events to a Google Calendar using code from this blog post.
Now I want to set a reminder for each event that is set 15 minutes before the event.
Can anyone give me some direction on how to achieve this?
Setting a reminder when creating an event is very easy. You just have to add a couple additional lines to the <gd:when></gd:when> tag.
<gd:when startTime='2006-03-30T22:00:00.000Z' endTime='2006-03-30T23:00:00.000Z'>
<gd:reminder minutes='15' method='email' />
<gd:reminder minutes='15' method='alert' />
</gd:when>
Here's an updated addEvent() method that includes support for reminders:
public function addEvent($params) {
$url = "http://www.google.com/calendar/feeds/{$this->getFeedEmail()}/private/full";
//startTime should be a time() value so we can convert it into the correct format
$params["startTime"] = date("c", $params["startTime"]);
//If no end-time is specified, set the end-time to 1 hour after the start-time
if(!array_key_exists("endTime", $params)) {
$params["endTime"] = date("c", strtotime($params["startTime"])+60*60*1);
}
$reminders = '';
if(is_array($params['reminders'])) {
foreach($params['reminders'] as $rem) {
$reminders .= "<gd:reminder minutes='{$rem['minutes']}' method='{$rem['method']}' />"\n;
}
}
$xml = "<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event"></category>
<title type="text">{$params["title"]}</title>
<content type="text">{$params["content"]}</content>
<gd:transparency value="http://schemas.google.com/g/2005#event.opaque">
</gd:transparency>
<gd:eventstatus value="http://schemas.google.com/g/2005#event.confirmed">
</gd:eventstatus>
<gd:where valuestring="{$params["where"]}"></gd:where>
<gd:when starttime="{$params["startTime"]}" endtime="{$params["endTime"]}">
{$reminders}
</gd:when>
</entry>";
//Do the initial POST to Google
$ret = $this->calPostRequest($url, $xml);
//If Google sends back a gsessionid, we need to make the request again
$matches = array();
if(preg_match('/gsessionid=(.*?)\s+/', $ret, $matches)) {
$url .= "?gsessionid={$matches[1]}";
$ret = $this->calPostRequest($url, $xml);
}
//Parse the XML response (which contains the newly added entry)
$retFields = explode("\n", $ret);
//print_r($retFields);
$entryXML = simplexml_load_string($retFields[count($retFields)-1]);
//Return an array containing the entry id (url) and the etag
return array(
"id"=> (string)$entryXML->id,
"etag"=> $this->getETagFromHeader($retFields),
"link"=> $this->getEditLinkFromHeader($retFields)
);
}
And you would call it like this:
$entryData = $cal->addEvent(array(
"title"=> "Auto Test event",
"content"=> "This is a test event",
"where"=> "Test location",
"startTime"=> time()+60*60*24*1,
"reminders"=> array(
array("method"=>"email", "minutes"=>"15"),
array("method"=>"alert", "minutes"=>"15"),
)
));

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