Search

Sunday, September 28, 2014

Working with the Google Reseller API

I spent a few days trying to get this to work so it’s worth a write-up of what it takes to use the API from .NET.

Setup

  1. Create an Google Apps account in you can use to impersonate the client and get the data. You do that by going to http://admin.google.com/reseller.domain.com for your Google Apps reseller account.
  2. Enable API Access by going to Security/API Reference and checking “Enable API access.”
  3. Create a new project in Google Developer Console. I called mine “ResellerAPI.”
  4. Configure the Reseller API to be available to your project by going to the “ResellerAPI” project/APIs and enabling “Google Apps Reseller API.”
  5. Create a service account credential under the “ResellerAPI” project/Credentials. You will need to download the P12 key, write down the client ID and the client email address.
  6. Back in the Google Apps admin console, enable client API access for the client ID you created in step 5. You do this by going to Advanced Settings/Mange API client access. You will add the client ID and the API scope “https://www.googleapis.com/auth/apps.order.


Project Setup

  1. Create a new .NET project. I called mine GoogleApi.
  2. Open the Nuget package manager and install Google.Apis.Reseller.v1 with the command: install-package Google.Apis.Reseller.v1
  3. Update the Microsoft.BCL.Async package to the latest version with: install-package Microsoft.Bcl.Async


Variable Setup

We will create all the above settings a local private constants:

private const string ClientSertificatePath = @"The path to the certificate file from step 5";
private const string ClientSertificatePassword = "notasecret";
private const string ClientAccountEmail = "The client email address from step 5";
private const string ClientImpersonateUser = "Your Google Apps user from step 1";
private const string ApplicationName = "Reseller Sample";
private const int ServiceMaxResults = 100;

Service Setup

We will use a separate function to setup the service:

/// <summary>
/// Creates the reseller service object
/// with the provided client settings and certificate
/// </summary>
/// <returns></returns>
private ResellerService Setup()
{
    // Create a new certificate from the client certificate file
    var certificate = new X509Certificate2(ClientSertificatePath, ClientSertificatePassword, X509KeyStorageFlags.Exportable);

    // Create new credentials based on the certificate and the client settings
    var credentials = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(ClientAccountEmail)
       {
           // Set the scope of the request, AppOrderReadonly does not work here
           Scopes = new[] { ResellerService.Scope.AppsOrder },
           User = ClientImpersonateUser
       }.FromCertificate(certificate));

    // Return a new service with the client credentials
    return new ResellerService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credentials,
        ApplicationName = ApplicationName,
    });
}

Get Subscriptions

A separate function will be used recursively to get a list of subscriptions:

/// <summary>
/// Gets a list of subscriptions
/// </summary>
/// <param name="service">The ResellerService object</param>
/// <param name="listOfSubscriptions">A list of Subscription to store the returned data</param>
/// <param name="nextPageToken">The string containing the next page token</param>
private void GetSubscriptions(ref ResellerService service, ref List<subscription> listOfSubscriptions, string nextPageToken)
{
    listOfSubscriptions = listOfSubscriptions ?? new List<subscription>();

    // Create the subscriptions list request
    var listResults = service.Subscriptions.List();

    // Set the max results and page token
    listResults.MaxResults = ServiceMaxResults;
    listResults.PageToken = !string.IsNullOrEmpty(nextPageToken) ? nextPageToken : string.Empty;

    // Execute the request
    var result = listResults.Execute();

    if (result.SubscriptionsValue != null)
    {
        // Add all the subscriptions to the list
        listOfSubscriptions.AddRange(result.SubscriptionsValue);

        // If the next page token exists
        if (result.NextPageToken != null)
        {
            // Call yourself again passing the next page token
            GetSubscriptions(ref service, ref listOfSubscriptions, result.NextPageToken);
        }
    }
}

Putting it Together

The run function that will setup the service and get a list of subscriptions:

private void Run()
{
    // Setup the service
    var service = Setup();
    var listOfSubscriptions = new List<subscription>();

    Console.WriteLine("Getting a list of subscriptions...");
    
    GetSubscriptions(ref service, ref listOfSubscriptions, string.Empty);

    foreach (var s in listOfSubscriptions)
    {
        Console.WriteLine(s.SubscriptionId + " - " + s.CustomerId);
    }

    Console.WriteLine("Total: {0}", listOfSubscriptions.Count);
}

Downloads and Source Code

You can download all the working project from my Dropbox. Source code is on GitHub.

// //]]>