Tạo báo cáo

Hướng dẫn này dành cho những nhà phát triển đã hoàn thành các bước điều kiện tiên quyết và muốn sử dụng API AdMob để lấy thông tin về tài khoản AdMob của họ, cũng như tạo báo cáo mạng và báo cáo dàn xếp theo phương thức lập trình.

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

Tạo yêu cầu

API AdMob được xây dựng trên nền tảng HTTP và JSON, do đó, mọi ứng dụng HTTP tiêu chuẩn đều có thể gửi yêu cầu tới API AdMob và phân tích cú pháp các phản hồi. Tuy nhiên, [Thư viện ứng dụng Google API][client_Libraries] cung cấp khả năng tích hợp ngôn ngữ tốt hơn, cải thiện khả năng bảo mật và hỗ trợ việc đưa ra các yêu cầu được cho phép. Các thư viện ứng dụng được cung cấp bằng một số ngôn ngữ lập trình. Bằng cách sử dụng các thư viện đó, bạn có thể tránh phải thiết lập yêu cầu HTTP và phân tích cú pháp phản hồi theo cách thủ công.

Nếu tạo thông tin xác thực OAuth 2.0, bạn đã sẵn sàng bắt đầu sử dụng API AdMob. Để yêu cầu quyền truy cập bằng OAuth 2.0, ứng dụng của bạn cũng sẽ cần thông tin về phạm vi.

Dưới đây là thông tin về phạm vi của OAuth 2.0:

Phạm vi Ý nghĩa
https://www.googleapis.com/auth/admob.readonly Xem tất cả dữ liệu AdMob. Dữ liệu này có thể bao gồm thông tin tài khoản, chế độ cài đặt khoảng không quảng cáo và tính năng dàn xếp, báo cáo và các dữ liệu khác. Tuy nhiên, nữ liệu này không bao gồm dữ liệu nhạy cảm (chẳng hạn như thông tin về thanh toán hoặc thông tin chiến dịch).
https://www.googleapis.com/auth/admob.report Xem báo cáo hiệu suất quảng cáo và thu nhập. Xem mã nhà xuất bản, múi giờ và mã đơn vị tiền tệ mặc định.

Hiện chúng tôi trình bày một số cách để đưa ra yêu cầu đầu tiên của bạ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.

    /**
     * Attempts to load user credentials from the provided client secrets file and persists data to
     * the provided data store.
     *
     * @param clientSecretsFile The path to the file containing client secrets.
     * @param dataStoreFactory he data store to use for caching credential information.
     * @return A {@link Credential} object initialized with user account credentials.
     */
    private static Credential loadUserCredentials(
        String clientSecretsFile, @Nonnull DataStoreFactory dataStoreFactory)
        throws CredentialException, IOException, RuntimeException {
    
      // Load client secrets JSON file.
      GoogleClientSecrets clientSecrets = null;
      try (Reader reader = Files.newBufferedReader(Paths.get(clientSecretsFile), UTF_8)) {
        clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, reader);
      }
    
      // Set up the authorization code flow.
      GoogleAuthorizationCodeFlow flow =
          new GoogleAuthorizationCodeFlow.Builder(
                  HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, ADMOB_READONLY)
              .setDataStoreFactory(dataStoreFactory)
              .build();
    
      // Authorize and persist credential information to the data store.
      return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }
    
    /**
     * Performs all necessary setup steps for running requests against the API.
     *
     * @return An initialized {@link AdMob} service object.
     */
    public static AdMob getInstance() throws Exception {
      Credential credential = authorize();
    
      // Create AdMob client.
      return new AdMob.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
          .setApplicationName("admobapi-java-samples")
          .build();
    }
    
  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. Nhận thông tin tài khoản.

    /* ACCOUNT_NAME should follow the format "accounts/pub-XXXXXXXXXXXXXXXX"
     * where "pub-XXXXXXXXXXXXXXXX" is your publisher ID
     * See https://support.google.com/admob/answer/2784578
     * for instructions on how to find your publisher ID.
     */
    private static final String ACCOUNT_NAME = "accounts/pub-XXXXXXXXXXXXXXXX";
    
    public static void runExample(AdMob adMob, String accountName) throws Exception {
    
      // Get publisher account.
      PublisherAccount account = adMob.accounts().get(accountName).execute();
    
      // Display publisher account information.
      System.out.printf(
          "Publisher Name: %s, Publisher Id: %s, Currency Code: %s, Reporting Time Zone: %s%n",
          account.getName(),
          account.getPublisherId(),
          account.getCurrencyCode(),
          account.getReportingTimeZone());
    }
    
  4. Tạo báo cáo mạng.

    public static void runExample(
        AdMob adMob, String accountName, GenerateNetworkReportRequest request)
        throws Exception {
    
      // Get network report.
      InputStream response =
          adMob
              .accounts()
              .networkReport()
              .generate(accountName, request)
              .executeAsInputStream();
    
      List<GenerateNetworkReportResponse> result =
          Arrays.asList(
              new JsonObjectParser(Utils.getDefaultJsonFactory())
                  .parseAndClose(
                      response, StandardCharsets.UTF_8, GenerateNetworkReportResponse[].class));
    
      // Print each record in the response stream.
      for (GenerateNetworkReportResponse record : result) {
        System.out.printf("%s%n", record);
      }
    }
    
    public static GenerateNetworkReportRequest getNetworkReportRequest() {
      /* AdMob API only supports the account default timezone and "America/Los_Angeles", see
       * https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.networkReport/generate
       * for more information.
       */
      String timeZone = "America/Los_Angeles";
      Clock clock = Clock.system(ZoneId.of(timeZone));
    
      // Specify date range.
      Date startDate = DateUtils.daysBeforeNow(clock, 30);
      Date endDate = DateUtils.today(clock);
      DateRange dateRange = new DateRange().setStartDate(startDate).setEndDate(endDate);
    
      // Specify metrics.
      ImmutableList<String> metrics = ImmutableList.of("IMPRESSIONS", "MATCH_RATE");
    
      // Specify dimensions.
      ImmutableList<String> dimensions = ImmutableList.of("FORMAT", "AD_UNIT");
    
      // Create network report specification.
      NetworkReportSpec reportSpec =
          new NetworkReportSpec()
              .setDateRange(dateRange)
              .setTimeZone(timeZone)
              .setMetrics(metrics)
              .setDimensions(dimensions);
    
      // Create network report request.
      return new GenerateNetworkReportRequest().setReportSpec(reportSpec);
    }
    
  5. Tạo báo cáo dàn xếp.

    public static void runExample(
        AdMob adMob, String accountName, GenerateMediationReportRequest request)
        throws Exception {
    
      // Get mediation report.
      InputStream response =
          adMob
              .accounts()
              .mediationReport()
              .generate(accountName, request)
              .executeAsInputStream();
    
      List<GenerateMediationReportResponse> result =
          Arrays.asList(
              new JsonObjectParser(Utils.getDefaultJsonFactory())
                  .parseAndClose(
                      response, StandardCharsets.UTF_8, GenerateMediationReportResponse[].class));
    
      // Print each record in the response stream.
      for (GenerateMediationReportResponse record : result) {
        System.out.printf("%s%n", record);
      }
    }
    
    public static GenerateMediationReportRequest getMediationReportRequest() {
      /* AdMob API only supports the account default timezone and "America/Los_Angeles", see
       * https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.mediationReport/generate
       * for more information.
       */
      String timeZone = "America/Los_Angeles";
      Clock clock = Clock.system(ZoneId.of(timeZone));
    
      // Specify date range.
      Date startDate = DateUtils.daysBeforeNow(clock, 30);
      Date endDate = DateUtils.today(clock);
      DateRange dateRange = new DateRange().setStartDate(startDate).setEndDate(endDate);
    
      // Specify metrics.
      ImmutableList<String> metrics = ImmutableList.of("CLICKS", "ESTIMATED_EARNINGS");
    
      // Specify dimensions.
      ImmutableList<String> dimensions = ImmutableList.of("APP", "AD_SOURCE", "COUNTRY");
    
      // Specify sorting conditions.
      List<MediationReportSpecSortCondition> sortConditions =
          new ArrayList<MediationReportSpecSortCondition>();
      sortConditions.add(
          new MediationReportSpecSortCondition().setOrder("ASCENDING").setMetric("CLICKS"));
    
      // Specify dimension filters.
      ImmutableList<String> countryList = ImmutableList.of("CA", "US");
      StringList dimensionFilterMatches = new StringList().setValues(countryList);
      List<MediationReportSpecDimensionFilter> dimensionFilters = new ArrayList<>();
      dimensionFilters.add(
          new MediationReportSpecDimensionFilter()
              .setDimension("COUNTRY")
              .setMatchesAny(dimensionFilterMatches));
    
      // Create mediation report specification.
      MediationReportSpec reportSpec =
          new MediationReportSpec()
              .setDateRange(dateRange)
              .setTimeZone(timeZone)
              .setMetrics(metrics)
              .setDimensions(dimensions)
              .setDimensionFilters(dimensionFilters)
              .setSortConditions(sortConditions);
    
      // Create mediation report request.
      return new GenerateMediationReportRequest().setReportSpec(reportSpec);
    }
    
  6. Liệt kê ứng dụng.

    // Defines maximum size page to retrieve. A smaller page size will require more API requests, see
    // inventory quota limits at https://developers.google.com/admob/api/quotas.
    private static final Integer PAGE_SIZE = 1000;
    
    public static void runExample(AdMob adMob) throws Exception {
    
      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);
    }
    
  7. Liệt kê đơn vị quảng cáo.

    // Defines maximum size page to retrieve. A smaller page size will require more API requests, see
    // inventory quota limits at https://developers.google.com/admob/api/quotas.
    private static final Integer PAGE_SIZE = 1000;
    
    public static void runExample(AdMob adMob) throws Exception {
    
      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);
    }
    

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 content 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. Nhận thông tin tài khoản.

    // Get account.
    $result = $service->accounts->get($accountName);
    
    // Print account information.
    if (!empty($result)) {
        printf(
            "
      Account Name: '%s' \n
      Publisher Id: '%s' \n
      Currency Code: '%s' \n
      Reporting Time Zone: '%s' \n",
            $result->getName(),
            $result->getPublisherId(),
            $result->getCurrencyCode(),
            $result->getReportingTimezone()
        );
    } else {
        print "No accounts found.\n";
    }
    
  4. Tạo báo cáo mạng.

    /**
     * Generates a network report.
     *
     * @param $service Google_Service_AdMob AdMob service object on which to
     *     run the requests.
     * @param account_name which follows the format "accounts/pub-XXXXXXXXXXXXXXXX".
     */
    public static function run($service, $accountName)
    {
        $separator = str_repeat('=', 80) . "\n";
        print $separator;
        print "Get Network Report\n";
        print $separator;
    
        // Generate network report.
        $networkReportRequest = self::createNetworkReportRequest();
        $networkReportResponse = $service->accounts_networkReport->generate(
            $accountName,
            $networkReportRequest
        );
    
        // Convert network report response to a simple object.
        $networkReportResponse = $networkReportResponse->tosimpleObject();
    
        // Print each record in the report.
        if (!empty($networkReportResponse)) {
            foreach ($networkReportResponse as $record) {
                printf("'%s' \n", json_encode($record));
            }
        } else {
            print "No report found.\n";
        }
        print "\n";
    }
    
    /**
     * Generates a network report request.
     */
    public static function createNetworkReportRequest()
    {
        /*
         * AdMob API only supports the account default timezone and
         * "America/Los_Angeles", see
         * https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.mediationReport/generate
         * for more information.
         */
        $startDate = DateUtils::oneWeekBeforeToday();
        $endDate = DateUtils::today();
    
        // Specify date range.
        $dateRange = new \Google_Service_AdMob_DateRange();
        $dateRange->setStartDate($startDate);
        $dateRange->setEndDate($endDate);
    
        // Create network report specification.
        $reportSpec = new \Google_Service_AdMob_NetworkReportSpec();
        $reportSpec->setMetrics(['IMPRESSIONS', 'MATCH_RATE']);
        $reportSpec->setDimensions(['FORMAT', 'AD_UNIT']);
        $reportSpec->setDateRange($dateRange);
    
        // Create network report request.
        $networkReportRequest = new \Google_Service_AdMob_GenerateNetworkReportRequest();
        $networkReportRequest->setReportSpec($reportSpec);
    
        return $networkReportRequest;
    }
    
  5. Tạo báo cáo dàn xếp.

    /**
     * Generates a mediation report.
     *
     * @param $service Google_Service_AdMob AdMob service object on which to
     *     run the requests.
     * @param account_name which follows the format "accounts/pub-XXXXXXXXXXXXXXXX".
     */
    public static function run($service, $accountName)
    {
        $separator = str_repeat('=', 80) . "\n";
        print $separator;
        print "Get Mediation Report\n";
        print $separator;
    
        // Generate mediation report.
        $mediationReportRequest = self::createMediationReportRequest();
        $mediationReportResponse = $service->accounts_mediationReport->generate(
            $accountName,
            $mediationReportRequest
        );
    
        // Convert mediation report response to a simple object.
        $mediationReportResponse = $mediationReportResponse->tosimpleObject();
    
        // Print each record in the report.
        if (!empty($mediationReportResponse)) {
            foreach ($mediationReportResponse as $record) {
                printf("'%s' \n", json_encode($record));
            }
        } else {
            print "No report found.\n";
        }
        print "\n";
    }
    
    /**
     * Generates a mediation report request.
     */
    public static function createMediationReportRequest()
    {
        /*
         * AdMob API only supports the account default timezone and
         * "America/Los_Angeles", see
         * https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.mediationReport/generate
         * for more information.
         */
        $startDate = DateUtils::oneWeekBeforeToday();
        $endDate = DateUtils::today();
    
        // Specify date range.
        $dateRange = new \Google_Service_AdMob_DateRange();
        $dateRange->setStartDate($startDate);
        $dateRange->setEndDate($endDate);
    
        // Specify sorting conditions.
        $sortConditions = new \Google_Service_AdMob_MediationReportSpecSortCondition();
        $sortConditions->setOrder('ASCENDING');
        $sortConditions->setMetric('CLICKS');
    
        // Specify dimension filters.
        $countries = new \Google_Service_AdMob_StringList();
        $countries->setValues(['CA', 'US']);
        $dimensionFilterMatches = new \Google_Service_AdMob_MediationReportSpecDimensionFilter();
        $dimensionFilterMatches->setDimension('COUNTRY');
        $dimensionFilterMatches->setMatchesAny($countries);
    
        // Create mediation report specification.
        $reportSpec = new \Google_Service_AdMob_MediationReportSpec();
        $reportSpec->setMetrics(['CLICKS', 'ESTIMATED_EARNINGS']);
        $reportSpec->setDimensions(['APP', 'AD_SOURCE', 'COUNTRY']);
        $reportSpec->setDateRange($dateRange);
        $reportSpec->setDimensionFilters($dimensionFilterMatches);
        $reportSpec->setSortConditions($sortConditions);
    
        // Create mediation report request.
        $mediationReportRequest = new \Google_Service_AdMob_GenerateMediationReportRequest();
        $mediationReportRequest->setReportSpec($reportSpec);
    
        return $mediationReportRequest;
    }
    
  6. 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);
    
  7. 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.

    PORT = 8080
    REDIRECT_URI = f"http://127.0.0.1:{PORT}"
    
    # This variable specifies the name of a file that contains the OAuth 2.0
    # information for this application, including its client_id and client_secret.
    CLIENT_SECRETS_FILE = "client_secrets.json"
    
    # Default OAuth 2.0 access parameters.
    #
    # These parameters allow for full read access to the authenticated user's AdMob
    # account and requires requests to use an SSL connection.
    API_NAME = "admob"
    API_VERSION = "v1"
    API_SCOPE = "https://www.googleapis.com/auth/admob.readonly"
    
    # Store refresh tokens in a local disk file. This file contains sensitive
    # authorization information.
    TOKEN_FILE = 'token.pickle'
    
    
    def load_user_credentials():
      # Name of a file containing the OAuth 2.0 information for this
      # application, including client_id and client_secret, which are found
      # on the Credentials tab on the Google Developers Console.
      client_secrets = os.path.join(os.path.dirname(__file__), CLIENT_SECRETS_FILE)
      return client_secrets
    
    
    # Authenticate user and create AdMob Service Object.
    def authenticate(
        api_name=API_NAME,
        api_version=API_VERSION,
        api_scopes=[API_SCOPE],
    ):
      """Authenticates a user and creates a Google API Service Object.
    
      Args:
        api_name: Google API name as shown in the API discovery doc. Defaults to the
          AdMob API.
        api_version: Google API version as shown in the API discovery doc. Defaults
          to v1.
        api_scopes: scope(s) to authenticate with oauth2 flow to access the APIs.
          Defaults to https://www.googleapis.com/auth/admob.readonly.
    
      Returns:
        A Google API Service Object that is authenticated with the user using either
        a client_secrets file or previously stored access and refresh tokens. By
        default, returns the AdMob API service object.
      """
    
      # The TOKEN_FILE stores the user's access and refresh tokens, and is
      # created automatically when the authorization flow completes for the first
      # time.
      if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'rb') as token:
          credentials = pickle.load(token)
    
        if credentials and credentials.expired and credentials.refresh_token:
          credentials.refresh(Request())
    
      # If there are no valid stored credentials, authenticate using the
      # client_secrets file.
      else:
        client_secrets = load_user_credentials()
        flow = Flow.from_client_secrets_file(client_secrets, scopes=api_scopes)
    
        flow.redirect_uri = REDIRECT_URI
    
        # Create an anti-forgery state token as described here:
        # https://developers.google.com/identity/protocols/OpenIDConnect#createxsrftoken
        passthrough_val = hashlib.sha256(os.urandom(1024)).hexdigest()
    
        # Redirect the user to auth_url on your platform.
        authorization_url, state = flow.authorization_url(
            access_type="offline",
            state=passthrough_val,
            included_granted_scopes="true")
    
        # Prints the authorization URL so you can paste into your browser. In a
        # typical web application you would redirect the user to this URL, and they
        # would be redirected back to "redirect_url" provided earlier after
        # granting permission.
        print("Paste this URL into your browser: ")
        print(authorization_url)
        print(f"\nWaiting for authorization and callback to: {REDIRECT_URI}...")
    
        # Retrieves an authorization code by opening a socket to receive the
        # redirect request and parsing the query parameters set in the URL.
        code = _get_authorization_code(passthrough_val)
    
        # Pass the code back into the OAuth module to get a refresh token.
        flow.fetch_token(code=code)
        refresh_token = flow.credentials.refresh_token
        credentials = flow.credentials
    
        print(f"\nYour refresh token is: {refresh_token}\n")
    
        # Save the credentials for the next run.
        with open(TOKEN_FILE, "wb") as token:
          pickle.dump(credentials, token)
    
      # Build the Google API service stub.
      service = build(api_name, api_version, credentials=credentials)
      return service
    
    
    def _get_authorization_code(passthrough_val):
      """Opens a socket to handle a single HTTP request containing auth tokens.
    
        Args:
            passthrough_val: an anti-forgery token used to verify the request
              received by the socket.
    
        Returns:
            a str access token from the Google Auth service.
        """
      # Open a socket at localhost:PORT and listen for a request
      sock = socket.socket()
      sock.bind(("localhost", PORT))
      sock.listen(1)
      connection, address = sock.accept()
      data = connection.recv(1024)
      # Parse the raw request to retrieve the URL query parameters.
      params = _parse_raw_query_params(data)
    
      try:
        if not params.get("code"):
          # If no code is present in the query params then there will be an
          # error message with more details.
          error = params.get("error")
          message = f"Failed to retrieve authorization code. Error: {error}"
          raise ValueError(message)
        elif params.get("state") != passthrough_val:
          message = "State token does not match the expected state."
          raise ValueError(message)
        else:
          message = "Authorization code was successfully retrieved."
      except ValueError as error:
        print(error)
        sys.exit(1)
      finally:
        response = ("HTTP/1.1 200 OK\n"
                    "Content-Type: text/html\n\n"
                    f"<b>{message}</b>"
                    "<p>Please check the console output.</p>\n")
    
        connection.sendall(response.encode())
        connection.close()
    
      return params.get("code")
    
    
    def _parse_raw_query_params(data):
      """Parses a raw HTTP request to extract its query params as a dict.
    
        Note that this logic is likely irrelevant if you're building OAuth logic
        into a complete web application, where response parsing is handled by a
        framework.
        Args:
            data: raw request data as bytes.
    
        Returns:
            a dict of query parameter key value pairs.
        """
      # Decode the request into a utf-8 encoded string
      decoded = data.decode("utf-8")
      # Use a regular expression to extract the URL query parameters string
      match = re.search("GET\s\/\?(.*) ", decoded)
      params = match.group(1)
      # Split the parameters to isolate the key/value pairs
      pairs = [pair.split("=") for pair in params.split("&")]
      # Convert pairs to a dict to make it easy to access the values
      return {key: val for key, val in pairs}
    
  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. Nhận thông tin tài khoản.

    # Set the 'PUBLISHER_ID' which follows the format "pub-XXXXXXXXXXXXXXXX".
    # See https://support.google.com/admob/answer/2784578
    # for instructions on how to find your publisher ID.
    PUBLISHER_ID = 'pub-XXXXXXXXXXXXXXXX'
    
    
    def get_account(service, publisher_id):
      """Gets and prints an AdMob account.
    
      Args:
        service: An AdMob Service Object.
        publisher_id: An ID that identifies the publisher.
      """
    
      # Execute the request.
      response = service.accounts().get(
          name='accounts/{}'.format(publisher_id)).execute()
    
      # Print the response.
      print('Name: ' + response['name'])
      print('Publisher ID: ' + response['publisherId'])
      print('Currency code: ' + response['currencyCode'])
      print('Reporting time zone: ' + response['reportingTimeZone'])
    
    
  4. Tạo báo cáo mạng.

    # Set date range. AdMob API only supports the account default timezone and
    # "America/Los_Angeles", see
    # https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.networkReport/generate
    # for more information.
    date_range = {
        'start_date': {'year': 2020, 'month': 1, 'day': 1},
        'end_date': {'year': 2020, 'month': 3, 'day': 30}
    }
    
    # Set dimensions.
    dimensions = ['DATE', 'APP', 'PLATFORM', 'COUNTRY']
    
    # Set metrics.
    metrics = ['ESTIMATED_EARNINGS', 'AD_REQUESTS', 'MATCHED_REQUESTS']
    
    # Set sort conditions.
    sort_conditions = {'dimension': 'DATE', 'order': 'DESCENDING'}
    
    # Set dimension filters.
    dimension_filters = {
        'dimension': 'COUNTRY',
        'matches_any': {
            'values': ['US', 'CA']
        }
    }
    
    # Create network report specifications.
    report_spec = {
        'date_range': date_range,
        'dimensions': dimensions,
        'metrics': metrics,
        'sort_conditions': [sort_conditions],
        'dimension_filters': [dimension_filters]
    }
    
    # Create network report request.
    request = {'report_spec': report_spec}
    
    # Execute network report request.
    response = service.accounts().networkReport().generate(
        parent='accounts/{}'.format(publisher_id), body=request).execute()
    
    # Display responses.
    for report_line in response:
      print(report_line)
    print()
    
  5. Tạo báo cáo dàn xếp.

    # Set date range. AdMob API only supports the account default timezone and
    # "America/Los_Angeles", see
    # https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.networkReport/generate
    # for more information.
    date_range = {
        'start_date': {'year': 2020, 'month': 1, 'day': 1},
        'end_date': {'year': 2020, 'month': 3, 'day': 30}
    }
    
    # Set dimensions.
    dimensions = ['DATE', 'APP', 'PLATFORM', 'COUNTRY']
    
    # Set metrics.
    metrics = ['ESTIMATED_EARNINGS', 'AD_REQUESTS', 'MATCHED_REQUESTS']
    
    # Set sort conditions.
    sort_conditions = {'dimension': 'DATE', 'order': 'DESCENDING'}
    
    # Set dimension filters.
    dimension_filters = {
        'dimension': 'COUNTRY',
        'matches_any': {
            'values': ['US', 'CA']
        }
    }
    
    # Create mediation report specifications.
    report_spec = {
        'date_range': date_range,
        'dimensions': dimensions,
        'metrics': metrics,
        'sort_conditions': [sort_conditions],
        'dimension_filters': [dimension_filters]
    }
    
    # Create mediation report request.
    request = {'report_spec': report_spec}
    
    # Execute mediation report request.
    response = service.accounts().mediationReport().generate(
        parent='accounts/{}'.format(publisher_id), body=request).execute()
    
    # Display responses.
    for report_line in response:
      print(report_line)
    print()
    
  6. 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'])
          if 'displayName' in linked_app_info:
            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']
    
  7. 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 ID: ' + ad_unit['appId'])
        if 'adTypes' in ad_unit:
          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 \
            https://www.googleapis.com/auth/admob.readonly
    
  2. Nhận thông tin tài khoản.

    Nhận thông tin tài khoản AdMob bằng cách thay thế pub-XXXXXXXXXXXXXXXX bằng mã nhà xuất bản của bạn. Xem instructions về cách tìm mã nhà xuất bản.

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

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

    {
     "account": [
       {
         "publisherId": "pub-XXXXXXXXXXXXXXXX",
         "name:": "accounts/pub-XXXXXXXXXXXXXXXX",
         "reportingTimeZone": "Europe/Paris",
         "currencyCode": "EUR"
       }
     ]
    }
    
  3. Tạo báo cáo mạng.

    Bạn có thể tạo báo cáo mạng bằng cách gọi phương thức networkReport:generate. Sử dụng publisherId nhận được trong bước Lấy thông tin tài khoản trong URI yêu cầu (ví dụ: v1/accounts/pub-XXXXXXXXXXXXXXXX/networkReport:generate).

    Sau đó, sử dụng lệnh sau để tạo báo cáo mạng:

    curl -X POST \
          https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/networkReport:generate \
          -H "Content-Type: application/json" \
          -H "$(oauth2l header --json path_to_credentials_json \
              https://www.googleapis.com/auth/admob.readonly)" \
          --data @- << EOF
    {
     "report_spec": {
       "date_range": {
         "start_date": {"year": 2020, "month": 4, "day": 1},
         "end_date": {"year": 2020, "month": 4, "day": 2}
       },
       "dimensions": ["DATE"],
       "metrics": ["CLICKS", "AD_REQUESTS", "IMPRESSIONS", "ESTIMATED_EARNINGS"],
       "dimension_filters": [{"dimension": "COUNTRY", "matches_any": {"values": ["US"]}}],
       "sort_conditions": [{"metric":"CLICKS", order: "DESCENDING"}],
       "localization_settings": {"currency_code": "USD", "language_code": "en-US"}
     }
    }
    EOF
    

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

    [{
     "header": {
       "dateRange": {
         "startDate": {"year": 2020, "month": 4, "day": 1},
         "endDate": {"year": 2020, "month": 4, "day": 2}
       }
     }
    },
    {
     "row": {
       "dimensionValues": {"DATE": {"value": "20200401"}},
       "metricValues": {
         "CLICKS": {"integerValue": "31"},
         "AD_REQUESTS": {"integerValue": "7409"},
         "IMPRESSIONS": {"integerValue": "3440"},
         "ESTIMATED_EARNINGS": {"microsValue": "6381903"}
       }
     }
    },
    {
     "row": {
       "dimensionValues": {"DATE": {"value": "20200402"}},
       "metricValues": {
         "CLICKS": {"integerValue": "30"},
         "AD_REQUESTS": {"integerValue": "8828"},
         "IMPRESSIONS": {"integerValue": "3724"},
         "ESTIMATED_EARNINGS": {"microsValue": "9010390"}
       }
     }
    },
    {
     "footer": {
       "matchingRowCount": "2"
     }
    }]
    
  4. Liệt kê ứng dụng.

    curl -X GET https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/apps \
           -H "Content-Type: application/json" \
           -H "$(oauth2l header --json path_to_credentials_json \
              https://www.googleapis.com/auth/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",
         }
       }
     ]
    }
    
  5. Liệt kê đơn vị quảng cáo.

    curl -X GET https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/adUnits \
           -H "Content-Type: application/json" \
           -H "$(oauth2l header --json path_to_credentials_json \
              https://www.googleapis.com/auth/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"],
       }
     ]
    }