Wednesday, February 10, 2016

Consume Google My Business API Using Service Account.

If it comes to google my business API setup one has to go through developer console request api access , create project and enabled OAuth2.0.

Very important things to note: This solution is applicable only if you're looking at creating a console or batch job that is going to run in server or in azure cloud.

What it tackles?

  1. There is no clear cut direction or documentation as such in terms of service account.
  2. There is no nuget pkg available at the moment.
  3. Sometimes you may face problem with Key.p12 file that is mentioned in documentation.
  4. If key.p12 path results into error look at Byte[] options to load it.

Here is the few tweak in terms of google my business c# implementation. Feel free to comment.

using System;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System.IO;
using Google.Apis.Mybusiness.v2;
using Google.Apis.Mybusiness.v2.Data;
namespace ConsoleApplication1
    /// This sample demonstrates the simplest use case for a Service Account service.
    /// The certificate needs to be downloaded from the Google Developers Console
    ///   "Create another client ID..." -> "Service Account" -> Download the certificate,
    ///   rename it as "key.p12" and add it to the project. Don't forget to change the Build action
    ///   to "Content" and the Copy to Output Directory to "Copy if newer".
    public class Program

        public static void Main(string[] args)
            Console.WriteLine("Google My Business API - Service Account");
            //byte[] scriot=ReadFile("key.p12");
            String serviceAccountEmail = "";

            var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
            //var certificate = new X509Certificate2(scriot);
            string[] scopes = new string[] { "" };

            ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail) {

               Scopes =scopes,
               User = ""

            MybusinessService service = new MybusinessService(new BaseClientService.Initializer()
                HttpClientInitializer = credential,
                ApplicationName = "ABC-GMB",

            string loc = "accounts/1900345345435435345";
            AccountsResource.LocationsResource.ListRequest locRequest = service.Accounts.Locations.List(loc);
            ListLocationsResponse locationsResponse =locRequest.Execute();
        internal static byte[] ReadFile(string fileName)
            FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            int size = (int)f.Length;
            byte[] data = new byte[size];
            size = f.Read(data, 0, size);
            return data;

Post a Comment