Subversion Repositories cheapmusic

Rev

Rev 21 | Go to most recent revision | Details | 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
 
60
	$arr = [];
61
 
62
// Check to see if the request found any results
63
	if (isset($result->TotalMatches)) {
64
  // If the response was loaded, parse it and store in array
65
		foreach ($result->item as $item) {
66
			$merchantId = strval($item->mid);
67
			$merchantName = (string)$item->merchantname;
68
			$barcode = (string)$item->upccode;
69
			$barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);
70
 
71
            // approved: SamAsh, alibris
72
 
73
			$title = (string)$item->productname;
74
			$pic = str_replace('http://', 'https://', (string)$item->imageurl);
75
			if (empty($pic)) {
76
			    continue;
77
			}
78
			$url = str_replace('http://', 'https://', (string)$item->linkurl);
79
			if (empty($url)) {
80
			    continue;
81
			}
82
 
83
			// bugbug check categories by merchant
84
			$category = (string)$item->category->primary;
85
			if ($category == "CDs") { //bugbug
86
				$category = "CD";
87
			}
88
 
89
			$condition = 'Brand New';
90
			$country = 'US';
91
			$bestOffer = false;
92
 
93
			$price = 0;
94
			if (!empty($item->price) && !empty($item->saleprice)) {
95
    			$price = minNotNull(array($item->price, $item->saleprice));
96
    		} else if (!empty($item->price)) {
97
    			$price = $item->price;
98
    		} else if (!empty($item->saleprice)) {
99
    			$price = $item->saleprice;
100
    		}
101
			$price = number_format(floatval($price), 2, '.', '');
102
			if ($price <= "0.00") {
103
			    continue;
104
			}
105
 
106
			$currency = 'USD';
107
			$timeLeft = 0;
108
			$listingType = 'Fixed';
109
			$location = 'US';
110
			$zip = '';
111
			$feedbackScore = -1;
112
			$feedbackPercent = -1;
113
			$sellerName = '';
114
			$handlingTime = -1;
115
			$shippingCost = 0.00;
116
			$shippingCurrency = 'USD';
117
 
118
// bugbug
119
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));
120
 
121
            // this is last after all checks
122
			$resultsMid[] = $merchantId;
123
			if (array_count_values($resultsMid)[$merchantId] > $numResultsMid) {
124
			    continue;
125
			}
126
 
127
			$arr[] = array(
128
				"Merchant" => $merchantName,
129
				"Type" => ($searchType == constant("NEW") ? 'New' : 'Used'),
130
				"Title" => "$title",
131
				"Barcode" => "$barcode",
132
				"BarcodeType" => "$barcodeType",
133
				"Image" => "$pic",
134
				"URL" => "$url",
135
				"Category" => "$category",
136
				"Condition" => "$condition",
137
				"Country" => "$country",
138
				"BestOffer" => "$bestOffer",
139
				"TimeLeft" => "$timeLeft",
140
				"Price" => "$price",
141
				"Currency" => "$currency",
142
				"ListingType" => "$listingType",
143
				"Location" => "$location",
144
				"Zip" => "$zip",
145
				"FeedbackScore" => "$feedbackScore",
146
				"FeedbackPercent" => "$feedbackPercent",
147
				"SellerName" => "$sellerName",
148
				"HandlingTime" => "$handlingTime",
149
				"ShippingCost" => "$shippingCost",
150
				"ShippingCurrency" => "$shippingCurrency",
151
				"Show" => true
152
			);
153
		}
154
	}
155
// If the response does not indicate 'Success,' log the error(s)
156
	else {
157
		foreach ($result->Errors as $error) {
158
		    if ($error->ErrorID != "7186919") { // no product found, not an error
159
    			error_log($url);
160
	    		error_log("$error->ErrorText ($error->ErrorId)");
161
	    	}
162
		}
163
	}
164
 
165
	return $arr;
166
}
167
 
168
// Get Linkshare Bearer Token
169
function getLinkshareToken($config)
170
{
171
    static $expiration = 0;
172
    static $accessToken = '';
173
    static $refreshToken = '';
174
 
175
    if ($expiration == 0 || time() > $expiration) {
176
        $url="https://api.rakutenmarketing.com/token";
177
        $postdata = "grant_type=password&username=" . $config['user'] . "&password=" . $config['password'] . "&scope=" . $config['scope'];
178
        $header = array(
179
            'Content-Type: application/x-www-form-urlencoded',
180
            'Authorization: ' . $config['authorizationToken']
181
            );
182
 
183
        $ch = curl_init();
184
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
185
        curl_setopt($ch, CURLOPT_URL, $url);
186
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
187
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
188
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
189
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
190
        curl_setopt($ch, CURLOPT_REFERER, $url);
191
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
192
        curl_setopt($ch, CURLOPT_POST, 1);
193
        $result = json_decode(curl_exec ($ch));
194
 
195
        curl_close($ch);
196
 
197
        $expiration = time() + $result->{'expires_in'};
198
        $accessToken = $result->{'access_token'};
199
        $refreshToken = $result->{'refresh_token'};
200
        $tokenType =  $result->{'token_type'};
201
    }
202
 
203
	return $accessToken;
204
}