Monday, 7 April 2014

Connecting to Gigya REST API


require 'cgi' 
require 'net/http'
require 'uri'
require 'hmac-sha1'
require 'digest/sha1'
require 'base64'
  
#@ here are the parameters you need to supply from your Gigya site's settings page.
api_url = "http://socialize.gigya.com/socialize.getUserInfo"
api_key = "your_apiKey_50K9LE1sUO6mohgUE"
gigya_secret_key = "*********************************"
user_id          = "_guid_4UUBV567==" # an already registered user in your site
id               = "random" 
#@ 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("UID=#{CGI.escape(user_id)}&apiKey=#{CGI.escape(api_key)}&nonce=#{CGI.escape(nonce)}&timestamp=#{timestamp}")
base_string = "#{http_method}&#{CGI.escape(api_url)}&#{parameters}"
puts "base_string:  #{base_string.inspect} \n\n"  

#@ 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}&timestamp=#{timestamp}&UID=#{user_id}&sig=#{gigya_sign}"

#puts request_url.inspect
puts "Request_url:  #{request_url.inspect} \n\n"
  
#@ 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