OAuth client code

 

Java

The following example utility class can be used to generate authentication data for SOAP and REST requests.

The main method of the class produces a working REST URL.

Download the source code here.

 

package com.zanox.api.lib.authorization;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * This is an example utility class that generates authentication data for zanox REST and SOAP APIs.
 * The class has a dependency on Base64 encoder from Apache commons-codec. Alternatively,
 * you can use http://www.source-code.biz/base64coder/java/Base64Coder.java.txt
 *
 */
public class ZAuthentication {

	/**
	 * In this example, we generate a signed GET request to retrieve all AdSpaces.
	 * Replace connectId and secretKey with your own values to view your results.
	 *
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		ZAuthentication za = new ZAuthentication();

		String connectId = "802B8BF4AE99EBE00F41";
		String secretKey = "fa4c0c2020Aa4c+ab9Ea0ec8d39E06/df2c5aa44";

		String restTs = za.getRestTimestamp();
		String restNonce = za.generateNonce();
		String restSignature = za.getRestSignature("GET", "/adspaces", restTs, restNonce, secretKey);

		String restRequest = "https://api.zanox.com/json/2011-03-01/adspaces?connectid={0}&date={1}&nonce={2}&signature={3}";
		System.out.println("Try me: " + MessageFormat.format(restRequest, connectId, restTs, restNonce, restSignature));

		/* Assuming that you have generated a WS client, using JAX-WS wsimport, the GetAdspaces call would look like this:
		
			String soapTs = za.getSoapTimestamp();
			String soapNonce = za.generateNonce();
			String soapSignature = za.getSoapSignature("publisherservice", "GetAdspaces", soapTs, soapNonce, secretKey);
	
			PublisherSoapPortType service = new PublisherService().getPublisherSoapPort();
			
			GetAdspacesRequest request = new GetAdspacesRequest();
			request.setConnectId(connectId);
			request.setNonce(soapNonce);
			request.setTimestamp(soapTs);
			request.setSignature(soapSignature);
			
			GetAdspacesResponse response = service.getAdspaces(request);
			System.out.println(response.getItems());
			System.out.println(response.getAdspaceItems().getAdspaceItem().get(0).getName()); // print the name of the first AdSpace
			
		*/

	}

	/**
	 * Generates a nonce for REST and SOAP requests
	 *
	 * @return nonce
	 * @throws NoSuchAlgorithmException
	 */
	public String generateNonce() throws NoSuchAlgorithmException {
		long currentTime = System.currentTimeMillis();
		long randomNumber = Math.abs(new Random().nextInt());

		String msg = new Long(currentTime).toString() + new Long(randomNumber).toString();
		MessageDigest algorithm = MessageDigest.getInstance("MD5");
		return hex(algorithm.digest(msg.getBytes()));

	}

	/**
	 * Generates a timestamp string for REST API authentication
	 *
	 * @return timestamp
	 */
	public final String getRestTimestamp() {
		return getTimestamp("EEE, dd MMM yyyy HH:mm:ss") + " GMT";
	}

	/**
	 * Generates a signature for a REST API request
	 *
	 * @param httpVerb GET, POST, PUT or DELETE
	 * @param uri resource URI that follows API version date 2011-03-01. e.g. for http://api.zanox.com/xml/2011-03-01/adspaces URL, use /adspaces as
	 *        URI
	 * @param timestamp timestamp string for REST authentication
	 * @param nonce nonce
	 * @param secretKey your secret key
	 * @return REST signature
	 * @throws GeneralSecurityException
	 */
	public String getRestSignature(String httpVerb, String uri, String timestamp, String nonce, String secretKey) throws GeneralSecurityException {
		String stringToSign = httpVerb + uri.toLowerCase() + timestamp + nonce;
		return getSignature(stringToSign, secretKey);
	}

	/**
	 * Generates a timestamp string for SOAP API authentication
	 *
	 * @return timestamp
	 */
	public final String getSoapTimestamp() {
		return getTimestamp("yyyy-MM-dd'T'HH:mm:ss.000'Z'");
	}

	/**
	 * Generates a signature for a SOAP API request
	 *
	 * @param serviceName publisherservice, dataservice or connectservice, depending on which API you are using
	 * @param serviceMethod API method/operation as defined in the WSDL. GetAdspaces would be one example.
	 * @param timeStamp timestamp string for SOAP authentication
	 * @param nonce nonce
	 * @param secretKey your secret key
	 * @return SOAP signature
	 * @throws GeneralSecurityException
	 */
	public String getSoapSignature(String serviceName, String serviceMethod, String timeStamp, String nonce, String secretKey)
		throws GeneralSecurityException {
		String stringToSign = serviceName.toLowerCase() + serviceMethod.toLowerCase() + timeStamp + nonce;
		return getSignature(stringToSign, secretKey);
	}

	private String getSignature(String stringToSign, String secretKey) throws GeneralSecurityException {
		SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(signingKey);

		byte[] rawHmac = mac.doFinal(stringToSign.getBytes());
		byte[] encoded = Base64.encodeBase64(rawHmac);
		return new String(encoded);

	}

	private String hex(byte[] array) {
		StringBuffer buffer = new StringBuffer();

		for (int i = 0; i < array.length; i++) {
			buffer.append(Integer.toHexString(array[i] & 0xFF | 0x100).toUpperCase().substring(1, 3));
		}

		return buffer.toString();
	}

	private String getTimestamp(String dateFormat) {
		SimpleDateFormat df = new SimpleDateFormat(dateFormat, Locale.US);
		df.setTimeZone(TimeZone.getTimeZone("GMT"));
		return df.format(new Date());
	}

}

 

PHP

This is an example of how authentication can be done in PHP:

<?php
$connectID = ''; // Please fill in these two variables with the proper information
$secretKey = ''; // They can be found in the zanox Marketplace under "Links & Tools", "API"

$http_verb = 'GET';
$date = date('Y-m-d');
$uri = '/reports/sales/date/' . $date;
$time_stamp = gmdate('D, d M Y H:i:s T', time());
$nonce = uniqid() . uniqid();
$string_to_sign = mb_convert_encoding($http_verb . $uri . $time_stamp . $nonce, 'UTF-8');
$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $secretKey, true));
$requestURL = 'http://api.zanox.com/json/2011-03-01' . $uri . '?connectid=' . $connectID . '&date=' . urlencode($time_stamp) . '&nonce=' . $nonce . '&signature=' . urlencode($signature);
echo "Request: ". $requestURL . "<br>";
echo "<a href=\"" . $requestURL . "\">Link</a>";
?>