شروع سریع: پیوندهای حساب Google Analytics را با استفاده از Google Marketing Platform Admin API مدیریت کنید

در این راهنمای سریع، شما درخواست‌هایی را به رابط برنامه‌نویسی کاربردی مدیریت پلتفرم بازاریابی گوگل (Google Marketing Platform Admin API) ارسال می‌کنید و پاسخ‌هایی را که حاوی فهرست حساب‌های گوگل آنالیتیکس مرتبط با سازمان مشخص‌شده در پلتفرم بازاریابی گوگل هستند، مشاهده می‌کنید.

شما می‌توانید این شروع سریع را با استفاده از SDK زبان برنامه‌نویسی در محیط محلی خود یا REST API تکمیل کنید.

پیش‌نیازها

تکمیل این راهنمای سریع مستلزم آن است که:

  • یک پروژه Google Cloud راه‌اندازی کنید و رابط برنامه‌نویسی کاربردی مدیریت پلتفرم بازاریابی گوگل (Google Marketing Platform Admin API) را فعال کنید.
  • روی دستگاه محلی شما:
    • نصب، راه‌اندازی اولیه و احراز هویت با Google Cloud
    • SDK مربوط به زبان مورد نظرتان را نصب کنید

راه‌اندازی یک پروژه گوگل کلود

پروژه گوگل کلود خود را راه‌اندازی کنید و رابط برنامه‌نویسی کاربردی مدیریت پلتفرم بازاریابی گوگل (Google Marketing Platform Admin API) را فعال کنید.

برای انتخاب یا ایجاد یک پروژه جدید Google Cloud و فعال کردن خودکار API مدیریت پلتفرم بازاریابی گوگل، روی این دکمه کلیک کنید:

فعال کردن رابط برنامه‌نویسی کاربردی مدیریت پلتفرم بازاریابی گوگل

گوگل کلود را راه‌اندازی کنید

روی دستگاه محلی خود، با Google Cloud راه‌اندازی و احراز هویت کنید.

  1. گوگل کلود را نصب و راه‌اندازی کنید .

  2. اگر قبلاً Google Cloud را نصب کرده‌اید، با اجرای این دستور مطمئن شوید که اجزای gcloud شما به‌روز هستند.

    gcloud components update
  3. برای احراز هویت با Google Cloud، با اجرای این دستور، یک فایل محلی Application Default Credentials (ADC) ایجاد کنید. جریان وب راه‌اندازی شده توسط این دستور برای ارائه اعتبارنامه‌های کاربری شما استفاده می‌شود.

    gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/marketingplatformadmin.analytics.read"

    توجه داشته باشید که چگونه محدوده‌های مورد نیاز توسط API مدیریت پلتفرم بازاریابی گوگل در دستور مشخص شده‌اند.

    برای اطلاعات بیشتر، به «تنظیم اعتبارنامه‌های پیش‌فرض برنامه» مراجعه کنید.

رابط برنامه‌نویسی کاربردی مدیریت پلتفرم بازاریابی گوگل (Google Marketing Platform Admin API) به یک پروژه سهمیه‌بندی نیاز دارد که به طور پیش‌فرض تنظیم نشده است. برای یادگیری نحوه تنظیم پروژه سهمیه‌بندی خود، به راهنمای اعتبارنامه‌های کاربری مراجعه کنید.

شناسه سازمانی پلتفرم بازاریابی گوگل خود را مشخص کنید

برای استفاده از رابط برنامه‌نویسی کاربردی مدیریت پلتفرم بازاریابی گوگل، باید شناسه سازمان پلتفرم بازاریابی گوگل خود را شناسایی کنید. وارد پلتفرم بازاریابی گوگل شوید، به کادر محاوره‌ای مدیریت بروید، سازمان خود را انتخاب کنید و شناسه سازمان را در زیر جزئیات سازمان یادداشت کنید.

تمام درخواست‌ها به رابط برنامه‌نویسی کاربردی مدیریت پلتفرم بازاریابی گوگل (Google Marketing Platform Admin API) باید شامل شناسه سازمان organizations/ORGANIZATION_ID باشند.

SDK را برای زبان برنامه‌نویسی خود تنظیم کنید

در دستگاه محلی خود، برای نصب SDK مربوط به زبان برنامه‌نویسی خود، روی یکی از تب‌های زیر کلیک کنید.

جاوا

راهنمای نصب کتابخانه کلاینت جاوا

پی اچ پی

راهنمای نصب کتابخانه کلاینت PHP

پایتون

راهنمای نصب کتابخانه کلاینت پایتون

نود جی اس

راهنمای نصب کتابخانه کلاینت Node.js

دات نت

راهنمای نصب کتابخانه کلاینت دات نت

روبی

راهنمای نصب کتابخانه کلاینت روبی

استراحت

متغیرهای محیطی خود را با وارد کردن موارد زیر پیکربندی کنید.

  1. به جای ORGANIZATION_ID ، شناسه سازمان پلتفرم بازاریابی گوگل خود را وارد کنید.
  2. به جای PROJECT_ID ، شناسه پروژه گوگل کلود خود را وارد کنید.

یک فراخوانی API انجام دهید

اکنون می‌توانید از API پلتفرم بازاریابی گوگل برای فهرست کردن حساب‌های گوگل آنالیتیکس که به سازمان پلتفرم بازاریابی گوگل مشخص شده لینک شده‌اند، استفاده کنید. کد زیر را برای انجام اولین فراخوانی API اجرا کنید:

جاوا

هنگام اجرای شروع سریع، فراخوانی‌های .setPageSize ‎ و .setPageToken ‎ را حذف کنید.

import com.google.ads.marketingplatform.admin.v1alpha.AnalyticsAccountLink;
import com.google.ads.marketingplatform.admin.v1alpha.ListAnalyticsAccountLinksRequest;
import com.google.ads.marketingplatform.admin.v1alpha.MarketingplatformAdminServiceClient;
import com.google.ads.marketingplatform.admin.v1alpha.OrganizationName;

public class SyncListAnalyticsAccountLinks {

  public static void main(String[] args) throws Exception {
    syncListAnalyticsAccountLinks();
  }

  public static void syncListAnalyticsAccountLinks() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (MarketingplatformAdminServiceClient marketingplatformAdminServiceClient =
        MarketingplatformAdminServiceClient.create()) {
      ListAnalyticsAccountLinksRequest request =
          ListAnalyticsAccountLinksRequest.newBuilder()
              .setParent(OrganizationName.of("[ORGANIZATION]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .build();
      for (AnalyticsAccountLink element :
          marketingplatformAdminServiceClient.listAnalyticsAccountLinks(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}

پی اچ پی

use Google\Ads\MarketingPlatform\Admin\V1alpha\AnalyticsAccountLink;
use Google\Ads\MarketingPlatform\Admin\V1alpha\Client\MarketingplatformAdminServiceClient;
use Google\Ads\MarketingPlatform\Admin\V1alpha\ListAnalyticsAccountLinksRequest;
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;

/**
 * Lists the Google Analytics accounts link to the specified Google Marketing
 * Platform organization.
 *
 * @param string $formattedParent The parent organization, which owns this collection of Analytics
 *                                account links. Format: organizations/{org_id}
 *                                Please see {@see MarketingplatformAdminServiceClient::organizationName()} for help formatting this field.
 */
function list_analytics_account_links_sample(string $formattedParent): void
{
    // Create a client.
    $marketingplatformAdminServiceClient = new MarketingplatformAdminServiceClient();

    // Prepare the request message.
    $request = (new ListAnalyticsAccountLinksRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $marketingplatformAdminServiceClient->listAnalyticsAccountLinks($request);

        /** @var AnalyticsAccountLink $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = MarketingplatformAdminServiceClient::organizationName('[ORGANIZATION]');

    list_analytics_account_links_sample($formattedParent);
}

پایتون

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.ads import marketingplatform_admin_v1alpha


def sample_list_analytics_account_links():
    # Create a client
    client = marketingplatform_admin_v1alpha.MarketingplatformAdminServiceClient()

    # Initialize request argument(s)
    request = marketingplatform_admin_v1alpha.ListAnalyticsAccountLinksRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_analytics_account_links(request=request)

    # Handle the response
    for response in page_result:
        print(response)

نود جی اس

کاربرد: node packages/google-marketingplatform-admin/samples/quickstart.js organizations/ORGANIZATION_ID.

  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The parent organization, which owns this collection of Analytics
   *  account links. Format: organizations/{org_id}
   */
  // const parent = 'abc123'
  /**
   *  Optional. The maximum number of Analytics account links to return in one
   *  call. The service may return fewer than this value.
   *  If unspecified, at most 50 Analytics account links will be returned. The
   *  maximum value is 1000; values above 1000 will be coerced to 1000.
   */
  // const pageSize = 1234
  /**
   *  Optional. A page token, received from a previous ListAnalyticsAccountLinks
   *  call. Provide this to retrieve the subsequent page.
   *  When paginating, all other parameters provided to
   *  `ListAnalyticsAccountLinks` must match the call that provided the page
   *  token.
   */
  // const pageToken = 'abc123'

  // Imports the Admin library
  const {MarketingplatformAdminServiceClient} =
    require('@google-ads/marketing-platform-admin').v1alpha;

  // Instantiates a client
  const adminClient = new MarketingplatformAdminServiceClient({fallback: true});

  async function callListAnalyticsAccountLinks() {
    // Construct request
    const request = {
      parent,
    };

    // Run request
    const iterable = adminClient.listAnalyticsAccountLinksAsync(request);
    for await (const response of iterable) {
      console.log(response);
    }
  }

  callListAnalyticsAccountLinks();

دات نت

    using Google.Ads.MarketingPlatform.Admin.V1Alpha;
    using Google.Api.Gax;
    using System;

    public sealed partial class GeneratedMarketingplatformAdminServiceClientSnippets
    {
        /// <summary>Snippet for ListAnalyticsAccountLinks</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void ListAnalyticsAccountLinks()
        {
            // Create client
            MarketingplatformAdminServiceClient marketingplatformAdminServiceClient = MarketingplatformAdminServiceClient.Create();
            // Initialize request argument(s)
            string parent = "organizations/[ORGANIZATION]";
            // Make the request
            PagedEnumerable<ListAnalyticsAccountLinksResponse, AnalyticsAccountLink> response = marketingplatformAdminServiceClient.ListAnalyticsAccountLinks(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (AnalyticsAccountLink item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListAnalyticsAccountLinksResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (AnalyticsAccountLink item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<AnalyticsAccountLink> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (AnalyticsAccountLink item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }

استراحت

برای ارسال این درخواست، دستور curl را از خط فرمان اجرا کنید یا فراخوانی REST را در برنامه خود بگنجانید.

curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \\
  -H "x-goog-user-project: ${PROJECT_ID}"
  -H "Content-Type: application/json" \\
  https://marketingplatformadmin.googleapis.com/v1alpha/organizations/${ORGANIZATION_ID}/analyticsAccountLinks

کد نمونه، پاسخی را با فهرستی از حساب‌های گوگل آنالیتیکس مرتبط با سازمان مشخص‌شده‌ی پلتفرم بازاریابی گوگل چاپ می‌کند:

{
  "analyticsAccountLinks": [
    {
      "name": "organizations/0a123456789-wxyz/analyticsAccountLinks/1234567890",
      "analyticsAccount": "analyticsadmin.googleapis.com/accounts/1234567890",
      "displayName": "Demo Account",
      "linkVerificationState": "LINK_VERIFICATION_STATE_VERIFIED"
    }
  ]
}

تبریک! شما اولین درخواست خود را به API پلتفرم بازاریابی گوگل ارسال کردید.