Eric Nagel

Google Affiliate Network API PHP Script

I have been, or can be if you click on a link and make a purchase, compensated via a cash payment, gift, or something else of value for writing this post. Regardless, I only recommend products or services I use personally and believe will be good for my readers.

I was excited when I read Google had released an API for their Affiliate Network, as I wanted to automate pulling sales data from GAN. But I quickly became disheartened when I realized how difficult it is to use.

Since this was for myself, and not a web-based service that would be used by others, the Simple API method of authorization was good enough. After getting it to work with Picasa, but not GAN, I asked for some help and was introduced to the OAuth 2.0 Playground. This showed me the headers I’d need to send, and how OAuth 2.0 works.

For the record: the Google Affiliate Network API does NOT support Simple API Access. You cannot access the service with an API Key and IP locking.

I now have a working script, and have written up step-by-step instructions on how you can pull orders from GAN automatically each day.

This script is not complete, as it’s up to you to do something with the data once you have it. You can also modify the final call to pull advertisers, instead of orders.

Copy this to a new file (double-click to select-all. I named mine gan.php)

<?php
$cPublisherID	=	'';
$cScope			=	'https://www.googleapis.com/auth/gan.readonly';
$cClientID		=	'';
$cClientSecret	=	'';
$cRedirectURI	=	'urn:ietf:wg:oauth:2.0:oob';

$cAuthCode		=	'';
$cRefreshToken	=	'';

$bRefresh = true;

if (empty($cAuthCode)) {
	$rsParams = array(
						'response_type'	=>	'code',
						'client_id'		=>	$cClientID,
						'redirect_uri'	=>	$cRedirectURI,
						'scope'			=>	$cScope
						);
	$cOauthURL = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($rsParams);
	echo("Go to\n$cOauthURL\nand enter the given value into \$cAuthCode\n");
	exit();
} // ends if (empty($cAuthCode))
elseif (empty($cRefreshToken)) {
	$cTokenURL = 'https://accounts.google.com/o/oauth2/token';
	$rsPostData = array(
						'code'			=>	$cAuthCode,
						'client_id'		=>	$cClientID,
						'client_secret'	=>	$cClientSecret,
						'redirect_uri'	=>	$cRedirectURI,
						'grant_type'	=>	'authorization_code',
						);
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, $cTokenURL);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$cTokenReturn = curl_exec($ch);
	$oToken = json_decode($cTokenReturn);
	echo("Enter the following values:\n\n");
	echo("\$cRefreshToken = '" . $oToken->refresh_token . "';\n");
} // ends
else {
	// Get a new Access Token
	$cTokenURL = 'https://accounts.google.com/o/oauth2/token';
	$rsPostData = array(
						'client_secret'	=>	$cClientSecret,
						'grant_type'	=>	'refresh_token',
						'refresh_token'	=>	$cRefreshToken,
						'client_id'		=>	$cClientID
						);
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, $cTokenURL);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$cTokenReturn = curl_exec($ch);
	$oToken = json_decode($cTokenReturn);
	$cAccessToken = $oToken->access_token;

	// Get the results
	$cGANURL = 'https://www.googleapis.com/gan/v1beta1/publishers/' . $cPublisherID . '/events';
	$cAuthHeader = "Authorization: OAuth " . $cAccessToken;

	$ch = curl_init();

	curl_setopt($ch, CURLOPT_HTTPHEADER, array($cAuthHeader));
	curl_setopt($ch, CURLOPT_URL, $cGANURL);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$cJsonReturn = curl_exec($ch);

	print_r(json_decode($cJsonReturn));
} // ends else from <all authenticated>

?>

Login to your GAN account and get your Publisher ID. It’s the 6-character ID under your name (or your site’s name) in the upper-right once you login. Enter that value here

$cPublisherID	=	'';

Next, go to https://code.google.com/apis/console/, login, click the drop-down in the left navigation, then choose Create… and name your project. I named my project GAN Reporting

In the list of services, turn on Google Affiliate Network API

Turn on the Google Affiliate Network API Service

Now click on API Access (left navigation), then click on the button Create an OAuth 2.0 client ID…

Enter “GAN Reporting” for the “Product name” then click Next

GAN API Create Client ID

Choose “Installed application” for the Application type, then click “Create client ID”

GAN API Application Type

You now have a Client ID, Client secret, and 2 Redirect URIs

Enter your Client ID in the variable $cClientID and the Client secret value in $cClientSecret

$cClientID		=	'xxxxxxxxxxxx.apps.googleusercontent.com';
$cClientSecret	=	'xxxxxxxxxxxxxxxxx_xxxxxx';

Make sure $cRedirectURI is correct. Then save and upload gan.php (yes, there will be some empty variables… that’s OK!), and run it via command-line or a browser. You’ll see:

[esnagel@ec2 temp]$ php gan.php
Go to
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgan.readonly
and enter the given value into $cAuthCode

Go to this URL while logged into the Google account associated with your Google Affiliate Network (usually you@gmail.com, but if you’re like me and use Google Apps, you’ll have to open an Incognito window in Chrome to login)

You’ll see a page telling you GAN Reporting (your application) wants access to your GAN data. Click Allow access.

GAN API Allow Access

Next, you’ll see an Auth Code.

GAN API Auth Code

Copy that value and paste it back into gan.php:

$cAuthCode		=	'x/x-xxxxxxxxxx-xxxxxxxxxxxxxxx';

Save, upload and run the script again. Now, you’re given the value for the Refresh Token. Copy that and put it in gan.php:

$cRefreshToken = 'x/xxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

Save, upload, and run the script again. Now when you run the script via command-line, you’ll see:

[esnagel@ec2 temp]$ php gan.php
stdClass Object
(
    [kind] => gan#events
    [items] => Array
        (
            [0] => stdClass Object
                (
                    [kind] => gan#event
                    [modifyDate] => 2011-12-21T01:17:47.608Z
                    [eventDate] => 2011-12-21T00:46:38.185Z
                    [orderId] => xxxxxx
                    [commissionableSales] => stdClass Object
                        (
                            [amount] => xx.xx
                            [currencyCode] => USD
                        )

                    [status] => ACTIVE
                    [type] => TRANSACTION
                    [products] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [sku] => @adjustment
                                    [quantity] => 1
                                    [unitPrice] => stdClass Object
                                        (
                                            [amount] => xx.xx
                                            [currencyCode] => USD
                                        )

                                )

                        )

                    [advertiserId] => xxxxxx
                    [advertiserName] => xxxxxxxxxxxxx
                    [memberId] => xxxxxxxxxx
                    [earnings] => stdClass Object
                        (
                            [amount] => xx.xxxx
                            [currencyCode] => USD
                        )

                )
...

This is the result of

print_r(json_decode($cJsonReturn));

At this point, it’s up to you to loop through the items array and do what you want with the data.

I’ll answer some technical questions in the comments, but for the complicated questions, I’ll direct you to my PHP Programmer page where you can email or call me to describe your project and receive an estimate.