AdWords is now Google Ads. Our new name reflects the full range of advertising options we offer across Search, Display, YouTube, and more. Learn more

My Business
3.3K members online now
3.3K members online now
For developers who are using the Google My Business API to manage locations
Guide Me
star_border
Reply

How to integrate GMB Restful API for retrieving all Location deatils

[ Edited ]
Visitor ✭ ✭ ✭
# 1
Visitor ✭ ✭ ✭

Hi All,

 

I want to integrate GMB restful API in my C# console application.

Below is my C# code.

----------------------------------------------------------------------------------------------------------------------------------

HttpClient client = new HttpClient();
client.BaseAddress = new System.Uri("https://mybusiness.googleapis.com/v3/accounts/1*******************/locations");

var Credentials = "emailID" + ':' + "password";
byte[] credentials = UTF8Encoding.UTF8.GetBytes(Credentials);

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage message = client.GetAsync("https://mybusiness.googleapis.com/v3/accounts/1*******************/locations", HttpCompletionOption.ResponseContentRead).Result;
var responseContent = message.Content;
string responseString = responseContent.ReadAsStringAsync().Result;

 

 

But i got response as below.  Please guide me to rid this problem.

 

{
  "error": {
    "code": 401,
    "message": "The request does not have valid authentication credentials.",
    "status": "UNAUTHENTICATED"
  }
}


 

1 Expert replyverified_user

Re: How to integrate GMB Restful API for retrieving all Location deatils

Google Employee
# 2
Google Employee

Hi @ICE P,

 

Judging from the source code you provided, you are not using the C# client library we provide on the Downloads and Samples page alongside the Google API Client Library for .NET for OAuth 2.0 Authorization. We strongly encourage you to use the client libraries we provide when interacting with Google's OAuth 2.0 endpoints for the security implications of getting the implementation correct.

 

Due to the complexities involved in using service accounts, we strongly recommend using the OAuth 2.0 client ID and persisting the refresh token. This way, your application will always be able to request a new access token when necessary. This process requires a user to manually authorize the application during the OAuth 2.0 installed applications flow only once.

 

The following is a code snippet for using an OAuth 2.0 client ID with the Google API Client Library for .NET:

           UserCredential credential;

           // The scope of Google My Business API

           string mybusinessServiceScope = "https://www.googleapis.com/auth/plus.business.manage";

           using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))

           {

               credential = GoogleWebAuthorizationBroker.AuthorizeAsync(

                   GoogleClientSecrets.Load(stream).Secrets,

                   new[] { mybusinessServiceScope },

                   "user", CancellationToken.None, new FileDataStore("Mybusiness.Auth.Store")).Result;

           }

 

           // Creates the service.

           var service = new MybusinessService(new BaseClientService.Initializer()

           {

               HttpClientInitializer = credential,

               ApplicationName = "Google My Business API Sample",

           });

 

If you need specific features of a service account, a one-time user consent is required for a service account to be able to access the Google My Business account and location data on behalf of a particular end user. When you prepare to make authorized API calls using a service account, you specify the user to impersonate by specifying the email address of the user account for access to their Google My Business data.

 

The following is a code snippet for using a service account with the Google API Client Library for .NET:

          // The scope of Google My Business API

          string MybusinessServiceScope = "https://www.googleapis.com/auth/plus.business.manage";

          String serviceAccountEmail = "123456789000-abc123def456@developer.gserviceaccount.com";

          var certificate = new X509Certificate2(@"MyProject.p12", "notasecret", X509KeyStorageFlags.Exportable);

          ServiceAccountCredential credential = new ServiceAccountCredential(

             new ServiceAccountCredential.Initializer(serviceAccountEmail)

             {

                 Scopes = new[] { MybusinessServiceScope },

                 User = "user@example.com"

             }.FromCertificate(certificate));

          // Creates the service.

          var service = new MybusinessService(new BaseClientService.Initializer()

          {

              HttpClientInitializer = credential,

              ApplicationName = "Google My Business API Sample",

          });

 

After you have obtained an access token through OAuth 2.0 authorization, you can use the following code snippet to list locations for the specified account:

           // Gets all accounts for the authenticated user.

           var accountsListRequest = service.Accounts.List();

           ListAccountsResponse accountsResult = accountsListRequest.Execute();

 

           // For testing purposes, selects the very first account in the accounts array

           Account account = accountsResult.Accounts[0];

 

           // Lists all locations for the specified account

           var locationsListRequest = service.Accounts.Locations.List(account.Name);

           ListLocationsResponse locationsResult = locationsListRequest.Execute();

 

Thanks,

Terry

How to integrate GMB Restful API for retrieving all Location deatils

Visitor ✭ ✭ ✭
# 3
Visitor ✭ ✭ ✭

Dear Terry,

I have been trying to use the code you provided for a while now, and I haven't had any success. I am simply not able to generate the access token (first sample of code you provided) programatically.

 

First of all, I wasn't able to define the redirect URL, so I was always getting a redirect_uri_mismatch, with a URI in the following form : "http://localhost:{some random port}/authorize/". I was able to overcome this problem by extending GoogleWebAuthorizationBroker, as explained in the link below:

 

http://stackoverflow.com/questions/31209273/how-do-i-set-return-uri-for-googlewebauthorizationbroker...

 

After following the accepted solution in the link above, the requests started to be accepted. But in the page to where I am redirected (OAuth 2.0 Playground) I am forced to insert the scope manually (by going back to Step 1) and only then I can obtain the access token. What I do is, after running the asynchronous call, I choose the user account, and then I end up in the following page:

 

https://s11.postimg.org/h5vgvw0fn/Screenshot_1.png

 

I click allow, and then in the next page(OAuth 2.0 Playground), when I click "exchange authorization code for tokens", I obtain the following response:

{
"error_description": "Unauthorized",
"error": "unauthorized_client"
}

 

By inspecting the URL in the GET request (on the right side of the "OAuth 2.0 Playground" page) I found out that there is no scope there. And if I manually add it to that URL, and execute the URL again, then I will get to the following page:

 

https://s22.postimg.org/7wlo2daqp/Screenshot_2.png

 

And now, by clicking allow, when I will be redirected to the "OAuth 2.0 Playground" page, I will be able to obtain the token by clicking "exchange authorization code for tokens".


What can I be doing wrong? Do I really have to create a method to insert the scope in the string, or is there a more elegant way to do this?