You are not logged in.   Log in | Register

Server Side API (REST)

From $1

Overview

The Gigya Socialize server-to-server API uses a REST-like interface. This means that the API method calls are made over the internet by sending HTTP GET or POST requests to the Socialize REST API server and the response is returned as XML.

Nearly every software development environment provides methods for communicating over HTTP with a REST server.

The REST API Reference provides specification to the various REST API methods supported by Gigya Socialize.

 

Prerequisites for Using REST API Methods

Please make sure you comply with the following requirements prior to making a REST API method call:

  • Making API calls requires an API Key and a Secret Key which are obtained from the Site Setup page on the Gigya website. The Secret Key must be kept secret and never transmitted to an untrusted client or over insecure networks. The API Key is a required parameter in each REST API method. The Secret Key is used for signing requests
  • REST API method calls require an identified Gigya user (the identification of whom is performed using the UID parameter) with an active session. A user session is created when a user logs in or connects via Gigya Socialize. The only way to log in or connect a user is through your client application, using our JavaScript Client API method calls: socialize.login, socialize.connect or socialize.notifyLogin. You may also use our ready made Widgets: Login Widget or Connect Widget.

REST-API_diagram (4).gif

To learn more about various authentication scenarios, please refer to the Authentication page in the Developer's Guide.

 

Making an API Call

A Sample API Call:

The following is an example of an HTTP GET request:

http://socialize.api.gigya.com/socialize.setStatus?uid=<User ID>&apiKey=<Your APIKey>&nonce=<nonce>&timestamp=<current unix-time>&
sig=<signature>&status=Hello

The call is composed of the following elements:

  1. The Socialize REST API URL: 
    http://socialize.api.gigya.com/

  2. The method name, which, in the above example, would be: 
    socialize.setStatus

  3. Common required parameters (the following section explains this subject further):
    ?uid=<User ID>&apiKey=<Your APIKey>&nonce=<nonce>&timestamp=<current unix-time>&sig=<signature>

  4. Method-specific parameters. In the above example: 
    &status=Hello
Note: all parameter values should be in UTF-8 and URL-encoded.

 

Common Required Parameters

The following parameters are required for all API calls:

  • uid - The unique ID of a connected user, with whom this method call is associated.
  • apiKey - Your API application key. If you don't have one, please create one at the Site Setup page on the Gigya website.
  • timestamp - The current GMT time when the request is made. Follows the the Unix time format (i.e. the number of seconds since Jan. 1st 1970). Requests which skew more than 120 seconds from the server time will be rejected.
  • nonce - A cryptographic nonce. The nonce string should be unique per method call.
  • sig - A signature verifying the authenticity of the request (see Signing the Request below for more details).
     

Making a Call Over HTTPS

When making the API call over HTTPS, you may pass the secret parameter. In such case the timestamp, nonce and sig parameters are no longer required.

Set the secret parameter with your Gigya Secret Key which can be obtained from the Site Setup page on the Gigya website.

The following is an example of an HTTPS request with the secret parameter:

https://socialize.api.gigya.com/socialize.setStatus?apiKey=<Your APIKey>&uid=<User ID>&secret=<Your Secret Key>&status=Hello

 

Note: Passing the secret parameter is allowed ONLY over HTTPS. If you attempt to pass the secret parameter over HTTP, the method will return the following error: "Secret Sent Over Http" (Error code: 403006).

 

 

Signing the Request

For security reasons, Gigya requires every API call to be signed, so as to guarantee that it originated from an authorized partner and was not tampered with in transit.

 

Please Note: We use a different algorithm for signing REST API requests and for signing API calls on client applications (web pages or flash widgets). This section discusses signing REST API requests. To learn how to sign Gigya Socialize Client API methods (JavaScript & AS3) please refer to the Cryptographic Signatures section of the Developer's Guide.

 

The Authentication Flow

  1. Generate a nonce and a timestamp to be used on the call.
  2. Build a "Signature Base String" and use your Gigya Secret Key to sign it, as described in the Generating the Signature section below.
  3. When making the call - pass the nonce, the timestamp and the calculated signature as parameters to the API method (the nonce, timestamp and sig parameters).
  4. Gigya verifies that the timestamp on the call is within 5 minutes of the current time; if this is not the case, the call will be rejected.
  5. Gigya verifies that the nonce has not been used during the last 10 minutes; otherwise, the call will be rejected.
  6. Gigya verifies the signature by performing the same calculation, using the same Secret Key and comparing the result to the sig parameter.

 

Generating the Signature

To generate the signature, do the following:

  1. Build a "Signature Base String" as instructed in section 9.1 of the OAuth specifications.
    Essentially, the Signature Base String consists of: 
    • The HTTP method ('GET' or 'POST')
    • The request URL: http://socialize.api.gigya.com/
    • The method name. For example: socialize.setStatus
    • The method parameters
       
    Important Notes:
    • Please make sure to append all method parameters except the sig parameter.
    • Please make sure that the parameters are sorted by name, using lexicographical byte value ordering.

  2. Apply the HMAC-SHA1 algorithm on the "Signature Base String" with your Gigya Secret Key as the key parameter of the algorithm as instructed in section 9.2 of the OAuth specifications.  Your Gigya Secret Key is provided, in BASE64 encoding, at the bottom of the Site Setup page on the Gigya website. This key should be kept on the server and should never be transmitted over any public network.
     

You may use one of the OAuth libraries that can be found in http://oauth.net/code to build the Base String and generate the Signature.

 

Implementation Examples:


The OAuth.php file is located at: http://oauth.googlecode.com/<wbr/>svn/code/php/OAuth.php

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

// Signature calculation method
// The parameters for the signature calculation are:
//  1. Your secret key
//  2. The HTTP method ('GET' or 'POST') 
//  3. Method API name (e.g. 'setStatus')
//  4. The parameters of the API method. Note that each API method has a different set of parameter. 
function calcSignatureREST($secretKey, $httpMethod, $apiMethod, $parameters) {   
    $req = OAuthRequest::from_request($httpMethod,'http://socialize.api.gigya.com/socialize.'.$apiMethod, $parameters);
    $baseString = $req->get_signature_base_string();    
    return  base64_encode(hash_hmac('sha1', $baseString, base64_decode($secretKey), true));
}

// Your secret key (can be found at the bottom of the Site Setup page on the Gigya website)
$secretKey = 'ENTER YOUR SECRET KEY HERE';

// The parameters for the socialize.getUserInfo API call: 
$parameters = array(
    "apiKey" => '2_OitqVv1ZZClsxml9-2L8eWZ-9FTTnTIu6S2-3jdEau4YuabkX4ssNcROopwy_rNv',
    "nonce" => '128900583063345187',
    "timestamp" => '1245584706',
    "uid" => '_gid_+mtciUK98aqx57Dn+7yFhA==');

echo calcSignatureREST($secretKey, 'POST', 'getUserInfo', $parameters);

?>
Notes:
In order to make this code work in your environment, please:
  1. Click the "Copy sample code" (link located above code) - This will open a popup window with a text version of the code, which you may copy.
  2. Modify the value of the "secretKey" field in the code, to your Gigya secret key. Your secret key is provided at the bottom of the Site Setup page on Gigya's web-site.
  3. Note that the 4th parameter of the calcSignatureREST function is an array of the Gigya API method parameters. In this example we use the getUserInfo API method, thus the $parameters variable is initialized with the corresponding parameters. When changing the API method, change the list of parameters accordingly. Check the REST API Reference for the list of parameters for the required method call.
class Post
  #@Shmueli:
  # I am using here the hmac/sha1 lib you can find here http://rubyforge.org/projects/ruby-hmac/
  # user, id, status_message are instance methods of the Post class.
  # this authentication method only works for the status api call as the http parameters are ordered 
  # hard coded and not sorted automatically.
  # some modifications may be needed for other API calls.
  def authenticate_and_share
    #@ escape the status message and replace all + with %20 as spaces are CGI.escaped to +
    message_text = CGI.escape(status_message).gsub('+', '%20')
    user_id = user.id
  
    #@ here are the parameters you need to supply from your Gigya site's settings page.
    api_url = "http://socialize.api.gigya.com/socialize.setStatus"
    api_key = "HERE_GOES_YOUR_API_KEY"
    gigya_secret_key = "HERE_GOES_YOUR_GIGYA_SECRET_KEY"
  
    #@ decode secret key and prepare nonce.
    gigya_secret = Base64.decode64(gigya_secret_key)
    timestamp = Time.now.gmtime.to_i
    nonce = "#{user_id}#{id}#{timestamp}"
    http_method = "GET" #@shmu: define your HTTP method

    #@ parameters are ordered alphabetically, base string include HTTP method call and its parameters, 
    # all separated with unescaped "&"
    parameters = CGI.escape("apiKey=#{CGI.escape(api_key)}&nonce=#{CGI.escape(nonce)}&status=#{message_text}
    &timestamp=#{timestamp}&uid=#{user_id}")
    base_string = "#{http_method}&#{CGI.escape(api_url)}&#{parameters}"
  
    #@ hmac/sha1 encription for the gigya secret and the base_string
    hmacsha1 = HMAC::SHA1.digest(gigya_secret, base_string)
    gigya_sign = Base64.encode64(hmacsha1).chomp.gsub(/\n/,'')
    gigya_sign = CGI.escape(gigya_sign) #@shmu: we must escape the signature as well.
  
    #@ finalized api request url with the signed signature
    request_url = "#{api_url}?apiKey=#{api_key}&nonce=#{nonce}&status=#{message_text}&timestamp=#{timestamp}
    &uid=#{user_id}&sig=#{gigya_sign}"
    puts request_url.inspect
  
    #@ read the response
    response_text = open(request_url).read
 
    #@ handle error messages from gigya XML output.
    regexp = /\<statusCode\>(.*?)\<\/statusCode\>/
    status_code = response_text.scan(regexp).to_s.to_i
    if status_code == 200
      okmsg = "Gigya: Content Shared: #{status_message} [#{user.nick}]"
      logger.info okmsg
      return okmsg
    else
      raise "GIGYA RESPONSE ERROR: #{response_text.scan(/\<errorMessage\>(.*?)\<\/errorMessage\>/).to_s} \n\n 
        #{response_text.inspect} \n\n\n [id:#{id}, user:#{user}]\n\nStatusMessage: #{status_message}\n\n Basestring:
        #{base_string}\n\n RequestURL: #{request_url}\n\n\n"
    end
  end
end

@The Ruby example code is written by Shmueli Ahdut.

Notes:
In order to make this code work in your environment, please:
  1. Click the "Copy sample code" (link located above code) - This will open a popup window with a text version of the code, which you may copy.
  2. Modify the value of the "secretKey" field in the code, to your Gigya Secret Key. Your secret key is provided at the bottom of the Site Setup page on Gigya's web-site.
  3. Note that the base string for calculating the signature include the Gigya API method name and the method's parameters. In this example we use the setStatus API method (see the api_url variable definition), thus the parameters variable is initialized with the corresponding parameters. When changing the API method, change the list of parameters accordingly. Check the REST API Reference for the list of parameters for the required method call.

 

The following code example is a Perl script that executes the socialize.getUserInfo API call: 

#!/usr/local/bin/perl

use Digest::HMAC_SHA1 qw(hmac_sha1);
use MIME::Base64;
use URI::Escape;

my $secretKey = "[ENTER YOUR SECRET KEY HERE]";
my $apikey = "[ENTER YOUR API KEY HERE]";
my $uid = "[ENTER THE UID FOR A CONNECTED USER HERE]";

my $key = MIME::Base64::decode ($secretKey);

my $time = time ();
my $nonce = $time;

my $url = "http://socialize.api.gigya.com/socialize.getUserInfo";
my $method = "GET";

my $parms = "apiKey=" . $apikey;
$parms .= "&nonce=" . $nonce;
$parms .= "&timestamp=" . $time;
$parms .= "&uid=" . uri_escape_utf8 ($uid);

my $sigbase = $method . "&" . uri_escape_utf8 ($url) . "&" . uri_escape_utf8 ($parms);

print STDERR "Base String: " . $sigbase . "\n\n";
my $hashed = hmac_sha1 ($sigbase, $key);
my $sig = MIME::Base64::encode ($hashed);
$sig =~ s/\n$//;

print STDERR "Sig: $sig\n";


my $url = "http://socialize.api.gigya.com/socialize.getUserInfo?apiKey=" . uri_escape ($apikey) . "&nonce=" . $time . "&sig=" . uri_escape ($sig) . 
            "&timestamp=" . $time . "&uid=" . uri_escape ($uid);

print STDERR "URL: " . $url . "\n";

 

Notes:
In order to make this code work in your environment, please:
  1. Click the "Copy sample code" (link located above code) - This will open a popup window with a text version of the code, which you may copy.
  2. Modify the values of the "$secretKey" and the "$apikey" fields in the code, to your Gigya secret key and API-Key. Your Gigya keys are provided on the Site Setup page on Gigya's web-site.
  3. Fill in the value of the UID of a connected user in the "$uid" field.
  4. Note that the "$parms" field is a concatenation of the Gigya API method parameters. In this example we use the getUserInfo API method, thus the "$parms" field consists of the getUserInfo parameters, sorted lexicographically. When changing the API method, change the list of parameters accordingly, and make sure to keep the parameters sorted. Check the REST API Reference for the list of parameters for the required method call.
  5. Run the script on a Linux host. The script prints a URL, which you may copy and paste into a browser window. This would list an XML formatted user information.

 

 

Receiving Responses

After sending a REST request, you will receive a response, which is by default an XML string.

Response XML Example:

<?xml version="1.0" encoding="utf-8" ?>
<socialize.disconnectResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="urn:com:gigya:api http://socialize.api.gigya.com/schema/1.0.xsd" xmlns="urn:com:gigya:api">
    <statusCode>200</statusCode>
    <statusReason>OK</statusReason>
</socialize.disconnectResponse>

The name of the root element in the response consists of the name of the request API method with the word "Response" appended to it, as demonstrated in the example above: <socialize.disconnectResponse> (in the response for socialize.disconnect method).

All responses include two child elements, <statusCode> and <statusReason>, which comply with the HTTP status and status reason:

  •      <statusCode> - This is the equivalent of the HTTP status code, such as 200, 400, 40, etc.
  •      <statusReason> - The equivalent of the HTTPreason code, such as "OK", "Bad Request", "Unauthorized", etc.

 

Some methods also return additional data as additional children of the root element. See the documentation of each method for details on the specific data it returns.

Note: if a response field contains no data, the return XML will not have a child element representing that field.

 

Error Handling

If an error occurs, the response will include two additional child elements:

  •      <errorCode> - An application-specific error code. This value is used to distinguish between different causes for the same statusCode.
  •      <errorMessage> - A detailed textual error message designated for the purpose of logging during the process of debugging.

Response XML with Error Example:

<?xml version="1.0" encoding="UTF-8" ?>
<socialize.setStatusResponse xmlns="urn:com:gigya:api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="urn:com:gigya:api http://api.gigya.com/schema/1.0.xsd">
    <statusCode>500</statusCode>
    <statusReason>Internal Server Error</statusReason>
    <errorCode>500024</errorCode>
    <errorMessage>No valid session</errorMessage>
</socialize.setStatusResponse>

The system will return HTTP status "200 OK" for all application-level errors and return the detailed error in the body of the response. Please note that some errors, such as 503, or "Server Unreachable" will still be returned on the HTTP level and should be handled accordingly.

 

Error Codes:

StatusCode StatusReason errorCode Description
200 OK   No error
400 Bad Request 400001 Invalid request format
    400002 Missing required parameter
    400004 Invalid parameter format
    400005 Invalid date range
    400006 Invalid parameter value
    400007 Missing required date parameter
    400008 Invalid date format
    400009 Missing required register widget id parameter
    400010 Invalid register widget id parameter format
      Missing required campaign name parameter
    400011 Invalid campaign name parameter format
    400012 Missing required ad title parameter
    400014 Missing required ad text parameter
    400017 Missing required campaign id parameter
    400018 Invalid campaign id parameter format
    400019 Missing required as ver parameter
    400020 Invalid as ver parameter format
    400021 Missing required cid parameter
    400022 Invalid cid parameter format
    400023 Missing required embedded code parameter
    400024 Invalid embedded code parameter format
    400025 Missing required offer types parameter
    400026 Invalid offer types parameter format
    400027 Missing required file parameter
    400028 Invalid file parameter format
    400029 Missing required country code parameter
    400030 Invalid country code parameter format
    400031 Missing required region code parameter
    400032 Invalid region code parameter format
    400033 Missing required gender code parameter
    400034 Invalid gender code parameter format
    400035 Missing required age group code parameter
    400036 Invalid age group parameter format
    400037 Missing required tag parameter
    400038 Invalid tag parameter format
    400039 Missing required daily budget cap parameter
    400040 Invalid daily budget cap parameter format
    400041 Invalid daily budget cap parameter range
    400042 Missing required amount parameter
    400043 Invalid amount format
    400044 Invalid amount range
    400060 Missing required provider parameter
    400061 Invalid network
    400070 Missing required recipients parameter
    400071 Invalid recipients parameter
    400080 Missing required body parameter
    400081 Invalid body parameter
    400090 Missing required subject parameter
    400091 Invalid subject parameter
    400092 Missing required ApiKey parameter
    400093 Invalid ApiKey parameter
    400094 Missing required uid parameter
    400095 Invalid uid parameter
401 Unauthorized 401001 Session token has expired
403 Forbidden 403001 Invalid session token
    403002 Request has expired
    403003 Invalid request signature
    403004 Duplicate nonce
    403005 Unauthorized user
404 Not Found  404001 Friend not found
    404002 Network not found
413 Request Entity Too Large 413001 File too large
500 Internal Server Error 500020 Invalid site ID
    500021 Data pending
    500022 Server error
    500023 Provider error
    500024 No valid session
501 Not Implemented 501001 Invalid API method


 

 

 

 < Back to 'Share Content' | Next to 'Advanced Customizations' >

Tags:
Files (0)