Basic Tutorial

Skip to end of metadata
Go to start of metadata

 

This page includes a basic example of a web page that uses the Gigya service - to connect a user to a social network using a Facebook app , and a guide for using Gigya API methods. This guide is designed for people familiar with HTML and JavaScript programming. Follow the tutorial to learn how to write your first Gigya application.

This tutorial is designed to give you basic knowledge of how to use the Gigya Web SDK on a web site and how to use a params object and is not meant to show the best way to implement Gigya on a site. See our RaaS Quick Start Guide for help implementing Gigya on your site after familiarizing yourself with our Web SDK.

 

Basic Web Page Working Example

Run the Example

 

The Example Code

<html>
<head>
    <title></title>

    <!-- STEP 1 - Including the gigya.js script: -->
    <script type="text/javascript" src="https://cdns.gigya.com/js/gigya.js?apiKey=INSERT-YOUR-APIKEY-HERE">

    // STEP 2 - Defining a global configuration object:    
    { 
        enabledProviders: "facebook"
    }
    </script>
</head>

<body >
<script type="text/javascript" >
    function Login()
    {
        var params = {
           "callback": onLogin,
           "provider": "facebook",
		   context:'testLogin'
        };   
        gigya.socialize.login(params);
    }

    //declare the callback function in your code
    function onLogin(response)
    {
        if (response.errorCode == 0) {

            // this will inject the user name and nickname
            document.getElementById('divUserName').innerHTML = response.user.nickname;

            ///set the photo to image src attribute.
            document.getElementById('imgUserPhoto').src = response.user.photoURL;
        }
        else {

            //handle errors
            alert("An error has occured!" + '\n' +
                "Error details: " + response.errorMessage + '\n' +
                "In method: " + response.operation);
        }
    }
</script>
 
<div id="runningCodeExample" style="border: 1px solid skyblue; padding: 15px; width: 400px; display: block; height: auto;">
<center>
    <input type="button" onclick="Login()" value="Connect to Facebook"  />
    <div id="UserInfo">
       <div id="divUserName"></div>
       <div id="divUserPhoto"><img id="imgUserPhoto" src="https://s3.amazonaws.com/wikifiles.gigya.com/transparent.GIF" onerror="this.src='transparent.GIF'"/></div>
    </div>
</center>
</div>
</body>
</html>

Notes:
In order to make this code work in your environment, please:

  • Copy the example code above.
  • Replace "INSERT-YOUR-APIKEY-HERE" string in lines 6 and 12 with your Gigya API Key, which can be obtained on the Dashboard page on the Gigya website. See also the Gigya's Setup documentation.
  • For development and testing purposes, it is possible to run the example on 'localhost' and with any valid API key.
  • When deploying, make sure your page loads from a web server that uses a DNS name (e.g. www.yoursite.com). If required, you may use your "hosts" file to map a DNS name that will point to the web server on your local machine.

When using Gigya's API's over HTTPS it is important that the script tag in the <head> of your pages reference the HTTPS version of the JS SDK, (note CDNS as opposed to CDN) e.g.,

<script type="text/javascript" src="https://cdns.gigya.com/js/gigya.js?apikey=YOUR-API-KEY-HERE"></script>

The example demonstrates the 5 basic steps of using the Gigya API:

Step 1: Include the 'gigya' Web SDK in Your Pages

Including the 'gigya.js' Web SDK in your pages is a prerequisite for using Gigya method calls.

Once you have obtained a Gigya API key, append it to the gigya.js source URL and add it to your page as seen in the following example.

Every page that uses the Gigya API should include the Web SDK (only once) in the <head> section:

<script type="text/javascript" src="https://cdns.gigya.com/js/gigya.js?apiKey=INSERT-YOUR-APIKEY-HERE"></script>

Notes:

  • Please replace " INSERT-YOUR-APIKEY-HERE " in the code with your Gigya API Key, which can be obtained on the Dashboard page on Gigya's website.
  • If you are implementing Gigya in an https page, please read about Loading the Gigya Web SDK over HTTPS.

 

Step 2: Create a Global Configuration Object (Optional)

A global configuration object can be defined if you wish to store global configuration parameters, which are common to all the API calls and are expected to remain static for the lifetime of the application.

If you define the global configuration object, it should be created once and then used with all the method calls in the lifetime of the application.

  { 
        enabledProviders: "facebook,twitter"
  }

 

The global configuration object consists of various optional members (please refer to the Web SDK Reference for full specifications).

In the example above, we have used one of the global configuration object members:

  • enabledProviders - A comma-separated list of providers that will be enabled in the Gigya service. The enableProviders is an optional configuration parameter. You may use '*' to enable all the providers.
     

Step 3: Create a Method-specific 'params' Object

Every GS API method requires a "params" object as the only parameter. The params object enfolds all the specific parameters sent to the API method.

var params = {
    callback: onConnectionAdded,
    provider: 'facebook'
}

 

Each method in the Gigya API accepts different parameters, as appropriate for that method. Additionally, all the methods in the Gigya API accept the following common parameters:

  • callback -
    A reference to a callback function. Gigya calls the specified function along with the results of the API method when the API method completes.
    The callback function should be defined with the following signature: functionName(Response).
    The "Response Object Data Members" table below provides specification of the data that is passed to the callback function.
  • context -
    A developer-created object that is passed back unchanged to the application as one of the fields in the response object.

 

The Web SDK Reference specifies the list of parameters ("params" object members) that each API method accepts - some are required and some are optional.

In our example we used the socialize.login method (in Step 4), which defines the following parameters: 

 

RequiredNameTypeDescription
providerstringThe provider to which to connect. The optional values for this parameter are: 'facebook', 'twitter', 'yahoo', 'microsoft', 'linkedin', 'qq', 'renren', 'sina' (Note: messenger has been replaced by microsoft, however, for backward compatibility, either can be used)
sessionExpirationintegerThis parameter defines the time in seconds that Gigya should keep the social network session valid for the user. To end the session when the browser closes, please assign the value '0'. If this parameter is not specified, the session will be valid forever.
callbackfunction
A reference to a callback function. Gigya calls the specified function along with the results of the API method when the API method completes.
The callback function should be defined with the following signature: functionName(Response).
The "Response Object Data Members" table below provides specification of the data that is passed to the callback function.
cidstring
A string of maximum 100 characters length. The CID sets categories for transactions that can be used later for filtering reports generated by Gigya in the "Context ID" combo box. The CID allows you to associate the report information with your own internal data. For example, to identify a specific widget or page on your site/application. You should not define more than 100 different context IDs.
contextobject
A developer-created object that is passed back unchanged to the application as one of the fields in the response object.

 

This means that the method requires a parameter called 'provider', in addition to some optional parameters. 

The 'var params' object in the above example conforms to this definition, and thus can be passed as the second parameter of the login method.

 

Note:

Some of the parameters may appear both in the global configuration object and in the method's specific "params" object. An example for that is the cid parameter. In such cases the value in the params object overrides the value in the configuration object.
For example:

{
   ...,  cid: "abc"
}

var params = { ...,  cid: "xyz" }
gigya.socialize.addConnection(params);  // The cid "xyz" will be used. 

This can be useful for defining a global default in the global configuration object, and overriding the default in some methods, by setting a different value in the method's params object.

 

 

Best Practice

It is important to define an independent params object per method call, as opposed to editing and reusing the same object for several method calls. This is due to the fact that the methods run asynchronously. The best practice is to concatenate the method name to the params object name. For example:

 

Step 4: Execute the API Method

Call the socialize.login API method. Transfer the 'params' object as a parameter.

   gigya.socialize.login(params); 

 

Step 5: Define a Callback Function (Optional)

The API uses an asynchronous programming model, meaning that socialize.login will run in the background and call a developer-provided callback function when it completes.

Recall that we specified the callback function in the parameter "callback": onLogin. Thus in our example the onLogin function is called when the processing of the  socialize.login method completes:

    function onLogin(response)
    {
        if (response.errorCode == 0)
        {
            // Update the page with the data received in the response:
            // inject the user's nickname to the "divUserName" div 
            document.getElementById('divUserName').innerHTML = response.user.nickname;
            // inject the user's photo to the image "src" attribute.
            document.getElementById('imgUserPhoto').src=response.user.photoURL;
        }
        else
        {
            //handle errors
            alert("An error has occurred!" + '\n' + 
                "Error details: " + response.errorMessage + '\n' +
                "In method: " + response.operation);
        }
    }   

 

The callback function is a developer-defined function. The only constraint is on its signature - the Gigya service expects the callback function to receive one parameter, which is the  response object .

The response object contains the values returned from the API method. The callback function should analyze the response object and handle it appropriately. For example, display an error message to the end-user if an error has occurred. In particular, the callback function should verify that the errorCode field of the response object equals zero (response.errorCode == 0) , as any other value indicates an error.

Every response object contains common members (values that are returned by all API methods).

The common members of the response object are specified in the following table:

 

FieldTypeDescription
errorCode integer The result code of the operation. Code '0' indicates success, any other number indicates failure. For a complete list of error codes, see the table.
errorMessage string A short textual description of an error associated with the errorCode for logging purposes.
callId string Unique identifier of the transaction, for debugging purposes.
context object The context object passed by the application as a parameter to the API method, or null if no context object has been passed.

 

Each API method defines its additional members in the response object. Method-specific members are detailed in the reference section for each API call.

In our example - the socialize.login method defines the following additional member:

 

user             User objectUser object with updated information for the current user.

Note - The 'user' parameter is of the type 'User object'. Please refer to the specification of User object in the Web SDK Reference section.

 

Notice how we used the response object in the implementation of the onLogin(response) function:

We used some of the common data members: response.errorCode, response.errorMessage, response.operation.

We also used the response.user data member, which is specific to the login method. 'response.user' is of the type User object, and thus includes the members - nickname and photoURL, which are used in the example: response.user.nickname, response.user.photoURL.

 

What's Next?

After reading the tutorial, you should be ready to start using the basic features of the Gigya API.

  • You may wish to continue reading the Developer's Guide for further learning about:
    • How to embed the Gigya service pre-built Web GUI elements in your site - in Using Add-ons.
    • How to react to Events, generated by the Gigya service.
    • How to integrate the Gigya service in your server or smart client application, using the REST API.
    • And more.
  • You may consult the Web SDK Reference section - for full specifications of the Gigya JavaScript Web SDK.
  • Check out some Working Code Examples of web-pages integrating the Gigya service. In each example, you may see a web page in action, and view the JavaScript code.