Subversion Repositories cheapmusic

Rev

Rev 109 | Rev 129 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 - 1
<?php
65 - 2
include_once ('php/constants.php');
1 - 3
 
4
// Get eBay listings
110 - 5
function get_ebay($query, $searchCondition, $zipFlag = true) {
9 - 6
    $vendors = Vendors::getInstance();
10 - 7
    $config = $vendors->getVendor(Vendors::EBAY);
109 - 8
    $apicall = '[cached]';
13 - 9
 
110 - 10
    $resp = ($zipFlag ? getSearchCache("ebay", $query, $searchCondition) : false);
99 - 11
    if ($resp === false) {
12
        // API request variables
13
        $endpoint = 'https://svcs.ebay.com/services/search/FindingService/v1';
14
        $version = '1.13.0';
15
        $appid = $config['appid'];
16
        $trackingId = $config['trackingId'];
17
        $globalid = 'EBAY-US';
18
        $numResults = $config['numResults'];
1 - 19
 
99 - 20
        // Create a PHP array of the item filters you want to use in your request
21
        $filterarray = array(
22
            array(
23
                'name' => 'Condition',
24
                'value' => ($searchCondition == constant("NEW") ? 'New' : 'Used') ,
25
                'paramName' => '',
26
                'paramValue' => ''
65 - 27
            ) ,
99 - 28
            array(
29
                'name' => 'HideDuplicateItems',
30
                'value' => 'true',
31
                'paramName' => '',
32
                'paramValue' => ''
33
            ) ,
34
            array(
35
                'name' => 'ListingType',
36
                'value' => array(
37
                    'AuctionWithBIN',
38
                    'FixedPrice',
39
                    'StoreInventory'
40
                ) ,
41
                'paramName' => '',
42
                'paramValue' => ''
43
            ) ,
44
        );
1 - 45
 
99 - 46
        // Build the indexed item filter URL snippet
47
        $urlfilter = buildURLArray($filterarray);
1 - 48
 
99 - 49
        // Construct the findItemsByKeywords HTTP GET call
50
        $params = [];
51
        $params["OPERATION-NAME"] = "findItemsAdvanced";
52
        $params["SERVICE-VERSION"] = $version;
53
        $params["SECURITY-APPNAME"] = $appid;
54
        $params["GLOBAL-ID"] = $globalid;
55
        $params["REST-PAYLOAD"] = "";
56
        $params["affiliate.networkId"] = "9";
57
        $params["affiliate.trackingId"] = $trackingId;
58
        $params["affiliate.customId"] = "findCheapMusic";
59
        $params["paginationInput.entriesPerPage"] = $numResults;
60
        $params["sortOrder"] = "PricePlusShippingLowest";
110 - 61
        if (!empty($_SESSION["buyer"]["Zip"]) && $zipFlag) {
99 - 62
            $params["buyerPostalCode"] = $_SESSION["buyer"]["Zip"];
63
        }
64
        $params["outputSelector"] = "SellerInfo";
65
        $params["keywords"] = $query;
66
        if ($_SESSION["filterMediaType"]["CD"] && $_SESSION["filterMediaType"]["Record"]) {
67
            $params["categoryId(0)"] = "176985"; // Music Records
68
            $params["categoryId(1)"] = "176984"; // Music CDs
69
 
70
        }
71
        else if ($_SESSION["filterMediaType"]["CD"]) {
72
            $params["categoryId"] = "176984"; // Music CDs
73
 
74
        }
75
        else if ($_SESSION["filterMediaType"]["Record"]) {
76
            $params["categoryId"] = "176985"; // Music Records
77
 
78
        }
79
        $params = array_merge($params, $urlfilter);
1 - 80
 
99 - 81
        $pairs = array();
82
        foreach ($params as $key => $value) {
83
            array_push($pairs, rawurlencode($key) . (!empty($value) ? "=" . rawurlencode($value) : ""));
84
        }
85
        $canonical_query_string = join("&", $pairs);
81 - 86
 
99 - 87
        $apicall = $endpoint . "?" . $canonical_query_string;
81 - 88
 
99 - 89
        // Load the call and capture the document returned by eBay API
90
        $resp = getUrl($apicall);
91
        if (empty($resp)) {
92
            return ([]);
93
        }
94
        saveSearchCache("ebay", $query, $searchCondition, $resp);
89 - 95
    }
99 - 96
 
65 - 97
    $resp = simplexml_load_string($resp);
98
    $arr = array();
1 - 99
 
65 - 100
    // Check to see if the request was successful, else print an error
101
    if ((string)$resp->ack == "Success") {
102
        // If the response was loaded, parse it and store in array
103
        foreach ($resp
104
            ->searchResult->item as $item) {
105
            $title = (string)$item->title;
106
            $pic = str_replace('http://', 'https://', (string)$item->galleryURL);
107
            $url = str_replace('http://', 'https://', (string)$item->viewItemURL);
66 - 108
            $mediaType = (string)$item
65 - 109
                ->primaryCategory->categoryName;
66 - 110
            if ($mediaType == "CDs") {
111
                $mediaType = "CD";
65 - 112
            }
66 - 113
            else if ($mediaType == "CDs & DVDs") {
114
                $mediaType = "CD";
65 - 115
            }
66 - 116
            else if ($mediaType == "Records") {
117
                $mediaType = "Record";
65 - 118
            }
66 - 119
            $detailCondition = (string)$item
65 - 120
                ->condition->conditionDisplayName;
121
            $country = (string)$item->country;
81 - 122
            $bestOffer = (string)$item
65 - 123
                ->listingInfo->bestOfferEnabled;
124
            if ($item
125
                ->listingInfo->buyItNowAvailable == "true") {
126
                $price = (string)$item
127
                    ->listingInfo->convertedBuyItNowPrice;
128
                $currency = (string)$item
129
                    ->listingInfo
130
                    ->convertedBuyItNowPrice['currencyId'];
131
            }
132
            else {
133
                $price = (string)$item
134
                    ->sellingStatus->currentPrice;
135
                $currency = (string)$item
136
                    ->sellingStatus
137
                    ->currentPrice['currencyId'];
138
            }
139
            $price = number_format(floatval($price) , 2, '.', '');
140
            $timeLeft = decodeeBayTimeLeft($item
141
                ->sellingStatus
142
                ->timeLeft);
143
            $listingType = (string)$item
144
                ->listingInfo->listingType;
145
            $location = (string)$item->location;
146
            $zip = (string)$item->postalCode;
147
            $feedbackScore = (string)$item
148
                ->sellerInfo->feedbackScore;
149
            $feedbackPercent = (string)$item
150
                ->sellerInfo->positiveFeedbackPercent;
151
            $sellerName = (string)$item
152
                ->sellerInfo->sellerUserName;
153
            $handlingTime = (string)$item
154
                ->shippingInfo->handlingTime;
81 - 155
            $shippingEstimated = false;
65 - 156
            $shippingCost = number_format(floatval((string)$item
157
                ->shippingInfo
158
                ->shippingServiceCost) , 2, '.', '');
159
            $shippingCurrency = (string)$item
160
                ->shippingInfo
161
                ->shippingServiceCost['currencyId'];
81 - 162
            if ($shippingCost <= 0.00 && strpos($item->shippingInfo->shippingType, "Calculated") !== false) {
163
                $shippingCost = 3.00;
164
                $shippingCurrency = "USD";
165
                $shippingEstimated = true;
166
            }
1 - 167
 
65 - 168
            // skip items without gallery image
169
            if ($pic == "") {
170
                continue;
171
            }
1 - 172
 
65 - 173
            $arr[] = array(
174
                "Merchant" => "eBay",
66 - 175
                "Condition" => ($searchCondition == constant("NEW") ? 'New' : 'Used') ,
81 - 176
                "Title" => $title,
65 - 177
                "Barcode" => "",
178
                "BarcodeType" => "",
81 - 179
                "Image" => $pic,
180
                "URL" => $url,
181
                "MediaType" => $mediaType,
182
                "DetailCondition" => $detailCondition,
183
                "Country" => $country,
184
                "BestOffer" => $bestOffer,
185
                "TimeLeft" => $timeLeft,
186
                "Price" => $price,
187
                "Currency" => $currency,
188
                "ListingType" => $listingType,
189
                "Location" => $location,
190
                "Zip" => $zip,
191
                "FeedbackScore" => $feedbackScore,
192
                "FeedbackPercent" => $feedbackPercent,
193
                "SellerName" => $sellerName,
194
                "HandlingTime" => $handlingTime,
195
                "ShippingCost" => $shippingCost,
196
                "ShippingCurrency" => $shippingCurrency,
197
                "ShippingEstimated" => $shippingEstimated,
198
                "FreeShippingCap" => 0,
65 - 199
                "Show" => true
200
            );
201
        }
1 - 202
 
65 - 203
        return ($arr);
204
    }
205
    // If the response does not indicate 'Success,' log an error
206
    else {
105 - 207
        foreach ($resp->errorMessage->error as $error) {
96 - 208
            my_error_log($apicall);
209
            my_error_log("Severity: $error->severity; Category: $error->category; Domain: $error->domain; ErrorId: $error->errorId; Message: $error->message");
65 - 210
        }
110 - 211
 
212
        if ($error->errorId == 18 && $zipFlag) {
213
            my_error_log("Retry without zip code");
214
            return (get_ebay($query, $searchCondition, false));
215
        }
65 - 216
    }
110 - 217
 
218
    return ([]);
1 - 219
}
220
 
221
// Generates an indexed URL snippet from the array of item filters
65 - 222
function buildURLArray($filterarray) {
81 - 223
    $filter = [];
65 - 224
    $i = '0'; // Initialize the item filter index to 0
225
    // Iterate through each filter in the array
226
    foreach ($filterarray as $itemfilter) {
227
        // Iterate through each key in the filter
228
        foreach ($itemfilter as $key => $value) {
229
            if (is_array($value)) {
230
                foreach ($value as $j => $content) { // Index the key for each value
81 - 231
                    $filter["itemFilter($i).$key($j)"] = $content;
65 - 232
                }
233
            }
234
            else {
235
                if ($value != "") {
81 - 236
                    $filter["itemFilter($i).$key"] =$value;
65 - 237
                }
238
            }
239
        }
240
        $i++;
241
    }
13 - 242
 
81 - 243
    return $filter;
5 - 244
}
24 - 245
 
246
// convert "P##D##H##M##S" to "## days ## hours ## minutes left"
247
function decodeeBayTimeLeft($t) {
248
    preg_match_all('!\d+!', $t, $m);
249
 
250
    $s = "";
251
    if ($m[0][0] > 0) {
252
        $s .= $m[0][0] . " days ";
253
    }
254
 
255
    if ($m[0][1] > 0) {
256
        $s .= $m[0][1] . " hours ";
257
    }
258
 
259
    if ($m[0][2]) {
260
        $s .= $m[0][2] . " minutes left";
261
    }
65 - 262
 
263
    return $s;
264
}
265