How to Program a Commission Junction and LinkShare Price Tracker | 2010-06-18

Technology Blog » Web Development

CJ (formally called commission junction) and LinkShare are two major affiliate network on the Internet. Because of their messy documentation on their web service or the high complexity to read its API, here I would like to share the application that I wrote to keep track of the prices of specific item from their web services (SOAP XML). Such as Nintendo Wii Tracker/Watcher, PS3 Tracker, etc. You could sightly modify my code to target on the product you want to display.
OK, here you go with the partial code I wrote, basically there are two file:

  • grabber.php
    is used to grab file from the XML server and save as local cache file.
  • watcher.php
    us used to present the result by reading the saved cache fie

It should be very clear to understand, right? Thing complicate should be how do I code the iteration of these two different web services and integrated into one application.

CODES in detail: Here I use Wii Tracker as an example:

wii_grabber.php

<?php
/*
    The following codes are written by [email protected]
    PCinvent.com All Rights Reserved
    Please keep the above line credit to the author!
*/

//start buffer
ob_start();

################################### START OF GLOBAL VARIBLES ################################################
$foldername = "watchers_usdt";
$filename    = "wii_console";
//$filename    = date("Y.m.d.H.i.s");
//var_dump($filename);
##################################### END OF GLOBAL VARIBLES ################################################

########################################### START OF EXECUTE ################################################
runLinkShareAPI();
runCJAPI();
############################################# END OF EXECUTE ################################################

############################################### START of Linkshare #########################################*/
function runLinkShareAPI(){
    //SETTINGS
    $apiurl = "http://feed.linksynergy.com/productsearch";
    $tokenkey = "1234 PLEASE PUT YOUR OWN KEY HERE"; //LinkShare Web Service Token
    $keyword="wii";//What to search
    $exact="wii bundle";
    $one="";
    $cat="";//What Category
    $none="for Nintendo";//exclusion
    $MaxResults="100";
    $Page="";
    $sort="mid";
    $sorttype="asc";
    $resturl = $apiurl."?"."token=".$tokenkey."&keyword=".$keyword."&exact=".$exact."&one=".$one."&cat=".$cat."&MaxResults=".$MaxResults."&Page=".$Page."&sort=".$sort."&sorttype=".$sorttype;
    
    $SafeQuery = urlencode($resturl);
    $ResponseXML = simplexml_load_file($SafeQuery);
    
    // Check to see if the XML response was loaded, else print an error
    if ($ResponseXML)
     {
        // If the XML response was loaded, parse it and build links
        foreach ($ResponseXML as $product)
        {
            $linkurl  = $product->linkurl;
            $name= $product->productname;
            //$imageurl = $product->imageurl;
            $price = $product->price;
            $merchantname = $product->merchantname;
            
            //Variables Converting/Replcement
            $advertiserName_find = array("Affiliate Program","Affiliate Advantage Network","Computer/Music World","USA and Buy.com CA","USA, LLC","!");
            $advertiserName_new = trim(str_replace($advertiserName_find, "", $merchantname));
            
            
            //row colors switch
            if ( $row_count%2 )
                $row_color = "even";
            else
                $row_color = "odd";
                
            if($price!="")//avoiding problems of showing blank $$$ line
            {
                echo "<div class='product_".$row_color."'>";
                    echo "<div class='store_name'>".$advertiserName_new."</div>";
                    echo "<div class='product_title'><a target='_blank' class='product_url' href='http://www.pcinvent.com/watcher.php?buy=".encoded($linkurl).rand(1,9)."'>".$name."</a></div>";
                    echo "<div class='product_price instock'><a target='_blank' class='product_url' href='http://www.pcinvent.com/watcher.php?buy=".encoded($linkurl).rand(1,9)."'>$".$price."</a></div>";
                echo "</div>";
                
                $row_count++;
                //print_r_formatted($product);
            }        
        }//end of foreach ($ResponseXML as $product)
    }//end of if ($ResponseXML)
    else
    {
        $results = "Error, please contact website administrator!";
        //print "INDEX is: $index value is $result<br />";
        $row_count++;
    }
}//end of function runLinkShareAPI()
################################################# END of Linkshare #########################################*/

##################################################### START of CJ #########################################*/
function runCJAPI(){
    //SETTINGS
    $key        = "1234 PLEASE PUT YOUR OWN KEY HERE";  // The developer Key you get when you initially sign up for webservices
    $siteId        = "1234 PLEASE PUT YOUR OWN CJ PID HERE"; // The PID you have with CJ.
    $wdslurl    = 'https://api.cj.com/wsdl/version2/productSearchServiceV2.wsdl';
    $keywords   = 'wii+system wii+console wii+bundle'; // What you want to search for.
    
    try {
        $productClient = new SoapClient($wdslurl, array(
                                                        'trace' => 1,
                                                        'soap_version' => SOAP_1_1,
                                                        'style' => SOAP_DOCUMENT,
                                                        'encoding' => SOAP_LITERAL
                                                        )
                                            );
    
        $results =  $productClient->search( array(
                                                    "developerKey" => $key,
                                                    "websiteId" => $siteId,
                                                    "advertiserIds" => 'joined',
                                                    "keywords"  => "$keywords",
                                                    "serviceableArea" => '',
                                                    "upc" => '',
                                                    "manufacturerName" => '',
                                                    "manufacturerSku" => '',
                                                    "advertiserSku" => '',
                                                    "lowPrice" => '220',
                                                    "highPrice" => '750',
                                                    "lowSalePrice" => '',
                                                    "highSalePrice" => '',
                                                    "currency" => 'USD',
                                                    "isbn" => '',
                                                    "sortBy" => 'advertiserName',
                                                    "sortOrder" => '',
                                                    "startAt" => 0,
                                                    "maxResults" => 1000
                                                )
                                        );
    
        //print_r_formatted($results);
        
        $row_count =0;//initialized counter for row color
        
        foreach($results->{"out"} as $index => $result)
        {
            if($index == "products")
            {
                foreach($result as $products)
                {
                    foreach($products as $product)
                    {
                        $linkurl  = $product->buyUrl;
                        $name = $product->name;
                        $price = $product->price;
                        $merchantname = $product->advertiserName;
                        
                        //Variables Converting/Replcement
                        $advertiserName_find = array("Affiliate Program","Affiliate Advantage Network","Computer/Music World","USA and Buy.com CA","USA, LLC","!");
                        $advertiserName_new = trim(str_replace($advertiserName_find, "", $merchantname));
                        
                        
                        //row colors switch
                        if ( $row_count%2 )
                            $row_color = "even";
                        else
                            $row_color = "odd";
                        
                        echo "<div class='product_".$row_color."'>";
                            echo "<div class='store_name'>".$advertiserName_new."</div>";
                            echo "<div class='product_title'><a target='_blank' class='product_url' href='http://www.pcinvent.com/watcher.php?buy=".encoded($linkurl).rand(1,9)."'>".$name."</a></div>";
                            if ( $product->inStock != "" )//instock value is empty string
                                echo "<div class='product_price soldout'><a target='_blank' class='product_url' href='http://www.pcinvent.com/watcher.php?buy=".encoded($linkurl).rand(1,9)."'>Sold Out</a></div>";
                            else
                                echo "<div class='product_price instock'><a target='_blank' class='product_url' href='http://www.pcinvent.com/watcher.php?buy=".encoded($linkurl).rand(1,9)."'>$".$price."</a></div>";
                        echo "</div>";
                        
                        $row_count++;
                    //print_r_formatted($product);
                    }//end of foreach($products as $product)
                }//end of foreach($result as $products)
            }//if($index == "products")
            else
            {
                //print "INDEX is: $index value is $result<br />";
                $row_count++;
            }
        }//end of foreach($results->{"out"} as $index => $result)
    }//end of try()
    catch (Exception $e)
    {
        print "<p>The following error occured: <div style='margin-left:15px;color:red;'>$e</div></p>";
    }//end of catch (Exception $e)
}//end of function runCJAPI()
##################################################### END of CJ #########################################*/

##################################### START of RESULT Presentation #########################################*/
$temp=ob_get_contents();//$temp is now holding the html
ob_end_clean();

$fp=fopen("/var/www/html/usdealtoday_com/cache/".$foldername."/".$filename.".php",'w');
fwrite($fp,$temp);

echo $temp;
##################################### END   of RESULT Presentation #########################################*/
?>

wii_watcher.php

<!--
    The following codes are written by [email protected]
    PCinvent.com All Rights Reserved
    Please keep the above line credit to the author!
-->
<html>
<head></head>
<title></title>
<body>
<div id="wrapper">
<link rel="stylesheet" type="text/css" href="watchers/styles.css" media="all">
<?php
$filename = "wii_console.php";
$cachefile    = "/var/www/html/usdealtoday_com/cache/watchers_usdt/".$filename;
if ( file_exists($cachefile) )
{
    echo "<div class='watcher'>";
    ?>
   
    <div id="logo">
        <span><img src="watchers/wii_logo_1.gif" /></span>
        <span><img src="watchers/wii_logo_2.gif" /></span>
        <span><img src="watchers/wii_logo_3.gif" /></span>
    </div>
    <div align="center" id="info" style="margin-bottom:6px;">
        ***This Watcher Refresh the New Data & This Page every <span style="color:red;">30 seconds</span>***
    </div>
    <?php

    include($cachefile);

    echo "</div>";//end of watcher div
}
else
{
    echo "System busy, please try again!";
}
?>
</div>
</body>
</html>