Ads Service

Step 1: Search On Publisher Page

To use the BOSS API with Ads you must have a web page, a web page hosting service, or your own network connected server, and a “search box” to complete the following steps. This web page will display your search results and Ads from Yahoo once you have been approved to use the Ads feature. These tools allow you to obtain and adjust the web search results per your unique design and implementation. The Ads token is a unique identifier that will be used to return relevant Ads directly to your user’s browser. For example, a BOSS API URL with the Ads feature and an XML response is displayed below.

Step 2: Request for Algo + Ads

Developers can use any common programming languages such as PHP, Java, or Perl to analyze the XML response and create a search results page. The Ads are called using Javascript in the HTML. See the Algo in JSON/XML + Ads Token below for a PHP example that can be used with the following Javascript.

A sample of three files (sample.php, bossClient.php and partner.js) are displayed below. These three files all need to exist in the same file directory. To use the example below make sure you have PHP installed with a web server. Also oAuth.php should be in the same directory.

You can run the code by running the sample URL http://your_test_domain/sample.php?q=dvd to see a sample page with news search results and three Ads at the top of the page.

Note

“Algo” refers to algorithimc search results. These search results use a formula to display the most relevalt results as they pertain to a search query term.

Simple Query Example

https://yboss.yahooapis.com/ysearch/web,ads?q=dvd&ads.url=BOSS_PARTNER_URL&ads.Partner=BOSS_PARTNER&ads.TYPE=BOSS_PARTNER1&ads.count=10&format=xml&start=0&count=1&market=en-us

Step 3: Algo in JSON/XML + Ads Token

The following two PHP files are used in conjuction with partner.js and oAuth.php. Copy and edit the following files with the information you recieved when you signed up for the BOSS API. To use Ads you must sign-up and be pre-approved.

Code Snipet: sample.php

<?php
require("bossClient.php");

/*
THIS CODE IS PROVIDED AS A SAMPLE ONLY.
1. Production Implementations must follow the rules stated the Advertising Display Rules https://developer.yahoo.com/search/boss/boss_api_guide/ch11s02.html
2. All Calls should be made from a Valid URL (not an IP Address). i.e. http://127.0.0.1/news.php will NOT return Ads. Change HOST File to map a local test domain.
3. Add the KEY/Secret/Partner and URL values in the code below
4. Following code is setup for News and Ads together. Add Code to displayWebResults() in bossClient.php for Web Search
*/

$boss = new BossClient;
$boss->query =  $_GET["q"]; // search query, 'q' is the name of input tag in the form
$boss->start =  isset($_GET["start"]) && (int)$_GET["start"] > 0 ? $_GET["start"] : 1; // result offset for pagination, start from 1 as default
/* ADD YOUR OAUTH KEYS HERE*/
$boss->cc_key  = "ENTER YOUR KEY HERE";
$boss->cc_secret = "ENTER YOUR SECRET HERE";

$boss->ads_Partner = "ENTER YOUR PARTNER TAG HERE - GIVEN BY DDC"; // REQUIRED PARAMETER - AN ALPHA-NUMBERIC STRING
$boss->ads_Type = "ENTER YOUR TYPE TAG - GIVEN BY DDC"; // REQUIRED PARAMETER - TYPE TAG
$boss->ads_url = "ENTER YOUR SITE URL HERE"; // REQUIRED PARAMETER - ADD your VALID URL HERE (not an IP Address).
$boss->ads_count = 3; // ads count per page
$boss->count = 3; // count of search result per page, for pagination usage
$boss->api_service = array("news","ads"); // subset array of {web,limitedweb,images,news,blogs,ads} - ADD CODE TO bossClient.php to support other services beyond News

// invoke boss api
$boss->run();

?><html>
<head>
<script src="https://s.yimg.com/rv/boss_v2/js/yjs.js"></script>
<script src="./partner.js"></script>
<?php $boss->printAdsTokenScript(); ?>
</head>
<body <?php $boss->printAdsCallOnload(); ?>>
<form>
<input type="text" id="q" name="q" value="<?php echo htmlentities($boss->query);?>">
<input type="submit" value="search">
</form>
<span id='ads'>
</span>
<span id='news'>
<p><b> NEWS RESULTS </b></p>
<?php
$boss->displayNewsResults();
?>
</span>
</body>
</html>

Code Snipet: bossClient.php

<?php
require("OAuth.php");

class BossClient
{
    /* mandatory parameters */
    public $query = "";
    public $cc_key  = "";
    public $cc_secret = "";
    public $ads_url = "";
    public $ads_Partner = ""; // ads partner tag
    public $ads_Type = ""; // ads type tag

    /* optional parameters, default values exist */
    public $start = 1; // search result offset, for pagination usage
    public $count = 10; // count of search result per page, for pagination usage
    public $ads_Token = "true"; // force to enable ads token mode for old system customer
    public $ads_count = 3; // ads count per page
    public $ads_start = 1; // ads offset

    public $api_service = array("news","ads"); // collection of services which to use
    public $boss_hostname = "yboss.yahooapis.com";

    /*Dispatch resquest to BOSS API Ads backend */
    private function dispatch() {
        if (trim($this->query) == "") return false;
        if (empty($this->cc_key)) return false;
        if (empty($this->cc_secret)) return false;
        if (empty($this->ads_Partner)) return false;

        $args = array();
        $args["q"] = $this->query; // Query Parameter
        $args["format"] = "xml"; // Format
        $args["count"] = $this->count; // Count of Algo results
        $args["start"] = $this->start; // Start value for Algo results

        /* Advertising Parameters - REQUIRED UNLESS STATED */
        $args["ads.Token"] = $this->ads_Token;
        $args["ads.Partner"] = $this->ads_Partner;
        $args["ads.Type"] = $this->ads_Type;
        $args["ads.url"] = $this->ads_url;

        // Optional Parameter
        $args["ads.count"] = $this->ads_count;
        $args["ads.start"] = $this->ads_start;

        // BOSS API Backend URL
        $this->url = "http://".$this->boss_hostname."/ysearch/".implode($this->api_service,",");

        try {
            $consumer = new OAuthConsumer($this->cc_key, $this->cc_secret);
            $request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $this->url, $args);
            $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
            $this->url = sprintf("%s?%s", $this->url, OAuthUtil::build_http_query($args));
            $ch = curl_init();
            $headers = array($request->to_header());

            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $rsp = curl_exec($ch);
            $this->boss_response = new SimpleXMLElement($rsp);
        } catch (Exception $e) {
            /* debug here */
            return false;
        }
        return true;
    }
    public function run() {
        /* main function to invoke boss api*/
        if ($this->dispatch()) {
            $this->extract();
        }
    }
    private function extract() {
        /* to extract meta results */
        if (!empty($this->boss_response)) {
            foreach($this->api_service as $service) {
                if(isset($this->boss_response->$service)) {
                    if ($service == 'ads') {
                        if (isset($this->boss_response->ads->dmtoken)) {
                            $this->dmtoken = (string)$this->boss_response->ads->dmtoken;
                        }
                    } else {
                        $this->result[$service] = $this->boss_response->$service;
                        $this->meta[$service] = $this->boss_response->$service->attributes();
                    }
                }
            }
        }
    }

    /* Method to print Ad Tokens to JS Script */
    public function printAdsTokenScript() {
        if (empty($this->dmtoken)) return;
        echo "<script> var dmtoken = '".$this->dmtoken."'; </script>";
        return true;
    }

    /* Method to print Ad Call to JS Script */
    public function printAdsCallOnload() {
        if (empty($this->dmtoken)) return;
        echo " onload='fire_ads(dmtoken)' ";
        return true;
    }

    /* TODO : Method to display Web Search Results */
    public function displayWebResults() {
        /* to do */
        /* implement presentation here if you want to display web search results */
    }

    /* Method to print News search Results */
    public function displayNewsResults() {
        /* sample implementation of News result presentationn */
        if (empty($this->query)) {
            echo " <p> empty query </p>";
            return false;
        }
        if(!isset($this->result['news']) OR !isset($this->meta['news'])) {
            echo " <p> error </p>";
            return false;
        }
        if($this->meta['news']['count'] == 0) {
            echo " <p> no result </p>";
            return false;
        }
        foreach($this->result['news']->results->result as $item) {
            echo "<ul>";
            echo "<li><a href='".$item->url."'>".$item->title."</a></li>";
            echo "<li>".$item->abstract."</li>";
            echo "<li>".$item->source." - ".date("Y-m-d H:i:s",(int)$item->date)."</li>";
            echo "</ul>";
        }
        return true;
    }
}
?>

**Note**

Make sure your test environment uses a Domain and not an IP address.
For example, a correct test host file has the following
``123.456.789.000 sampleboss.com``. You then use
**``sampleboss.com``** (domain name) in the BOSS API URL. For more
information on host files `click
here <http://en.wikipedia.org/wiki/Hosts_file>`__.

Simple XML Response Example

<?xml version="1.0"encoding="UTF-8"?><bossresponse responsecode="200">
<ads>    <dmtoken>
appid=aEC17S4g&amp;ads.Token=4oACeziXt.7y8T_j6emKkoehzihQjmCfOQrYn3W_nO_xCmJdfOJwX2lX6UQUPE1cVgbQEdxOAecSsEna0NViyx1q861rhOSepK5Ft2St1mIiSpZahuZ2RVVjVb6CsZ_WvLCZNeQY6Ab0APaFKetQtAytsQqcneY6SI2Iftxdoj_LTnxv5NEw1B3rtZR.~A
</dmtoken>
</ads>
<web start="0" count="1" totalresults="XX">
<results>
...
</results>
</web>
</bossresponse>

Step 4: Serve Algo Results

Displays the search results on the user browser window. In the sample code please see the displayNewsResults method to print News search results in bossClient.php.

Step 5: Call Yahoo JavaScript with Token

The partner.js file provided below, calls the fetch_ads function in the Yahoo hosted JS file https://s.yimg.com/rv/boss_v2/js/yjs.js.

Code Snippet: partner.js

function fire_ads(token) {

post_search_display(); /* implemented in yahoo js, HAS TO BE INVOKED */
var callback_function = "render_ads";  /* implemented in partner.js */

    /* make call to fetch ads providing token as a parameter */
fetch_ads(callback_function, token, "");
    /* fetch_ads is implemented in yahoo js, HAS TO BE INVOKED  */

}

/* Callback function for Ads JSON */
function render_ads(result_json) {

    if (result_json.bossresponse.responsecode != 200) {
        return false;
    }
    if (result_json.bossresponse.ads.resultset.numResults == null || result_json.bossresponse.ads.resultset.numResults == 0) {
        return false;
    }

    // See rules for using BOSS Search Ads https://developer.yahoo.com/search/boss/boss_api_guide/important_adsrules.html
    var innerHTML = "<div style=\"background-color:#FBEFF5\">";
    innerHTML += "<p><a href='https://help.yahoo.com/l/us/yahoo/search/basics/basics-03.html'><b>Sponsored Ads</b> <img src='http://l.yimg.com/a/i/us/sch/boss2/createdwith1.png'></a></p>";

    for(i=0;i<result_json.bossresponse.ads.resultset.numResults;i++) {
        var item = result_json.bossresponse.ads.resultset.listing[i];
        title = item.title;
        description = item.description;
        siteHost = item.siteHost;
        clickurl = item.clickurl;
        innerHTML += "<ul>";
        innerHTML += "<li><a href='"+clickurl+"'>"+title+"</a></li>";
        innerHTML += "<li>"+description+"</li>";
        innerHTML += "<li>"+siteHost+"</li>";
        innerHTML += "</ul>";
    }

    innerHTML += "</div>";

    var adsSection = document.getElementById('ads');
    adsSection.innerHTML = innerHTML;
}

Step 6: Get Back Ads in JSON

The fetch_ads method above returns Ads in JSON format which are rendered using the render_ads function.

{
   "bossresponse": {
      "responsecode": "200",
           "ads": {
                "resultset": {
                    "id": "adListings",
                    "numResults": "1",
                        "listing": [
                                {
                                "rank": "1",
                                "title": "<b>Football</b> Equipment",
                                "description": "Large selection of <b>football</b> equipment and training aids",
                                "siteHost": "www.athleticsgalore.com",
                                "clickurl": "http://1010101.r.msn.com/?ld=4vq9ndR1Iz05F-VIR1ArZ-yMDKq78eT62kklvEWHpT7_2T6zwB-UELQxgdhrYum33ydEW48-CGl-yXCLedW3LQ6ApZNZ-6G6pc7fHVo5V50mLQhHj9lr533IlA8xzM8y9VMi7cd66LXkpWPv3nuBptDfzXd34S7fPTz4wcOxUHPODOMFjXA2p5Mzw5hhSTSdd7t7Af_RgCG1UFBtdTHJte9ctQWOxcw-nJ6FFS7v15FsqDxEJOslcVD9iH1pp52ZnxPBnkGBAmY3M9z-1RJIREEbcjGSDlX7HcXsiDZHm-FBRbIIaxnsN06bI"
                                }
                                   ]
                             }
                 }
    }
}

Ads Service Arguments

The following arguments are specific to the Ads service. All Ads arguments are case sensitive!

When requesting Ads, the BOSS API sends the same query term you entered to Ads service. This ensures that the Ad is associated with your BOSS API query term. The following table displays the advertising parameters used in BOSS API.

For addtional information see the Ad FAQ’s.

Arguments Default Value Required Description
Partner A unique alpha numeric string Yes Partner Tag/Source Tag associated with the user’s unique usage. Do not encode this parameter.
Type A unique alpha numeric string Yes Partner Tag/Source Tag associated with the user’s unique usage
start Default value = 1 No Optional. Start count of Ad to be returned
test false Yes Optional. Set value to true to return a fake ad for testing purposes. The fake ad returned by the call is not representative of the Ad Marketplace but allows developers to test their token generation and search ads deployment. Clicks made by users on the Ad do NOT count towards advertising revenue.
count Default value = 10 No Optional. Number of Ads to be returned
url A unique url string Yes The URL for the Partner where to return the Ads.

Note

Please prefix the ads Service to parameters. For example: ads.Partner = BOSS_PARTNER. Parameters are passed in the request to get the token.

Note

The argumentads.Token can only be used by BOSS API qualified publishers pre 11/7/2011. Set ads.Token=true to migrate to new system.