Google Analytics (обновление пользовательского измерения) Недостаточно прав доступа 403 - PullRequest
0 голосов
/ 30 мая 2018

Я пытаюсь обновить настраиваемые поля измерений (https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/customDimensions/update) в Google Analytics, вызвав API-интерфейс Analytics из C #.

Я создал проект в https://console.developers.google.com,, добавил учетную запись службы(скачал файл .p12, файл закрытого ключа), включил API-интерфейс аналитики и связал адрес электронной почты учетной записи службы в https://analytics.google.com

Я могу прочитать «данные аналитики» (например, сводки учетных записей и т. д.), но не вставитьили обновить. Когда я пытаюсь это сделать, я получаю сообщение об ошибке Недостаточное разрешение 403. У служебной учетной записи, добавленной в Google Analytics, есть все привилегии.

 class Program
    {
        static void Main(string[] args)
        {
            test();
        }

        public static void test() //takes clientid as input
        {

            string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data

            var keyFilePath = @"C:\Users\xyz\Desktop\CustomDimUpdate\xxxxxxxx.p12";    // Downloaded from https://console.developers.google.com
            var serviceAccountEmail = "xxxx.iam.gserviceaccount.com";  // found https://console.developers.google.com

            //loading the Key file
            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = scopes
            }.FromCertificate(certificate));


            var service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential
                //ApplicationName = "Analytics API Sample",
            });


            CustomDimension body = new CustomDimension();
            body.Name = "Configurable"; //Found in https://analytics.google.com
            body.Scope = "Product"; //Found in https://analytics.google.com
            body.Active = true;


            try
            {
                //analytics.management().customDimensions()
                //    .update("123456", "UA-123456-1", "ga:dimension2", body).execute();
                ManagementResource.CustomDimensionsResource.UpdateRequest update = service.Management.CustomDimensions.Update(body, "123456", "UA-123456-1", "ga:dimension1");

                update.Execute(); //Errors out here

                ManagementResource.AccountsResource.ListRequest list = service.Management.Accounts.List();
                list.MaxResults = 1000; // Maximum number of Accounts to return, per request. 
                Accounts feed1 = list.Execute(); //Works perfectly fine

                foreach (Account account in feed1.Items)
                {
                    // Account
                    Console.WriteLine(string.Format("Account: {0}({1})", account.Name, account.Id));
                }

                ManagementResource.ProfilesResource.ListRequest list1 = service.Management.Profiles.List("123456", "UA-123456-1");
                Profiles feed = list1.Execute();
                foreach (Profile profile in feed.Items)
                {
                    Console.WriteLine(string.Format("\t\tProfile: {0}({1})", profile.Name, profile.Id));
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

            }


        }

1 Ответ

0 голосов
/ 30 мая 2018

Мне удалось решить эту проблему, изменив приведенную ниже строку кода

string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data

на

string[] scopes = new string[] { AnalyticsService.Scope.AnalyticsEdit }; // view and manage your Google Analytics data
...