البدء السريع: إدارة روابط حسابات "إحصاءات Google" باستخدام Google Marketing Platform Admin API

في هذا التشغيل السريع، ستنشئ طلبات إلى Admin API في "منصة Google للتسويق" وستعرض الردود التي تحتوي على قائمة بحسابات "إحصاءات Google" المرتبطة بمؤسسة "منصة Google للتسويق" المحدّدة.

يمكنك إكمال هذا التشغيل السريع باستخدام حزمة SDK للغة برمجة في بيئتك المحلية أو واجهة REST API.

المتطلبات الأساسية

يتطلّب إكمال هذا التشغيل السريع ما يلي:

  • إعداد مشروع على Google Cloud وتفعيل Admin API في "منصة Google للتسويق"
  • على جهازك المحلي:
    • تثبيت Google Cloud وتهيئته والمصادقة عليه
    • تثبيت حزمة SDK للغة البرمجة التي تستخدمها

إعداد مشروع على Google Cloud

عليك إعداد مشروعك على Google Cloud وتفعيل Admin API في "منصة Google للتسويق".

انقر على هذا الزر لاختيار مشروع على السحابة الإلكترونية جديد على Google Cloud أو إنشائه وتفعيل Admin API في "منصة Google للتسويق" تلقائيًا:

تفعيل Admin API في "منصة Google للتسويق"

إعداد Google Cloud

على جهازك المحلي، عليك إعداد Google Cloud والمصادقة عليه.

  1. ثبِّت Google Cloud وتهيئته.

  2. إذا سبق لك تثبيت Google Cloud، تأكَّد من تعديل مكوّنات gcloud من خلال تشغيل هذا الأمر.

    gcloud components update
  3. للمصادقة على Google Cloud، أنشئ ملف بيانات الاعتماد التلقائية للتطبيق (ADC) محليًا من خلال تشغيل هذا الأمر. يتم استخدام مسار الويب الذي يبدأه الأمر لتقديم بيانات اعتماد المستخدم.

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

    لاحظ كيفية تحديد النطاقات المطلوبة من Admin API في "منصة Google للتسويق" في الأمر.

    لمزيد من المعلومات، يُرجى الاطّلاع على مقالة إعداد "بيانات الاعتماد التلقائية للتطبيق".

تتطلّب Admin API في "منصة Google للتسويق" مشروع حصة، وهو غير مضبوط تلقائيًا. للتعرّف على كيفية ضبط مشروع الحصة، يُرجى الاطّلاع على دليل بيانات اعتماد المستخدم.

تحديد رقم تعريف مؤسستك على "منصة Google للتسويق"

لاستخدام Admin API في "منصة Google للتسويق"، عليك تحديد رقم تعريف مؤسستك على "منصة Google للتسويق". سجِّل الدخول إلى منصة Google للتسويق، وانتقِل إلى مربّع الحوار الإدارة، واختَر مؤسستك، ثمّ سجِّل رقم تعريف المؤسسة ضمن تفاصيل المؤسسة.

يجب أن تتضمّن جميع الطلبات إلى Admin API في "منصة Google للتسويق" رقم تعريف المؤسسة بالتنسيق organizations/ORGANIZATION_ID.

إعداد حزمة SDK للغة البرمجة التي تستخدمها

على جهازك المحلي، انقر على أحد علامات التبويب التالية لتثبيت حزمة SDK للغة البرمجة التي تستخدمها.

جافا

دليل تثبيت مكتبة برامج Java

PHP

دليل تثبيت مكتبة برامج PHP

Python

دليل تثبيت مكتبة برامج Python

Node.js

دليل تثبيت مكتبة برامج Node.js

NET.

دليل تثبيت مكتبة برامج ‎.NET

Ruby

دليل تثبيت مكتبة برامج Ruby

REST

عليك ضبط متغيّرات البيئة من خلال إدخال ما يلي.

  1. استبدِل ORGANIZATION_ID برقم تعريف مؤسستك على "منصة Google للتسويق" .
  2. استبدِل PROJECT_ID برقم تعريف مشروعك على Google Cloud.

تقديم طلب بيانات من واجهة برمجة التطبيقات

يمكنك الآن استخدام Google Marketing Platform API لعرض حسابات "إحصاءات Google" المرتبطة بمؤسسة "منصة Google للتسويق" المحدّدة. شغِّل الرمز البرمجي التالي لإجراء أول طلب بيانات من واجهة برمجة التطبيقات:

جافا

أزِل طلبات البيانات من .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);
      }
    }
  }
}

PHP

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);
}

Python

# 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.js

Usage: 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();

NET.

    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;
        }
    }

REST

لإرسال هذا الطلب، شغِّل أمر 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

يطبع نموذج الرمز البرمجي ردًا يتضمّن قائمة بحسابات "إحصاءات Google" المرتبطة بمؤسسة "منصة Google للتسويق" المحدّدة:

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

تهانينا! لقد أرسلت أول طلب بيانات من Google Marketing Platform API.