Subversion Repositories cheapmusic

Rev

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

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

error_reporting(E_ALL);
// Get linkshare listings
function get_linkshare($query, $searchType) {
    $vendors = Vendors::getInstance();
    $config = $vendors->getVendor(Vendors::LINKSHARE);

    $token = getLinkshareToken($config);
    if ($token === false) {
        return [];
    }

    $arr = [];
    foreach ($config["advertiser"] as $advertiser) {
        $arrTemp = get_linkshareAdvertiser($config, $token, $query, $searchType, $advertiser);
        $arr = array_merge($arr, $arrTemp);
    }

    return ($arr);
}

// Get linkshare listings by advertiser id
function get_linkshareAdvertiser($config, $token, $query, $searchType, $advertiserId) {
    // API request variables
    $safequery = urlencode($query);
    $numResults = $config['numResults'];
    $numResultsMid = $config['numResultsMid'];
    $resultsMid = [];

    // Construct the findItemsByKeywords HTTP GET call
    $url = "https://api.rakutenmarketing.com/productsearch/1.0";
    $url .= "?keyword=" . $safequery;
    $url .= "&max=" . $numResults;
    $url .= "&pagenumber=1";
    $url .= "&sort=retailprice";
    $url .= "&sorttype=asc";
    $url .= "&mid=" . $advertiserId;

    $header = array(
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: application/xml',
        'Accept-Language: en-US,en;q=0.5',
        'Accept-Charset: UTF-8,*;q=0.5',
        'Authorization: Bearer ' . $token
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

    $result = utf8_encode($result);
    $result = simplexml_load_string($result);

    curl_close($ch);

    //echo "$url<br><pre>";print_r($result);echo "</pre>";
    $arr = [];

    // Check to see if the request found any results
    if (isset($result->TotalMatches)) {
        // If the response was loaded, parse it and store in array
        foreach ($result->item as $item) {
            $merchantId = strval($item->mid);
            $merchantName = (string)$item->merchantname;
            $barcode = (string)$item->upccode;
            $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);

            $title = (string)$item->productname;
            $pic = str_replace('http://', 'https://', (string)$item->imageurl);
            if (empty($pic)) {
                continue;
            }
            $url = str_replace('http://', 'https://', (string)$item->linkurl);
            if (empty($url)) {
                continue;
            }

            $country = 'US';

            switch ($merchantId) {
                case 35126: // Sam Ash Music
                    if ($item
                        ->category->primary == "Books/Dvds") {
                        $type = 'New';
                        $condition = "Brand New";
                        $category = "Book";
                        $freeShippingCap = 0.00; // 9.99 on webpage
                        $handlingTime = 1;
                        $shippingCost = 0.00;
                        $shippingCurrency = 'USD';
                    }
                    else {
                        continue 2; // next loop
                        
                    }
                break;

                case 13770: // Music Notes
                    $type = 'New';
                    $condition = "Brand New";
                    $category = "Book";
                    $freeShippingCap = 0.00;
                    $handlingTime = 1;
                    $shippingCost = 0.00;
                    $shippingCurrency = 'USD';
                break;

                case 2653: // alibris
                    
                case 24390: // alibris uk
                    if ($item
                        ->category->primary == "Media > Music" || $item
                        ->category->primary == "Media > Dvds & Movies") {
                        $category = "CD";
                    }
                    else {
                        $category = "Book";
                    }
                    $type = 'Used';
                    $condition = "Used";
                    $handlingTime = 1;
                    if ($merchantId == 2653) {
                        $shippingCost = 3.99;
                        $freeShippingCap = 39.00;
                    }
                    else { /* 24390 */
                        $shippingCost = 4.25;
                        $freeShippingCap = 0.00;
                        $country = 'GB';
                    }
                    $shippingCurrency = 'USD';
                break;

                default:
                    $type = 'Used';
                    $condition = "Used";
                    $category = "CD";
                    $freeShippingCap = 0.00;
                    $handlingTime = - 1;
                    $shippingCost = 0.00;
                    $shippingCurrency = 'USD';
                break;
            }

            $bestOffer = false;

            $price = 0;
            if (!empty($item->price) && !empty($item->saleprice)) {
                $price = minNotNull(array(
                    $item->price,
                    $item->saleprice
                ));
            }
            else if (!empty($item->price)) {
                $price = $item->price;
            }
            else if (!empty($item->saleprice)) {
                $price = $item->saleprice;
            }
            $price = number_format(floatval($price) , 2, '.', '');
            if ($price <= "0.00") {
                continue;
            }

            $currency = 'USD';
            $timeLeft = 0;
            $listingType = 'Fixed';
            $location = 'US';
            $zip = '';
            $feedbackScore = - 1;
            $feedbackPercent = - 1;
            $sellerName = '';

            // bugbug
            //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));
            // this is last after all checks
            $resultsMid[] = $merchantId;
            if (array_count_values($resultsMid) [$merchantId] > $numResultsMid) {
                continue;
            }

            $arr[] = array(
                "Merchant" => $merchantName,
                "Type" => "$type",
                "Title" => "$title",
                "Barcode" => "$barcode",
                "BarcodeType" => "$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" => "$freeShippingCap",
                "Show" => true
            );
        }
    }
    // If the response does not indicate 'Success,' log the error(s)
    else {
        foreach ($result->Errors as $error) {
            if ($error->ErrorID != "7186919") { // no product found, not an error
                error_log($url);
                error_log("$error->ErrorText ($error->ErrorId)");
            }
        }
    }

    return $arr;
}

// Get Linkshare Bearer Token
function getLinkshareToken($config) {
    static $expiration = 0;
    static $accessToken = '';
    static $refreshToken = '';

    if ($expiration == 0 || time() > $expiration) {
        $url = "https://api.rakutenmarketing.com/token";
        $postdata = "grant_type=password&username=" . $config['user'] . "&password=" . $config['password'] . "&scope=" . $config['scope'];
        $header = array(
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: ' . $config['authorizationToken']
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_POST, 1);
        $result = curl_exec($ch);
        $result = json_decode($result);
        curl_close($ch);

        if (empty($result)) {
            return false;
        }

        $expiration = time() + $result->{'expires_in'};
        $accessToken = $result->{'access_token'};
        $refreshToken = $result->{'refresh_token'};
        $tokenType = $result->{'token_type'};
    }

    return $accessToken;
}

// get linkshare coupon codes
function get_linkshareCoupons() {
    $vendors = Vendors::getInstance();
    $config = $vendors->getVendor(Vendors::LINKSHARE);

    $token = getLinkshareToken($config);
    if ($token === false) {
        return [];
    }

    // Construct the findItemsByKeywords HTTP GET call
    $url = "https://api.rakutenmarketing.com/coupon/1.0?category=22&network=1&resultsperpage=100&pagenumber=1";

    $header = array(
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: application/xml',
        'Accept-Language: en-US,en;q=0.5',
        'Accept-Charset: UTF-8,*;q=0.5',
        'Authorization: Bearer ' . $token
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

    $result = utf8_encode($result);
    $result = simplexml_load_string($result);

    curl_close($ch);

    //echo "$url<br><pre>";print_r($result);echo "</pre>";
    $arr = [];

    // Check to see if the request found any results
    if (isset($result->TotalMatches)) {
        // If the response was loaded, parse it and store in array
        foreach ($result->link as $link) {
            echo "NULL";
            echo "," . $link->advertisername;
            echo "," . $link->offerstartdate;
            echo "," . $link->offerenddate;
            echo ",\"" . $link->offerdescription . "\"";
            echo "," . $link->couponcode;
            echo "," . str_replace('http://', 'https://', (string)$link->clickurl);
            echo "," . str_replace('http://', 'https://', (string)$link->impressionpixel);
            echo "<br>";
        }
    }
    // If the response does not indicate 'Success,' log the error(s)
    else {
        foreach ($result->Errors as $error) {
            if ($error->ErrorID != "7186919") { // no product found, not an error
                error_log($url);
                error_log("$error->ErrorText ($error->ErrorId)");
            }
        }
    }

    return $arr;
}