Subversion Repositories cheapmusic

Rev

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

Rev Author Line No. Line
20 - 1
<?php
2
include_once('php/constants.php');
3
 
4
error_reporting(E_ALL);
5
// Get linkshare listings
6
function get_linkshare($query, $searchType) {
7
    $vendors = Vendors::getInstance();
8
    $config = $vendors->getVendor(Vendors::LINKSHARE);
9
 
10
    $token = getLinkshareToken($config);
11
 
12
    $arr = [];
13
    foreach($config["advertiser"] as $advertiser) {
14
        $arrTemp = get_linkshareAdvertiser($config, $token, $query, $searchType, $advertiser);
15
        $arr = array_merge($arr, $arrTemp);
16
    }
17
 
18
    return($arr);
19
}
20
 
21
// Get linkshare listings by advertiser id
22
function get_linkshareAdvertiser($config, $token, $query, $searchType, $advertiserId) {
23
// API request variables
24
	$safequery = urlencode($query);
25
	$numResults = $config['numResults'];
26
	$numResultsMid = $config['numResultsMid'];
27
	$resultsMid = [];
28
 
29
// Construct the findItemsByKeywords HTTP GET call
30
    $url = "https://api.rakutenmarketing.com/productsearch/1.0";
31
    $url .= "?keyword=" . $safequery;
32
    $url .= "&max=" . $numResults;
33
    $url .= "&pagenumber=1";
34
    $url .= "&sort=retailprice";
35
    $url .= "&sorttype=asc";
36
    $url .= "&mid=" . $advertiserId;
37
 
38
    $header = array(
39
        'Content-Type: application/x-www-form-urlencoded',
40
        'Accept: application/xml',
41
        'Accept-Language: en-US,en;q=0.5',
42
        'Accept-Charset: UTF-8,*;q=0.5',
43
        'Authorization: Bearer ' . $token
44
        );
45
 
46
    $ch = curl_init();
47
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
48
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
49
    curl_setopt($ch, CURLOPT_URL, $url);
50
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
51
    curl_setopt($ch, CURLOPT_HEADER, 0);
52
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
53
    $result = curl_exec ($ch);
54
 
55
	$result = utf8_encode($result);
56
	$result = simplexml_load_string($result);
57
 
58
    curl_close($ch);
59
 
23 - 60
//echo "$url<br><pre>";print_r($result);echo "</pre>";
21 - 61
 
20 - 62
	$arr = [];
63
 
64
// Check to see if the request found any results
65
	if (isset($result->TotalMatches)) {
66
  // If the response was loaded, parse it and store in array
67
		foreach ($result->item as $item) {
21 - 68
 
69
 
70
 
20 - 71
			$merchantId = strval($item->mid);
72
			$merchantName = (string)$item->merchantname;
73
			$barcode = (string)$item->upccode;
74
			$barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
75
 
76
            // approved: SamAsh, alibris
77
 
78
			$title = (string)$item->productname;
79
			$pic = str_replace('http://', 'https://', (string)$item->imageurl);
80
			if (empty($pic)) {
81
			    continue;
82
			}
83
			$url = str_replace('http://', 'https://', (string)$item->linkurl);
84
			if (empty($url)) {
85
			    continue;
86
			}
87
 
21 - 88
			switch ($merchantId) {
89
			    case 35126: // Sam Ash Music
90
			        if ($item->category->primary == "Books/Dvds") {
91
                        $type = 'NEW';
92
   	    			    $condition = "Brand New";
93
    	    			$category = "Book";
94
    	    		} else {
95
    	    		    continue;
96
    	    		}
97
			        break;
98
 
99
			    case 13770: // Music Notes
100
                    $type = 'NEW';
101
   				    $condition = "Brand New";
102
    				$category = "Book";
103
			        break;
104
 
105
			    case 2653: // alibris (does not return any search results) bugbug
106
			        break;
107
 
108
   				default:
109
                    $type = 'USED';
110
   				    $condition = "Used";
111
    				$category = "CD";
112
    				break;
20 - 113
			}
114
 
115
			$country = 'US';
116
			$bestOffer = false;
117
 
118
			$price = 0;
119
			if (!empty($item->price) && !empty($item->saleprice)) {
120
    			$price = minNotNull(array($item->price, $item->saleprice));
121
    		} else if (!empty($item->price)) {
122
    			$price = $item->price;
123
    		} else if (!empty($item->saleprice)) {
124
    			$price = $item->saleprice;
125
    		}
126
			$price = number_format(floatval($price), 2, '.', '');
127
			if ($price <= "0.00") {
128
			    continue;
129
			}
130
 
131
			$currency = 'USD';
132
			$timeLeft = 0;
133
			$listingType = 'Fixed';
134
			$location = 'US';
135
			$zip = '';
136
			$feedbackScore = -1;
137
			$feedbackPercent = -1;
138
			$sellerName = '';
139
			$handlingTime = -1;
140
			$shippingCost = 0.00;
141
			$shippingCurrency = 'USD';
142
 
143
// bugbug
21 - 144
//ls_cj_csv(array($merchantName,(string)$item->category->primary,(string)$item->productname,(string)$item->description->short,"'".$barcode,$barcodeType,minNotNull(array($item->price, (string)$item->saleprice)),(string)$item->linkurl));
20 - 145
 
146
            // this is last after all checks
147
			$resultsMid[] = $merchantId;
148
			if (array_count_values($resultsMid)[$merchantId] > $numResultsMid) {
149
			    continue;
150
			}
151
 
152
			$arr[] = array(
153
				"Merchant" => $merchantName,
154
				"Type" => ($searchType == constant("NEW") ? 'New' : 'Used'),
155
				"Title" => "$title",
156
				"Barcode" => "$barcode",
157
				"BarcodeType" => "$barcodeType",
158
				"Image" => "$pic",
159
				"URL" => "$url",
160
				"Category" => "$category",
161
				"Condition" => "$condition",
162
				"Country" => "$country",
163
				"BestOffer" => "$bestOffer",
164
				"TimeLeft" => "$timeLeft",
165
				"Price" => "$price",
166
				"Currency" => "$currency",
167
				"ListingType" => "$listingType",
168
				"Location" => "$location",
169
				"Zip" => "$zip",
170
				"FeedbackScore" => "$feedbackScore",
171
				"FeedbackPercent" => "$feedbackPercent",
172
				"SellerName" => "$sellerName",
173
				"HandlingTime" => "$handlingTime",
174
				"ShippingCost" => "$shippingCost",
175
				"ShippingCurrency" => "$shippingCurrency",
176
				"Show" => true
177
			);
178
		}
179
	}
180
// If the response does not indicate 'Success,' log the error(s)
181
	else {
182
		foreach ($result->Errors as $error) {
183
		    if ($error->ErrorID != "7186919") { // no product found, not an error
184
    			error_log($url);
185
	    		error_log("$error->ErrorText ($error->ErrorId)");
186
	    	}
187
		}
188
	}
189
 
190
	return $arr;
191
}
192
 
193
// Get Linkshare Bearer Token
194
function getLinkshareToken($config)
195
{
196
    static $expiration = 0;
197
    static $accessToken = '';
198
    static $refreshToken = '';
199
 
200
    if ($expiration == 0 || time() > $expiration) {
201
        $url="https://api.rakutenmarketing.com/token";
202
        $postdata = "grant_type=password&username=" . $config['user'] . "&password=" . $config['password'] . "&scope=" . $config['scope'];
203
        $header = array(
204
            'Content-Type: application/x-www-form-urlencoded',
205
            'Authorization: ' . $config['authorizationToken']
206
            );
207
 
208
        $ch = curl_init();
209
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
210
        curl_setopt($ch, CURLOPT_URL, $url);
211
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
212
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
213
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
214
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
215
        curl_setopt($ch, CURLOPT_REFERER, $url);
216
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
217
        curl_setopt($ch, CURLOPT_POST, 1);
218
        $result = json_decode(curl_exec ($ch));
219
 
220
        curl_close($ch);
221
 
222
        $expiration = time() + $result->{'expires_in'};
223
        $accessToken = $result->{'access_token'};
224
        $refreshToken = $result->{'refresh_token'};
225
        $tokenType =  $result->{'token_type'};
226
    }
227
 
228
	return $accessToken;
229
}