Subversion Repositories cheapmusic

Rev

Rev 24 | Rev 66 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
include_once ('php/constants.php');

// Get eBay listings
function get_ebay($query, $searchType) {
    $vendors = Vendors::getInstance();
    $config = $vendors->getVendor(Vendors::EBAY);

    // API request variables
    $endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';
    $version = '1.13.0';
    $appid = $config['appid'];
    $trackingId = $config['trackingId'];
    $globalid = 'EBAY-US';
    $safequery = urlencode($query);
    $numResults = $config['numResults'];

    // Create a PHP array of the item filters you want to use in your request
    $filterarray = array(
        array(
            'name' => 'Condition',
            'value' => ($searchType == 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
    $apicall = "$endpoint?";
    $apicall .= "OPERATION-NAME=findItemsAdvanced";
    $apicall .= "&SERVICE-VERSION=$version";
    $apicall .= "&SECURITY-APPNAME=$appid";
    $apicall .= "&GLOBAL-ID=$globalid";
    $apicall .= "&REST-PAYLOAD";
    $apicall .= "&affiliate.networkId=9";
    $apicall .= "&affiliate.trackingId=$trackingId";
    $apicall .= "&affiliate.customId=findCheapMusic";
    $apicall .= "&paginationInput.entriesPerPage=$numResults";
    $apicall .= "&sortOrder=PricePlusShippingLowest";
    if (isset($_SESSION['buyer"]["Zip'])) {
        $apicall .= "&buyerPostalCode=" . $_SESSION['buyer"]["Zip'];
    }
    $apicall .= "&outputSelector=SellerInfo";
    $apicall .= "&keywords=$safequery";
    if ($_SESSION["filterMediaType"]["CD"] && $_SESSION["filterMediaType"]["Record"]) {
        $apicall .= "&categoryId(0)=176985"; // Music Records
        $apicall .= "&categoryId(1)=176984"; // Music CDs
        
    }
    else if ($_SESSION["filterMediaType"]["CD"]) {
        $apicall .= "&categoryId=176984"; // Music CDs
        
    }
    else if ($_SESSION["filterMediaType"]["Record"]) {
        $apicall .= "&categoryId=176985"; // Music Records
        
    }
    $apicall .= "$urlfilter";

    // Load the call and capture the document returned by eBay API
    $resp = getUrl($apicall);
    $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);
            $category = (string)$item
                ->primaryCategory->categoryName;
            if ($category == "CDs") {
                $category = "CD";
            }
            else if ($category == "CDs & DVDs") {
                $category = "CD";
            }
            else if ($category == "Records") {
                $category = "Record";
            }
            $condition = (string)$item
                ->condition->conditionDisplayName;
            $country = (string)$item->country;
            $bestOffer = $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;
            $shippingCost = number_format(floatval((string)$item
                ->shippingInfo
                ->shippingServiceCost) , 2, '.', '');
            $shippingCurrency = (string)$item
                ->shippingInfo
                ->shippingServiceCost['currencyId'];

            // skip items without gallery image
            if ($pic == "") {
                continue;
            }

            $arr[] = array(
                "Merchant" => "eBay",
                "Type" => ($searchType == constant("NEW") ? 'New' : 'Used') ,
                "Title" => "$title",
                "Barcode" => "",
                "BarcodeType" => "",
                "Image" => "$pic",
                "URL" => "$url",
                "Category" => "$category",
                "Condition" => "$condition",
                "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",
                "FreeShippingCap" => "0",
                "Show" => true
            );
        }

        return ($arr);
    }
    // If the response does not indicate 'Success,' log an error
    else {
        foreach ($resp
            ->errorMessage->error as $error) {
            error_log($apicall);
            error_log("Severity: $error->severity; Category: $error->category; Domain: $error->domain; ErrorId: $error->errorId; Message: $error->message");
        }
        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;
}