Tutorial: Make a Google Powered Shopping Search Website

Demo Download

In this tutorial, we will be making a simple product search engine. Using jQuery and PHP, we will tap into Google's Shopping Search API and return a list of items available for purchase, along with prices, photos and other useful information. The Shopping Search API gives us direct access to Google's large database of products and prices, obtained from partnering online stores. Another benefit to using this service, is that products are automatically ranked and filtered for us behind the scenes to better match with the user's search query.

Important update: Google have revoked API access for this application, citing that it doesn't comply with their TOS. This means that the demo won't work any longer and that, unfortunately, there is nothing we can do about it. However, the tutorial will be left online, as it shows techniques and code that a lot of you would find useful. Only keep in mind that you should integrate the shopping API as a part of your services, and not make it central, as this case, otherwise it could get banned.

Let's start coding!

The HTML

The first step, as usual, is to lay down the HTML layout of the page. We will be making use of a simple HTML5 document, which you can see below:

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Google Product Search | Tutorialzine Demo</title>

        <!-- CSS Includes -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans+Condensed:700" />
        <link rel="stylesheet" href="assets/css/styles.css" />

        <!--[if lt IE 9]>
          <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <header>
            <h1>Product Search</h1>

            <form action="" method="get">
                <input type="text" id="q" name="q" placeholder="what do you want to buy?" />
                <img id="preload" alt="preload" src="assets/img/325.gif"/>
            </form>

            <h2>Powered by <b>Google</b></h2>
        </header>

        <section id="products">
            <!-- The product list will go here -->
        </section>

        <p id="message">
            <!-- Error messages will be displayed here -->
        </p>

        <!-- JavaScript includes -->
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>

Nothing too exciting is going on here. We have a form containing of single text field, the products section, which will hold the shopping items, and a message that is shown when nothing is found. And here is the markup of a shopping list item (it will be generated by jQuery depending on the result of the api call):

<a class="product" data-price="$73.99" href="http://ebay.com/..." target="_blank">
    <img alt="eBay" src="http://i.ebayimg.com/.." />
    <span>eBay</span>
</a>

Once we have this in place, we can now continue with generating our Google API key.

Obtaining a Google API Key

Google offers its API for free, but we have to generate a unique key for our app in order to use it. This helps them track usage and authenticate each request. We have done this before, when we were building a one-click registration form with Google, and it isn't much different this time. What you need to do is visit Google's API Console and set up a new project, next activate the Search API for Shopping; this will give you an API key that we will use in the next section (read here for more details on the steps).

Note that Google imposes limits on the number of API requests per key. The shopping search api allows only 2.5k requests per day for free, so if you are planning to do something serious with it, you will probably have to pay.

product-search.jpg

Writing the Proxy

In order to communicate securely, and to keep your API key private, we will have to route our requests through a PHP script on the server. Although the API returns JSON formatted data, we can not use it directly from JavaScript without exposing our key (and without violating the same origin policy for that matter).

This PHP script, or proxy, is pretty straightforward:

proxy.php

// Enter your Google API key here
// you can obtain it from the API console
$key = 'YOUR API KEY GOES HERE';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search'])) {

    $search = urlencode($_POST['search']);
    $url = 'https://www.googleapis.com/shopping/search/v1/public/products?key=' . $key . '&country=US&q=' . $search . '&maxResults=24';

    echo file_get_contents($url);
}

The script takes its input from $_POST, encodes it, and sends it to Google, printing the result.

The jQuery Code

Now that we have everything in place, we can proceed with writing the jQuery code that will drive our shopping search engine:

assets/js/script.js

$(document).ready(function(){

    var saveTimer,
        searchBox = $('#q'),
        products =  $('#products'),
        message = $('#message'),
        preloader = $('#preload');

    preloader.css('visibility','hidden');

    searchBox.on('input',function(e){

        // Clearing the timeout prevents
        // saving on every key press
        clearTimeout(saveTimer);

        // If the field is not empty, schedule a search
        if($.trim(searchBox.val()).length > 0) {
            saveTimer = setTimeout(ajaxProductsSearch, 2000);
        }
    });

    $('form').submit(function(e){
        e.preventDefault();

        if($.trim(searchBox.val()).length > 0) {
            clearTimeout(saveTimer);
            ajaxProductsSearch();
        }
    });

    function ajaxProductsSearch(){

        products.empty();
        preloader.css('visibility','visible')

        // Issue a request to the proxy
        $.post('proxy.php', {
            'search' : searchBox.val()
        },
        function(data) {

            if(data.totalItems == 0){

                preloader.css('visibility','hidden');
                message.html("We couldn't find anything!").show();
                return false;
            }

            $.each(data.items, function(i, item){

                var html = ' <a class="product" data-price="$ '+item.product.inventories[0]['price']+'" href="'+item.product['link']+'" target="_blank">';

                // If the product has images
                if(item.product.images && item.product.images.length > 0){
                    html += '<img alt="'+item.product.author['name']+'" src="'+ item.product.images[0]['link']+'"/>';
                }

                html+='<span>'+item.product.author['name'].substr(0, 20)+'</span></a> ';

                products.append(html);
            });

            preloader.css('visibility','hidden');

        },'json');
    }

});

I am using the same timeout trick that we used in the AJAX notes tutorial a few weeks ago. By setting a timeout two seconds in the future and clearing it on every key press, we are able to run the search only when the user has stopped typing.

With this our product search website is complete!

It's a wrap!

You can use the product search API to enhance your existing web app with relevant products that will be of interest to your visitors. The API gives you much more functionality than what is shown here - you can filter, sort and group results, apply spell checking and display statistics. You can even take part in google's affiliate network and earn real money from your application.

Bootstrap Studio

The revolutionary web design tool for creating responsive websites and apps.

Learn more

Related Articles

Rg Enzon

Great tutorial as usual! Thanks for sharing :)

An amazing bit of inspirational work, Well done!

Martin, great! Thanks!

Is it possible to add a definition (when available) of the product one is searching? From a thesaurus or some other place?

Let me know,
M

Difdesigner

Nice tuts.
I am bit confuse adding API console.
I added API key but its not working.

Martin Angelov

Be sure to enable "Search API for Shopping" from the services section.

Aditya Maulana

amazing tutorial....

Codeforest

Nice tutorial as always.

One note though:
On many shared server environments file_get_contents is disabled, so I prefer using curl for communicating with web services.

Amazing as always! can i change currency, lets say change to Indonesian Rupiah?

Martin Angelov

Thank you! Yes you can change the currency. It is passed as a parameter to the Google API request in proxy.php. See a list of possible parameters here (search for currency).

Zahin Alwa

With reply to Martin, here is the link to get your country ISO code martin mentioned above, to use it in proxy.php search request parameter..

Martin, great and inspiring tutorial,..
Cheers

Hello Martin, congratulations ! This tut is amazing!
I was looking for something like that!
Iam trying it out and testing it, but unfortunately when i try to change currency to EUR or other parametres it isn't finding anything...
Is there any other settings to make there in proxy.php ?

Martin Angelov

All the parameters that can be sent to google can be seen on their documentation page. I haven't tested it with EUR but it should work fine.

Dear Martin, thank you very much for your reply!
Im impressed!
I read the <a rel="nofollow" href="https://developers.google.com/shopping-search/v1/reference-request-parameters">documentation page</a>, i am not an expert one, but i think i made the correct changes in the $url of proxy.php, but nothing. Can you please check it?

Google Product Search API does not work for my country.
Here is a list of countries for which this API will work.
http://support.google.com/merchants/bin/answer.py?hl=en&answer=160619
Sorry for the trouble Martin.

Thanks for great tutorial. Its awesome !

Great tutorial, is it possible to show results by price or to add more pages?

Thanks Martin! :D

Very great tutorial...

thanks it is very useful ..thanks for sharing..

This tutorial is very good but ,
Hey I m new in PHP

I want to create a website that search product from according to my clients like.

How to search product from particular website

Hi...

I've changed the currency (BRL) in the code but does not work, just shows (USD)

"$key . '&country=BR&qlanguage=pt-BR&qcurrency=BRL=' "

Hey, great tutorial, sad I couldn't get it working. Was working in localhost but there is a unexpected character break in JSON.parse, don't know what it is. Is this has something to with file_get_contents. Should I try cURL.

Thanks in advance

Excellent work. It will become a lot o famous :)

working for me now!
I was getting this error file_get_contents(): Unable to find the wrapper &quot;https&quot

This was being caused because extension=php_openssl.dll was missing from my php.ini - xampp

thank you for the tutorial!

David Augustus

You are the best. Do you think is there any way to strict the search for results in a country domain, for example? Or limitating specifying the currency of the search results? Thank you very much for the classes! I love you .

I hope that you revisit this sometime and possibly use another service like Amazon.

Great but google Shopping search API was despached
It will be great to see something similar for Google Plus Search API

Like showing search results of posts from Google Plus...