Trong hướng dẫn nhanh này, bạn sẽ tạo các yêu cầu đến API Quản trị của Google Marketing Platform và xem các phản hồi chứa danh sách tài khoản Google Analytics được liên kết với tổ chức Google Marketing Platform đã chỉ định.
Bạn có thể hoàn tất hướng dẫn bắt đầu nhanh này bằng cách sử dụng SDK ngôn ngữ lập trình trong môi trường cục bộ hoặc API REST.
Điều kiện tiên quyết
Để hoàn tất hướng dẫn nhanh này, bạn cần:
- Thiết lập dự án Google Cloud và bật API Quản trị của Google Marketing Platform
- Trên máy cục bộ:
- Cài đặt, khởi chạy và xác thực bằng Google Cloud
- Cài đặt SDK cho ngôn ngữ của bạn
Thiết lập dự án trên Google Cloud
Thiết lập dự án Google Cloud và bật API Quản trị của Google Marketing Platform.
Nhấp vào nút này để chọn hoặc tạo một dự án Google Cloud mới và tự động bật API Quản trị của Google Marketing Platform:
Bật API Quản trị của Google Marketing PlatformThiết lập Google Cloud
Trên máy cục bộ, hãy thiết lập và xác thực bằng Google Cloud.
-
Cài đặt và khởi chạy Google Cloud.
-
Nếu trước đây bạn đã cài đặt Google Cloud, hãy đảm bảo các thành phần
gcloud
của bạn được cập nhật bằng cách chạy lệnh này.gcloud components update
-
Để xác thực với Google Cloud, hãy tạo một tệp Thông tin xác thực mặc định của ứng dụng (ADC) cục bộ bằng cách chạy lệnh sau. Quy trình web do lệnh này khởi chạy được dùng để cung cấp thông tin xác thực người dùng.
gcloud auth application-default login --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/marketingplatformadmin.analytics.read"
Lưu ý cách chỉ định các phạm vi mà API quản trị của Google Marketing Platform yêu cầu trong lệnh.
Để biết thêm thông tin, hãy xem bài viết Thiết lập thông tin xác thực mặc định của ứng dụng.
API Quản trị của Google Marketing Platform yêu cầu một dự án hạn mức. Dự án này không được đặt theo mặc định. Để tìm hiểu cách đặt dự án hạn mức, hãy xem Hướng dẫn về thông tin xác thực người dùng.
Xác định mã tổ chức Google Marketing Platform
Để sử dụng API Quản trị của Google Marketing Platform, bạn cần xác định mã tổ chức của mình trong Google Marketing Platform. Đăng nhập vào Google Marketing Platform, chuyển đến hộp thoại Quản trị, chọn tổ chức của bạn rồi ghi lại Mã tổ chức trong phần Chi tiết về tổ chức.
Tất cả yêu cầu gửi đến API Quản trị của Google Marketing Platform phải bao gồm mã tổ chức ở định dạng organizations/ORGANIZATION_ID
.
Thiết lập SDK cho ngôn ngữ lập trình
Trên máy cục bộ, hãy nhấp vào một trong các thẻ sau để cài đặt SDK cho ngôn ngữ lập trình của bạn.
Java
PHP
Python
Node.js
.NET
Ruby
REST
Định cấu hình các biến môi trường bằng cách nhập nội dung sau.
- Thay thế
ORGANIZATION_ID
bằng mã nhận dạng của tổ chức Google Marketing Platform. - Thay thế
PROJECT_ID
bằng mã nhận dạng của dự án Google Cloud.
Thực hiện lệnh gọi API
Giờ đây, bạn có thể sử dụng API Google Marketing Platform để liệt kê các tài khoản Google Analytics liên kết với tổ chức Google Marketing Platform đã chỉ định. Chạy mã sau để thực hiện lệnh gọi đầu tiên đến API:
Java
Xoá các lệnh gọi đến .setPageSize
và .setPageToken
khi chạy phần hướng dẫn nhanh.
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
Cách sử dụng: 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
Để gửi yêu cầu này, hãy chạy lệnh curl từ dòng lệnh hoặc đưa lệnh gọi REST vào ứng dụng.
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
Mã mẫu sẽ in một phản hồi có danh sách các tài khoản Google Analytics được liên kết với tổ chức Google Marketing Platform đã chỉ định:
{
"analyticsAccountLinks": [
{
"name": "organizations/0a123456789-wxyz/analyticsAccountLinks/1234567890",
"analyticsAccount": "analyticsadmin.googleapis.com/accounts/1234567890",
"displayName": "Demo Account",
"linkVerificationState": "LINK_VERIFICATION_STATE_VERIFIED"
}
]
}
Xin chúc mừng! Bạn đã gửi yêu cầu đầu tiên đến API Google Marketing Platform.