How to access data on Zanox from Ruby code
I've joined Bioddicted team since last autumn. On my way implementing Bioddicted web application, I wrote some Ruby code which accesses data on Zanox.
I know it's a super niche topic but it's better not to share it ;) Let me start from introducing what Zanox is. Zanox is a popular affiliate provider in Europe.
Join Our UK Affiliate Network - Awin
The same as other affiliate providers, Zanox also provides APIs for dealing with data on Zanox. And ... there is a Ruby client library!
http://wiki.zanox.com/en/REST_V2011-03-01_Reports
http://wiki.zanox.com/en/Ruby_Client_Library
But unfortunately the library doesn't work well probably due to a SOAP module the client library uses ;) So, I decided to write a simple code using their REST API. There are two main methods: 1. create a signature to access data on Zanox and 2. get data with the signature. Here is the code:
■ Method 1: create a signature
http://wiki.zanox.com/en/RESTful_API_authentication_with_zanoxConnect#Requests_with_Signature
def create_zanox_signature( http_method, sig_path, time_stamp, nonce) string2sign = http_method + sig_path + time_stamp + nonce signature = Base64.encode64(OpenSSL::HMAC::digest(OpenSSL::Digest::SHA1.new, ZANOX_SECRET_KEY, string2sign)).chomp return signature end
■ Method 2: get data
http://wiki.zanox.com/en/REST_V2011-03-01_Reports#GET:_Retrieving_all_sale_items
def get_sale_items( signature, time_stamp, nonce, target_date_str) http = Net::HTTP.new("api.zanox.com") request_url_path = "/json/2011-03-01/reports/sales/date/#{target_date_str}?connectid=#{ZANOX_CONNECT_ID}&date=#{CGI.escape(time_stamp)}&signature=#{CGI.escape(signature)}&nonce=#{nonce}" request = Net::HTTP::Get.new(request_url_path) response = http.request(request) result = response.body numItems = JSON.parse(result)["items"] if numItems > 0 return JSON.parse(result)["saleItems"]["saleItem"] else return nil end end
■ Main
# prepare values target_date_str = "2012-03-30" sig_path = "/reports/sales/date/#{target_date_str}" time_stamp = Time.new.gmtime.strftime("%a, %d %b %Y %H:%M:%S GMT").to_s # format: Mon, 09 Jun 2008 08:17:35 GMT nonce = Digest::MD5.hexdigest((Time.new.usec + rand()).to_s)[0..19] signature = create_zanox_signature( "GET", sig_path, time_stamp, nonce) # get sales data from Zanox sale_items = get_sale_items( signature, time_stamp, nonce, target_date_str ) puts sale_items.to_yaml
That's all :) Happy coding!
# The same thing can be done for example for lead data just by replacing the sig_path in main to "/reports/leads/date/#{target_date_str}".