Получите доступ к Google MyBusiness API, используя OAuth, используя учетную запись службы

У меня есть учетная запись Google MyBusiness, настроенная для нескольких компаний. Я пытаюсь получить доступ к этим данным с помощью C# путем реализации учетной записи службы. Я создал учетную запись службы в консоли разработчика Google и загрузил файл JSON, содержащий необходимые учетные данные.

Кажется, я могу вызвать API, используя приведенный ниже код, однако мне кажется, что мне возвращают неверную учетную запись (учетную запись с нулевым местоположением, которая также является частью учетной записи Google, которая используется для других целей), это становится очевидным, когда я попытаться перечислить все места.

Учетная запись службы была создана в правильной учетной записи Google, которая содержит информацию о местонахождении компании.

Я не получаю ошибок и не могу точно определить, где находятся проблемы.

Любая помощь будет принята с благодарностью! Спасибо

Код для получения учетной записи сервиса MyBusinessService

using Google.Apis.MyBusiness.v4;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.IO;
using Newtonsoft.Json;

namespace BranchProfileGoogleBusinessAPI
{
public class ServiceAccountJson
{
    public string type { get; set; }
    public string project_id { get; set; }
    public string private_key_id { get; set; }
    public string private_key { get; set; }
    public string client_email { get; set; }
    public string client_id { get; set; }
    public string auth_uri { get; set; }
    public string token_uri { get; set; }
    public string auth_provider_x509_cert_url { get; set; }
    public string client_x509_cert_url { get; set; }
}


public class ServiceAccountAuth
{

    /// <summary>
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// </summary>
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
    /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
    /// <returns>MyBusinessService used to make requests against the MyBusiness API</returns>
    public static MyBusinessService AuthenticateServiceAccount(string serviceAccountCredentialFilePath)
    {
        try
        {

            // For Json file
            if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
            {

                var json = File.ReadAllText(serviceAccountCredentialFilePath);
                var cr = JsonConvert.DeserializeObject<ServiceAccountJson>(json);
                // Create an explicit ServiceAccountCredential credential
                var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
                    {
                        Scopes = new[] {
                        "https://www.googleapis.com/auth/plus.business.manage"
                    }
                }.FromPrivateKey(cr.private_key));


                // Create the  MyBusiness service.
                return new MyBusinessService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = xCred,
                    ApplicationName = "MyBusiness Authentication Sample",
                });
            }
            else
            {
                throw new Exception("Unsupported Service accounts credentials.");
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine("Create service account MyBusinessService failed" + ex.Message);
            throw new Exception("CreateServiceAccountMyBusinessServiceFailed", ex);
        }
    }

}

}

Код для вызова API с использованием учетной записи службы MyBusinessService, которая возвращает неверную учетную запись и, в конечном счете, бизнес-местоположения отсутствуют

var serviceAccount = ServiceAccountAuth.AuthenticateServiceAccount(JsonPath);

        var test = serviceAccount.Accounts.List().Execute();
        var test2 = serviceAccount.Accounts.Locations.List(test.Accounts.FirstOrDefault().Name).Execute();

0 ответов

Другие вопросы по тегам