Truy xuất đơn vị quảng cáo và thông tin chi tiết về ứng dụng

Hướng dẫn này chỉ cho bạn cách xem khoảng không quảng cáo, bao gồm các mục như ứng dụng và đơn vị quảng cáo theo phương thức lập trình.

Điều kiện tiên quyết

Chi tiết ứng dụng

Bạn có thể xem thông tin chi tiết và chế độ cài đặt của ứng dụng theo phương thức lập trình thông qua API AdMob, chẳng hạn như mã ứng dụng, mã cửa hàng ứng dụng và nền tảng. Để biết thêm thông tin, hãy xem accounts.apps.list.

Đơn vị quảng cáo

Đơn vị quảng cáo là một tập hợp các quảng cáo hiển thị nhờ một đoạn mã quảng cáo AdMob. Để biết thêm thông tin, hãy xem accounts.adUnits.list.

Tạo yêu cầu

Có một số cách để gửi yêu cầu đầu tiên:

Thư viện ứng dụng Java

Yêu cầu bằng thư viện ứng dụng Java

  1. Tải tệp bí mật ứng dụng khách và tạo thông tin xác thực uỷ quyền.

    Khi thực hiện bước này lần đầu tiên, bạn sẽ được yêu cầu chấp nhận lời nhắc uỷ quyền trong trình duyệt. Trước khi chấp nhận, hãy nhớ đăng nhập bằng Tài khoản Google có quyền truy cập vào API AdMob. Ứng dụng của bạn sẽ được uỷ quyền truy cập vào dữ liệu thay mặt cho bất kỳ tài khoản nào đang đăng nhập.

    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.util.Utils;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.util.store.DataStoreFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.services.admob.v1.AdMob;
    
    ...
    
    /** Directory to store user credentials. */
    private static final java.io.File DATA_STORE_DIR =
        new java.io.File(System.getProperty("user.home"), ".store/admobapi_sample");
    
    private static final HttpTransport HTTP_TRANSPORT = Utils.getDefaultTransport();
    private static final JsonFactory JSON_FACTORY = Utils.getDefaultJsonFactory();
    
    // Load client secrets JSON file.
    String pathToClientSecretsFile = "INSERT_PATH_TO_CLIENT_SECRETS";
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(
            JSON_FACTORY,
            Files.newBufferedReader(Paths.get(pathToClientSecretsFile), UTF_8)
        );
    
    // Set up the authorization code flow.
    //
    // Note: providing a DataStoreFactory allows auth credentials to be cached,
    // so they survive multiple runs of the program. This avoids prompting the
    // user for authorization every time the access token expires, by remembering
    // the refresh token.
    ImmutableSet<String> READONLY_SCOPE =
        ImmutableSet.of("https://www.googleapis.com/auth/admob.readonly");
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
             HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, READONLY_SCOPE)
            .setDataStoreFactory(dataStoreFactory)
            .build();
    
    // Build installed application credential.
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    
  2. Tạo một ứng dụng AdMob được uỷ quyền.

    // Create an AdMob client instance.
    AdMob admob =
        new AdMob.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("admobapi-java-samples")
            .build();
    
  3. Liệt kê ứng dụng.

     ListAppsResponse response;
     String nextPageToken = null;
    
     do {
       // Create and execute the apps list request.
       response =
           adMob
               .accounts()
               .apps()
               .list(ACCOUNT_NAME)
               .setPageSize(PAGE_SIZE)
               .setPageToken(nextPageToken)
               .execute();
    
       // Display apps.
       List<App> apps = response.getApps();
    
       for (App app : apps) {
         AppLinkedAppInfo linkedAppInfo = app.getLinkedAppInfo();
    
         System.out.printf(
             "App Name: %s, "
                 + "App ID: %s, "
                 + "App Platform: %s, "
                 + "App Store ID: %s, "
                 + "App Store Display Name: %s, "
                 + "App Manual Info: %s%n",
             app.getName(),
             app.getAppId(),
             app.getPlatform(),
             linkedAppInfo == null ? "" : linkedAppInfo.getAppStoreId(),
             linkedAppInfo == null ? "" : linkedAppInfo.getDisplayName(),
             app.getManualAppInfo().getDisplayName());
       }
    
       // Update the next page token.
       nextPageToken = response.getNextPageToken();
     } while (nextPageToken != null && !nextPageToken.isEmpty());
    
  4. Liệt kê đơn vị quảng cáo.

     ListAdUnitsResponse response;
     String nextPageToken = null;
    
     do {
       // Create and execute the ad units list request.
       response =
           adMob
               .accounts()
               .adUnits()
               .list(ACCOUNT_NAME)
               .setPageSize(PAGE_SIZE)
               .setPageToken(nextPageToken)
               .execute();
    
       // Display ad units.
       List<AdUnit> adUnits = response.getAdUnits();
       for (AdUnit adUnit : adUnits) {
         System.out.printf(
             "Ad Unit Display Name: %s, "
                 + "Ad Unit Name: %s, "
                 + "Ad Unit ID: %s, "
                 + "Ad Unit Format: %s, "
                 + "Ad Unit App ID: %s, "
                 + "Ad Unit Ad Types: %s%n",
             adUnit.getDisplayName(),
             adUnit.getName(),
             adUnit.getAdUnitId(),
             adUnit.getAdFormat(),
             adUnit.getAppId(),
             adUnit.getAdTypes());
       }
    
       // Update the next page token.
       nextPageToken = response.getNextPageToken();
     } while (nextPageToken != null && !nextPageToken.isEmpty());
    

Thư viện ứng dụng PHP

Yêu cầu qua thư viện ứng dụng PHP

  1. Tải tệp khoá bí mật của ứng dụng và tạo một ứng dụng AdMob được uỷ quyền.

    Khi thực hiện bước này lần đầu tiên, bạn sẽ được yêu cầu chấp nhận lời nhắc uỷ quyền trong trình duyệt. Trước khi chấp nhận, hãy nhớ đăng nhập bằng Tài khoản Google có quyền truy cập vào API AdMob. Ứng dụng của bạn sẽ được uỷ quyền truy cập vào dữ liệu thay mặt cho bất kỳ tài khoản nào đang đăng nhập.

    // Create an AdMob Client.
    $client = new Google_Client();
    $client->addScope('https://www.googleapis.com/auth/admob.readonly');
    $client->setApplicationName('AdMob API PHP Quickstart');
    $client->setAccessType('offline');
    
    // Be sure to replace the contents of client_secrets.json with your developer
    // credentials.
    $client->setAuthConfig('client_secrets.json');
    
    // Create the URL for the authorization prompt.
    $authUrl = $client->createAuthUrl();
    
    // Once the authorization prompt has been accepted, exchange the
    // authorization code for an access and refresh token.
    $client->authenticate($_GET['code']);
    $client->getAccessToken();
    
  2. Tạo đối tượng dịch vụ AdMob.

    // Create an AdMob service object on which to run the requests.
    $service = new Google_Service_AdMob($client);
    
  3. Liệt kê ứng dụng.

     // Create the page token variable.
     $pageToken = '';
    
     $optParams['pageSize'] = $maxPageSize;
    
     do {
         $optParams['pageToken'] = $pageToken;
         // Get list of apps.
         $response = $service->accounts_apps->listAccountsApps($accountName, $optParams);
         $apps = $response->getApps();
    
         // Print list of apps.
         if (!empty($apps)) {
             foreach ($apps as $app) {
                 if(!empty($app->getLinkedAppInfo)){
                     $appStoreId = $app->getLinkedAppInfo()->getAppStoreId();
                     $displayName = $app->getLinkedAppInfo()->getDisplayName();
                 } else {
                     $appStoreId = '';
                     $displayName = '';
                 }
                 printf(
                   "App Name: '%s' \n"
                   ."App ID: '%s' \n"
                   ."App Platform: '%s' \n"
                   ."App Store ID: '%s' \n"
                   ."App Store Display Name: '%s' \n"
                   ."App Display Name: '%s' \n\n",
                   $app->getName(),
                   $app->getAppId(),
                   $app->getPlatform(),
                   $appStoreId,
                   $displayName,
                   $app->getManualAppInfo()->getDisplayName(),
                 );
             }
         }
         $pageToken = $response->getNextPageToken();
     } while ($pageToken);
    
  4. Liệt kê đơn vị quảng cáo.

     // Create the page token variable.
     $pageToken = '';
    
     $optParams['pageSize'] = $maxPageSize;
    
     do {
         $optParams['pageToken'] = $pageToken;
         // Get list of ad units.
         $response = $service->accounts_adUnits->listAccountsAdUnits($accountName, $optParams);
         $adUnits = $response->adUnits;
    
         // Print list of ad units.
         if (!empty($adUnits)) {
             foreach ($adUnits as $adUnit) {
                 printf(
                   "Ad Unit Display Name: '%s' \n"
                   ."Ad Unit Name: '%s' \n"
                   ."Ad Unit ID: '%s' \n"
                   ."Ad Unit Format: '%s' \n"
                   ."Ad Unit App ID: '%s' \n"
                   ."Ad Unit Ad Types: '%s' \n\n",
                   $adUnit->getDisplayName(),
                   $adUnit->getName(),
                   $adUnit->getAdUnitId(),
                   $adUnit->getAdFormat(),
                   $adUnit->getAppId(),
                   json_encode($adUnit->getAdTypes()),
                     );
             }
         }
         $pageToken = $response->getNextPageToken();
     } while ($pageToken);
    

Thư viện ứng dụng Python

Yêu cầu bằng thư viện ứng dụng Python

  1. Tải tệp bí mật ứng dụng khách và tạo thông tin xác thực uỷ quyền.

    Khi thực hiện bước này lần đầu tiên, bạn sẽ được yêu cầu chấp nhận lời nhắc uỷ quyền trong trình duyệt. Trước khi chấp nhận, hãy nhớ đăng nhập bằng Tài khoản Google có quyền truy cập vào API AdMob. Ứng dụng của bạn sẽ được uỷ quyền truy cập vào dữ liệu thay mặt cho bất kỳ tài khoản nào đang đăng nhập.

    import os
    
    from google_auth_oauthlib.flow import Flow
    from googleapiclient.discovery import build
    from google.auth.transport.requests import Request
    
    ...
    
    # Authenticate using the client_secrets file.
    client_secrets = os.path.join(
        os.path.dirname(__file__), 'client_secrets.json')
    flow = Flow.from_client_secrets_file(
        client_secrets,
        scopes=['https://www.googleapis.com/auth/admob.readonly'],
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    
    # Redirect the user to auth_url on your platform.
    auth_url, _ = flow.authorization_url()
    print('Please go to this URL: {}\n'.format(auth_url))
    
    # The user will get an authorization code. This code is used to get the
    # access token.
    code = input('Enter the authorization code: ')
    flow.fetch_token(code=code)
    credentials = flow.credentials
    
  2. Tạo đối tượng dịch vụ AdMob.

    // Create an AdMob service object on which to run the requests.
    admob = build('admob', 'v1', credentials=credentials)
    
  3. Liệt kê ứng dụng.

    next_page_token = ''
    while True:
      # Execute the request.
      response = service.accounts().apps().list(
          pageSize=PAGE_SIZE,
          pageToken=next_page_token,
          parent='accounts/{}'.format(publisher_id)).execute()
    
      # Check if the response is empty.
      if not response:
        break
    
      # Print the result.
      apps = response['apps']
      for app in apps:
        print('App ID: ' + app['appId'])
        print('App Platform: ' + app['platform'])
        print('App Name: ' + app['name'])
    
        if 'linkedAppInfo' in app:
          linked_app_info = app['linkedAppInfo']
          print('App Store ID: ' + linked_app_info['appStoreId'])
          print('App Store Display Name: ' + linked_app_info['displayName'])
    
        if 'manualAppInfo' in app:
          manual_app_info = app['manualAppInfo']
          print('App Manual Info: ' + manual_app_info['displayName'])
    
      if 'nextPageToken' not in response:
        break
    
      # Update the next page token.
      next_page_token = response['nextPageToken']
    
    
  4. Liệt kê đơn vị quảng cáo.

    next_page_token = ''
    while True:
      # Execute the request.
      response = service.accounts().adUnits().list(
          pageSize=PAGE_SIZE,
          pageToken=next_page_token,
          parent='accounts/{}'.format(publisher_id)).execute()
    
      # Check if the response is empty.
      if not response:
        break
    
      # Print the result.
      ad_units = response['adUnits']
      for ad_unit in ad_units:
        print('Ad Unit Display Name: ' + ad_unit['displayName'])
        print('Ad Unit Name: ' + ad_unit['name'])
        print('Ad Unit ID: ' + ad_unit['adUnitId'])
        print('Ad Unit Format: ' + ad_unit['adFormat'])
        print('Ad Unit App ID: ' + ad_unit['appId'])
        print('Ad Unit Format: ' + ', '.join(ad_unit['adTypes']))
    
      if 'nextPageToken' not in response:
        break
      # Update the next page token.
      next_page_token = response['nextPageToken']
    

curl (dòng lệnh)

Yêu cầu bằng curl

  1. Tải tệp bí mật ứng dụng khách và tạo thông tin xác thực uỷ quyền.

    Khi thực hiện bước này lần đầu tiên, bạn sẽ được yêu cầu chấp nhận lời nhắc uỷ quyền trong trình duyệt. Trước khi chấp nhận, hãy nhớ đăng nhập bằng Tài khoản Google có quyền truy cập vào API AdMob. Ứng dụng của bạn sẽ được uỷ quyền truy cập vào dữ liệu thay mặt cho bất kỳ tài khoản nào đang đăng nhập.

    Để xác thực và uỷ quyền, bạn nên sử dụng OAuth2l, một công cụ dòng lệnh đơn giản để làm việc với Google OAuth 2.0. Cài đặt OAuth2l và chạy lệnh bên dưới, thay thế path_to_credentials_json bằng một đường dẫn đến tệp credentials.json mà bạn tải xuống khi đăng ký ứng dụng trên đám mây. Đối với lần chạy đầu tiên, lệnh này sẽ hướng dẫn bạn thực hiện quy trình uỷ quyền OAuth 2.0. Các lần chạy tiếp theo sẽ tự động làm mới mã thông báo.

    oauth2l header --json path_to_credentials_json \
    --scope admob.readonly
    
  2. Liệt kê ứng dụng.

    curl -X GET https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/apps \
     -H "$(oauth2l header --json path_to_credentials_json \
     --scope admob.readonly)"
    

    Câu trả lời mẫu:

    {
     "app": [
       {
         "name": "accounts/pub-XXXXXXXXXXXXXXXX/apps/XXXXXXXXXX",
         "appId": "ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX",
         "platform": "ANDROID",
         "manualAppInfo": {
           "displayName": "Example App"
         },
         "linkedAppInfo": {
           "appStoreId": "com.example.myApp",
           "displayName": "Example App",
         }
       }
     ]
    }
    
  3. Liệt kê đơn vị quảng cáo.

    curl -X GET https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/adUnits \
    -H "$(oauth2l header --json path_to_credentials_json \
    --scope admob.readonly)"
    

    Câu trả lời mẫu:

    {
     "adUnit": [
       {
         "name": "accounts/pub-XXXXXXXXXXXXXXXX/adUnits/XXXXXXXXXX",
         "adUnitId": "ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX",
         "appId": "ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX",
         "displayName": "AdMob Rewarded",
         "adFormat": "REWARDED",
    
         "adTypes": ["RICH_MEDIA", "VIDEO"],
       }
     ]
    }