Rev 129 | Blame | Compare with Previous | Last modification | View Log | RSS feed
<?php
include_once ('php/constants.php');
// Get eBay listings
function get_ebay($query, $searchCondition, $zipFlag = true) {
$vendors = Vendors::getInstance();
$config = $vendors->getVendor(Vendors::EBAY);
$apicall = '[cached]';
$resp = ($zipFlag ? getSearchCache("ebay", $query, $searchCondition) : false);
if ($resp === false) {
// API request variables
$endpoint = 'https://svcs.ebay.com/services/search/FindingService/v1';
$version = '1.13.0';
$appid = $config['appid'];
$trackingId = $config['trackingId'];
$globalid = 'EBAY-US';
$numResults = $config['numResults'];
// Create a PHP array of the item filters you want to use in your request
$filterarray = array(
array(
'name' => 'Condition',
'value' => ($searchCondition == constant("NEW") ? 'New' : 'Used') ,
'paramName' => '',
'paramValue' => ''
) ,
array(
'name' => 'HideDuplicateItems',
'value' => 'true',
'paramName' => '',
'paramValue' => ''
) ,
array(
'name' => 'ListingType',
'value' => array(
'AuctionWithBIN',
'FixedPrice',
'StoreInventory'
) ,
'paramName' => '',
'paramValue' => ''
) ,
);
// Build the indexed item filter URL snippet
$urlfilter = buildURLArray($filterarray);
// Construct the findItemsByKeywords HTTP GET call
$params = [];
$params["OPERATION-NAME"] = "findItemsAdvanced";
$params["SERVICE-VERSION"] = $version;
$params["SECURITY-APPNAME"] = $appid;
$params["GLOBAL-ID"] = $globalid;
$params["REST-PAYLOAD"] = "";
$params["affiliate.networkId"] = "9";
$params["affiliate.trackingId"] = $trackingId;
$params["affiliate.customId"] = "findCheapMusic";
$params["paginationInput.entriesPerPage"] = $numResults;
$params["sortOrder"] = "PricePlusShippingLowest";
if (!empty($_SESSION["buyer"]["Zip"]) && $zipFlag) {
$params["buyerPostalCode"] = $_SESSION["buyer"]["Zip"];
}
$params["outputSelector"] = "SellerInfo";
$params["keywords"] = $query;
if ($_SESSION["filterMediaType"]["CD"] && $_SESSION["filterMediaType"]["Record"]) {
$params["categoryId(0)"] = "176985"; // Music Records
$params["categoryId(1)"] = "176984"; // Music CDs
}
else if ($_SESSION["filterMediaType"]["CD"]) {
$params["categoryId"] = "176984"; // Music CDs
}
else if ($_SESSION["filterMediaType"]["Record"]) {
$params["categoryId"] = "176985"; // Music Records
}
$params = array_merge($params, $urlfilter);
$pairs = array();
foreach ($params as $key => $value) {
array_push($pairs, rawurlencode($key) . (!empty($value) ? "=" . rawurlencode($value) : ""));
}
$canonical_query_string = join("&", $pairs);
$apicall = $endpoint . "?" . $canonical_query_string;
// Load the call and capture the document returned by eBay API
$resp = getUrl($apicall);
if (empty($resp)) {
return ([]);
}
saveSearchCache("ebay", $query, $searchCondition, $resp);
}
$resp = simplexml_load_string($resp);
$arr = array();
// Check to see if the request was successful, else print an error
if ((string)$resp->ack == "Success") {
// If the response was loaded, parse it and store in array
foreach ($resp
->searchResult->item as $item) {
$title = (string)$item->title;
$pic = str_replace('http://', 'https://', (string)$item->galleryURL);
$url = str_replace('http://', 'https://', (string)$item->viewItemURL);
$mediaType = (string)$item
->primaryCategory->categoryName;
if ($mediaType == "CDs") {
$mediaType = "CD";
}
else if ($mediaType == "CDs & DVDs") {
$mediaType = "CD";
}
else if ($mediaType == "Records") {
$mediaType = "Record";
}
else if ($mediaType == "Disques") {
$mediaType = "Record";
}
$detailCondition = (string)$item
->condition->conditionDisplayName;
$country = (string)$item->country;
$bestOffer = (string)$item
->listingInfo->bestOfferEnabled;
if ($item
->listingInfo->buyItNowAvailable == "true") {
$price = (string)$item
->listingInfo->convertedBuyItNowPrice;
$currency = (string)$item
->listingInfo
->convertedBuyItNowPrice['currencyId'];
}
else {
$price = (string)$item
->sellingStatus->currentPrice;
$currency = (string)$item
->sellingStatus
->currentPrice['currencyId'];
}
$price = number_format(floatval($price) , 2, '.', '');
$timeLeft = decodeeBayTimeLeft($item
->sellingStatus
->timeLeft);
$listingType = (string)$item
->listingInfo->listingType;
$location = (string)$item->location;
$zip = (string)$item->postalCode;
$feedbackScore = (string)$item
->sellerInfo->feedbackScore;
$feedbackPercent = (string)$item
->sellerInfo->positiveFeedbackPercent;
$sellerName = (string)$item
->sellerInfo->sellerUserName;
$handlingTime = (string)$item
->shippingInfo->handlingTime;
$shippingEstimated = false;
$shippingCost = number_format(floatval((string)$item
->shippingInfo
->shippingServiceCost) , 2, '.', '');
$shippingCurrency = (string)$item
->shippingInfo
->shippingServiceCost['currencyId'];
if ($shippingCost <= 0.00 && strpos($item->shippingInfo->shippingType, "Calculated") !== false) {
$shippingCost = 3.00;
$shippingCurrency = "USD";
$shippingEstimated = true;
}
// skip items without gallery image
if ($pic == "") {
continue;
}
$arr[] = array(
"Merchant" => "eBay",
"Condition" => ($searchCondition == constant("NEW") ? 'New' : 'Used') ,
"Title" => $title,
"Barcode" => "",
"BarcodeType" => "",
"Image" => $pic,
"URL" => $url,
"MediaType" => $mediaType,
"DetailCondition" => $detailCondition,
"Country" => $country,
"BestOffer" => $bestOffer,
"TimeLeft" => $timeLeft,
"Price" => $price,
"Currency" => $currency,
"ListingType" => $listingType,
"Location" => $location,
"Zip" => $zip,
"FeedbackScore" => $feedbackScore,
"FeedbackPercent" => $feedbackPercent,
"SellerName" => $sellerName,
"HandlingTime" => $handlingTime,
"ShippingCost" => $shippingCost,
"ShippingCurrency" => $shippingCurrency,
"ShippingEstimated" => $shippingEstimated,
"FreeShippingCap" => 0,
"Show" => true,
"Details" => ""
);
}
return ($arr);
}
// If the response does not indicate 'Success,' log an error
else {
foreach ($resp->errorMessage->error as $error) {
my_error_log($apicall);
my_error_log("Severity: $error->severity; Category: $error->category; Domain: $error->domain; ErrorId: $error->errorId; Message: $error->message");
}
if ($error->errorId == 18 && $zipFlag) {
my_error_log("Retry without zip code");
return (get_ebay($query, $searchCondition, false));
}
}
return ([]);
}
// Generates an indexed URL snippet from the array of item filters
function buildURLArray($filterarray) {
$filter = [];
$i = '0'; // Initialize the item filter index to 0
// Iterate through each filter in the array
foreach ($filterarray as $itemfilter) {
// Iterate through each key in the filter
foreach ($itemfilter as $key => $value) {
if (is_array($value)) {
foreach ($value as $j => $content) { // Index the key for each value
$filter["itemFilter($i).$key($j)"] = $content;
}
}
else {
if ($value != "") {
$filter["itemFilter($i).$key"] =$value;
}
}
}
$i++;
}
return $filter;
}
// convert "P##D##H##M##S" to "## days ## hours ## minutes left"
function decodeeBayTimeLeft($t) {
preg_match_all('!\d+!', $t, $m);
$s = "";
if ($m[0][0] > 0) {
$s .= $m[0][0] . " days ";
}
if ($m[0][1] > 0) {
$s .= $m[0][1] . " hours ";
}
if ($m[0][2]) {
$s .= $m[0][2] . " minutes left";
}
return $s;
}