इनवॉइस पाएं

Java

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.billing;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v17.enums.MonthOfYearEnum.MonthOfYear;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.Invoice;
import com.google.ads.googleads.v17.resources.Invoice.AccountBudgetSummary;
import com.google.ads.googleads.v17.services.InvoiceServiceClient;
import com.google.ads.googleads.v17.services.ListInvoicesResponse;
import com.google.ads.googleads.v17.utils.ResourceNames;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.ZonedDateTime;

/** Retrieves the invoices issued last month for a given billing setup. */
public class GetInvoices {

  private static class GetInvoicesParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.BILLING_SETUP_ID, required = true)
    private Long billingSetupId;
  }

  public static void main(String[] args) {
    GetInvoicesParams params = new GetInvoicesParams();

    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.billingSetupId = Long.parseLong("INSERT_BILLING_SETUP_ID_HERE");
    }

    GoogleAdsClient googleAdsClient = null;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      System.exit(1);
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      System.exit(1);
    }

    try {
      new GetInvoices().runExample(googleAdsClient, params.customerId, params.billingSetupId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  private void runExample(GoogleAdsClient googleAdsClient, Long customerId, Long billingSetupId) {
    try (InvoiceServiceClient invoiceServiceClient =
        googleAdsClient.getLatestVersion().createInvoiceServiceClient()) {
      ZonedDateTime oneMonthAgo = ZonedDateTime.now().minusMonths(1);

      // Issues the request.
      ListInvoicesResponse response =
          invoiceServiceClient.listInvoices(
              String.valueOf(customerId),
              ResourceNames.billingSetup(customerId, billingSetupId),
              String.valueOf(oneMonthAgo.getYear()),
              MonthOfYear.valueOf(oneMonthAgo.getMonth().toString()));

      // Iterates over all invoices retrieved and prints their information.
      for (Invoice invoice : response.getInvoicesList()) {
        System.out.printf(
            "- Found the invoice '%s':\n"
                + "  ID (also known as Invoice Number): '%s'\n"
                + "  Type: %s\n"
                + "  Billing setup ID: '%s'\n"
                + "  Payments account ID (also known as Billing Account Number): '%s'\n"
                + "  Payments profile ID (also known as Billing ID): '%s'\n"
                + "  Issue date (also known as Invoice Date): %s\n"
                + "  Due date: %s\n"
                + "  Currency code: %s\n"
                + "  Service date range (inclusive): from %s to %s\n"
                + "  Adjustments: subtotal '%.2f', tax '%.2f', total '%.2f'\n"
                + "  Regulatory costs: subtotal '%.2f', tax '%.2f', total '%.2f'\n"
                + "  Replaced invoices: '%s'\n"
                + "  Amounts: subtotal '%.2f', tax '%.2f', total '%.2f'\n"
                + "  Corrected invoice: '%s'\n"
                + "  PDF URL: '%s'\n"
                + "  Account budgets: ",
            invoice.getResourceName(),
            invoice.getId(),
            invoice.getType(),
            invoice.getBillingSetup(),
            invoice.getPaymentsAccountId(),
            invoice.getPaymentsProfileId(),
            invoice.getIssueDate(),
            invoice.getDueDate(),
            invoice.getCurrencyCode(),
            invoice.getServiceDateRange().getStartDate(),
            invoice.getServiceDateRange().getEndDate(),
            convertMicrosToCurrency(invoice.getAdjustmentsSubtotalAmountMicros()),
            convertMicrosToCurrency(invoice.getAdjustmentsTaxAmountMicros()),
            convertMicrosToCurrency(invoice.getAdjustmentsTotalAmountMicros()),
            convertMicrosToCurrency(invoice.getRegulatoryCostsSubtotalAmountMicros()),
            convertMicrosToCurrency(invoice.getRegulatoryCostsTaxAmountMicros()),
            convertMicrosToCurrency(invoice.getRegulatoryCostsTotalAmountMicros()),
            invoice.getReplacedInvoicesList(),
            convertMicrosToCurrency(invoice.getSubtotalAmountMicros()),
            convertMicrosToCurrency(invoice.getTaxAmountMicros()),
            convertMicrosToCurrency(invoice.getTotalAmountMicros()),
            invoice.getCorrectedInvoice(),
            invoice.getPdfUrl());
        for (AccountBudgetSummary accountBudgetSummary : invoice.getAccountBudgetSummariesList()) {
          System.out.printf(
              "  - Account budget '%s':\n"
                  + "      Name (also known as Account Budget): '%s'\n"
                  + "      Customer (also known as Account ID): '%s'\n"
                  + "      Customer descriptive name (also known as Account): '%s'\n"
                  + "      Purchase order number (also known as Purchase Order): '%s'\n"
                  + "      Billing activity date range (inclusive): from %s to %s\n"
                  + "      Amounts: subtotal '%.2f', tax '%.2f', total '%.2f'\n",
              accountBudgetSummary.getAccountBudget(),
              accountBudgetSummary.getAccountBudgetName(),
              accountBudgetSummary.getCustomer(),
              accountBudgetSummary.getCustomerDescriptiveName(),
              accountBudgetSummary.getPurchaseOrderNumber(),
              accountBudgetSummary.getBillableActivityDateRange().getStartDate(),
              accountBudgetSummary.getBillableActivityDateRange().getEndDate(),
              convertMicrosToCurrency(accountBudgetSummary.getSubtotalAmountMicros()),
              convertMicrosToCurrency(accountBudgetSummary.getTaxAmountMicros()),
              convertMicrosToCurrency(accountBudgetSummary.getTotalAmountMicros()));
        }
      }
    }
  }

  /**
   * Provides a utility method which converts API micros into an amount of currency. For example, if
   * the API returns 1_250_000 micros, and the account currency is USD, then this represents $1.25.
   */
  private static double convertMicrosToCurrency(long amountMicros) {
    return amountMicros / 1_000_000.0;
  }
}

      

C#

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V17.Enums.MonthOfYearEnum.Types;
using static Google.Ads.GoogleAds.V17.Resources.Invoice.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// This code example retrieves the invoices issued last month for a given billing setup.
    /// </summary>
    public class GetInvoices : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="GetInvoices"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// The billing setup ID for which to request invoices.
            /// </summary>
            [Option("billingSetupId", Required = true, HelpText =
                "The billing setup ID for which to request invoices.")]
            public long BillingSetupId { get; set; }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = ExampleUtilities.ParseCommandLine<Options>(args);

            GetInvoices codeExample = new GetInvoices();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.BillingSetupId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example retrieves the invoices issued last month for a given billing setup.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="billingSetupId">The billing setup ID for which to request invoices.</param>
        public void Run(GoogleAdsClient client, long customerId, long billingSetupId)
        {
            // Get the InvoiceService client.
            InvoiceServiceClient invoiceServiceClient =
                client.GetService(Services.V17.InvoiceService);

            // Get the last month before today.
            DateTime lastMonthDateTime = DateTime.Today.AddMonths(-1);

            // Convert the desired month to its representation in the MonthOfYear enum.
            MonthOfYear lastMonth =
                (MonthOfYear) Enum.Parse(typeof(MonthOfYear), lastMonthDateTime.ToString("MMMM"));

            ListInvoicesResponse response = invoiceServiceClient.ListInvoices(customerId.ToString(),
                ResourceNames.BillingSetup(customerId, billingSetupId),
                // Year must be 2019 or later.
                lastMonthDateTime.Year.ToString("yyyy"),
                lastMonth);

            // information.
            foreach (Invoice invoice in response.Invoices)
            {
                Console.WriteLine(
                    "- Found the invoice '{0}':\n" +
                    "  ID (also known as Invoice Number): '{1}'\n" +
                    "  Type: {2}\n" +
                    "  Billing setup ID: '{3}'\n" +
                    "  Payments account ID (also known as Billing Account Number): '{4}'\n" +
                    "  Payments profile ID (also known as Billing ID): '{5}'\n" +
                    "  Issue date (also known as Invoice Date): {6}\n" +
                    "  Due date: {7}\n" +
                    "  Currency code: {8}\n" +
                    "  Service date range (inclusive): from {9} to {10}\n" +
                    "  Adjustments: subtotal '{11}', tax '{12}', total '{13}'\n" +
                    "  Regulatory costs: subtotal '{14}', tax '{15}', total '{16}'\n" +
                    "  Replaced invoices: '{17}'\n" +
                    "  Amounts: subtotal '{18}', tax '{19}', total '{20}'\n" +
                    "  Corrected invoice: '{21}'\n" +
                    "  PDF URL: '{22}'\n" +
                    "  Account budgets:\n",
                    invoice.ResourceName,
                    invoice.Id,
                    invoice.Type.ToString(),
                    invoice.BillingSetup,
                    invoice.PaymentsAccountId,
                    invoice.PaymentsProfileId,
                    invoice.IssueDate,
                    invoice.DueDate,
                    invoice.CurrencyCode,
                    invoice.ServiceDateRange.StartDate,
                    invoice.ServiceDateRange.EndDate,
                    FormatMicros(invoice.AdjustmentsSubtotalAmountMicros),
                    FormatMicros(invoice.AdjustmentsTaxAmountMicros),
                    FormatMicros(invoice.AdjustmentsTotalAmountMicros),
                    FormatMicros(invoice.RegulatoryCostsSubtotalAmountMicros),
                    FormatMicros(invoice.RegulatoryCostsTaxAmountMicros),
                    FormatMicros(invoice.RegulatoryCostsTotalAmountMicros),
                    invoice.ReplacedInvoices.Count > 0
                        ? string.Join("', '", invoice.ReplacedInvoices)
                        : "none",
                    FormatMicros(invoice.SubtotalAmountMicros),
                    FormatMicros(invoice.TaxAmountMicros),
                    FormatMicros(invoice.TotalAmountMicros),
                    string.IsNullOrEmpty(invoice.CorrectedInvoice)
                        ? invoice.CorrectedInvoice
                        : "none",
                    invoice.PdfUrl);
                foreach (AccountBudgetSummary accountBudgetSummary in
                    invoice.AccountBudgetSummaries)
                {
                    Console.WriteLine(
                        "\t- Account budget '{0}':\n" +
                        "\t  Name (also known as Account Budget): '{1}'\n" +
                        "\t  Customer (also known as Account ID): '{2}'\n" +
                        "\t  Customer descriptive name (also known as Account): '{3}'\n" +
                        "\t  Purchase order number (also known as Purchase Order): '{4}'\n" +
                        "\t  Billing activity date range (inclusive): from {5} to {6}\n" +
                        "\t  Amounts: subtotal '{7}', tax '{8}', total '{9}'\n",
                        accountBudgetSummary.AccountBudget,
                        accountBudgetSummary.AccountBudgetName ?? "none",
                        accountBudgetSummary.Customer,
                        accountBudgetSummary.CustomerDescriptiveName ?? "none",
                        accountBudgetSummary.PurchaseOrderNumber ?? "none",
                        accountBudgetSummary.BillableActivityDateRange.StartDate,
                        accountBudgetSummary.BillableActivityDateRange.EndDate,
                        FormatMicros(accountBudgetSummary.SubtotalAmountMicros),
                        FormatMicros(accountBudgetSummary.TaxAmountMicros),
                        FormatMicros(accountBudgetSummary.TotalAmountMicros));
                }
            }
        }

        /// <summary>
        /// Format an amount in micros to a more readable, currency-like form.
        /// </summary>
        /// <param name="amountMicros">The amount in micros.</param>
        /// <returns>String representation of the original amount in "X.YY" form.</returns>
        private string FormatMicros(long amountMicros)
        {
            return (amountMicros / 1000000.0).ToString("0.##");
        }
    }
}

      

PHP

<?php

/**
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\Billing;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Enums\InvoiceTypeEnum\InvoiceType;
use Google\Ads\GoogleAds\V17\Enums\MonthOfYearEnum\MonthOfYear;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\Invoice;
use Google\Ads\GoogleAds\V17\Resources\Invoice\AccountBudgetSummary;
use Google\Ads\GoogleAds\V17\Services\ListInvoicesRequest;
use Google\ApiCore\ApiException;

/**
 * This code example retrieves the invoices issued last month for a given billing setup.
 */
class GetInvoices
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const BILLING_SETUP_ID = 'INSERT_BILLING_SETUP_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::BILLING_SETUP_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::BILLING_SETUP_ID] ?: self::BILLING_SETUP_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $billingSetupId the billing setup ID to filter the invoices on
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $billingSetupId
    ) {
        // Gets the date one month before now.
        $lastMonth = strtotime('-1 month');

        // Issues the request.
        $response = $googleAdsClient->getInvoiceServiceClient()->listInvoices(
            ListInvoicesRequest::build(
                $customerId,
                ResourceNames::forBillingSetup($customerId, $billingSetupId),
                // The year needs to be 2019 or later.
                date('Y', $lastMonth),
                MonthOfYear::value(strtoupper(date('F', $lastMonth)))
            )
        );

        // Iterates over all invoices retrieved and prints their information.
        foreach ($response->getInvoices() as $invoice) {
            /** @var Invoice $invoice */
            printf(
                "- Found the invoice '%s':" . PHP_EOL .
                "  ID (also known as Invoice Number): '%s'" . PHP_EOL .
                "  Type: %s" . PHP_EOL .
                "  Billing setup ID: '%s'" . PHP_EOL .
                "  Payments account ID (also known as Billing Account Number): '%s'" . PHP_EOL .
                "  Payments profile ID (also known as Billing ID): '%s'" . PHP_EOL .
                "  Issue date (also known as Invoice Date): %s" . PHP_EOL .
                "  Due date: %s" . PHP_EOL .
                "  Currency code: %s" . PHP_EOL .
                "  Service date range (inclusive): from %s to %s" . PHP_EOL .
                "  Adjustments: subtotal '%.2f', tax '%.2f', total '%.2f'" . PHP_EOL .
                "  Regulatory costs: subtotal '%.2f', tax '%.2f', total '%.2f'" . PHP_EOL .
                "  Replaced invoices: '%s'" . PHP_EOL .
                "  Amounts: subtotal '%.2f', tax '%.2f', total '%.2f'" . PHP_EOL .
                "  Corrected invoice: '%s'" . PHP_EOL .
                "  PDF URL: '%s'" . PHP_EOL .
                "  Account budgets:" . PHP_EOL,
                $invoice->getResourceName(),
                $invoice->getId(),
                InvoiceType::name($invoice->getType()),
                $invoice->getBillingSetup(),
                $invoice->getPaymentsAccountId(),
                $invoice->getPaymentsProfileId(),
                $invoice->getIssueDate(),
                $invoice->getDueDate(),
                $invoice->getCurrencyCode(),
                $invoice->getServiceDateRange()->getStartDate(),
                $invoice->getServiceDateRange()->getEndDate(),
                Helper::microToBase($invoice->getAdjustmentsSubtotalAmountMicros()),
                Helper::microToBase($invoice->getAdjustmentsTaxAmountMicros()),
                Helper::microToBase($invoice->getAdjustmentsTotalAmountMicros()),
                Helper::microToBase($invoice->getRegulatoryCostsSubtotalAmountMicros()),
                Helper::microToBase($invoice->getRegulatoryCostsTaxAmountMicros()),
                Helper::microToBase($invoice->getRegulatoryCostsTotalAmountMicros()),
                $invoice->getReplacedInvoices()
                    ? implode(
                        "', '",
                        iterator_to_array($invoice->getReplacedInvoices()->getIterator())
                    ) : 'none',
                Helper::microToBase($invoice->getSubtotalAmountMicros()),
                Helper::microToBase($invoice->getTaxAmountMicros()),
                Helper::microToBase($invoice->getTotalAmountMicros()),
                $invoice->getCorrectedInvoice() ?: 'none',
                $invoice->getPdfUrl()
            );
            foreach ($invoice->getAccountBudgetSummaries() as $accountBudgetSummary) {
                /** @var AccountBudgetSummary $accountBudgetSummary */
                printf(
                    "  - Account budget '%s':" . PHP_EOL .
                    "      Name (also known as Account Budget): '%s'" . PHP_EOL .
                    "      Customer (also known as Account ID): '%s'" . PHP_EOL .
                    "      Customer descriptive name (also known as Account): '%s'" . PHP_EOL .
                    "      Purchase order number (also known as Purchase Order): '%s'" . PHP_EOL .
                    "      Billing activity date range (inclusive): from %s to %s" . PHP_EOL .
                    "      Amounts: subtotal '%.2f', tax '%.2f', total '%.2f'" . PHP_EOL,
                    $accountBudgetSummary->getAccountBudget(),
                    $accountBudgetSummary->getAccountBudgetName() ?: 'none',
                    $accountBudgetSummary->getCustomer(),
                    $accountBudgetSummary->getCustomerDescriptiveName() ?: 'none',
                    $accountBudgetSummary->getPurchaseOrderNumber() ?: 'none',
                    $accountBudgetSummary->getBillableActivityDateRange()->getStartDate(),
                    $accountBudgetSummary->getBillableActivityDateRange()->getEndDate(),
                    Helper::microToBase($accountBudgetSummary->getSubtotalAmountMicros()),
                    Helper::microToBase($accountBudgetSummary->getTaxAmountMicros()),
                    Helper::microToBase($accountBudgetSummary->getTotalAmountMicros())
                );
            }
        }
    }
}

GetInvoices::main();

      

Python

#!/usr/bin/env python
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Retrieves the invoices issued last month for a given billing setup."""


import argparse
from datetime import date, timedelta
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


def main(client, customer_id, billing_setup_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        billing_setup_id: a billing setup ID.
    """

    # The last day of last month.
    last_month = date.today().replace(day=1) - timedelta(days=1)
    # Issues a request to list invoices.
    response = client.get_service("InvoiceService").list_invoices(
        customer_id=customer_id,
        billing_setup=client.get_service("GoogleAdsService").billing_setup_path(
            customer_id, billing_setup_id
        ),
        # The year needs to be 2019 or later, per the docs:
        # https://developers.google.com/google-ads/api/docs/billing/invoice?hl=en#retrieving_invoices
        issue_year=str(last_month.year),
        issue_month=last_month.strftime("%B").upper(),
    )

    for invoice in response.invoices:
        print(
            f"""
- Found the invoice {invoice.resource_name}
    ID (also known as Invoice Number): '{invoice.id}'
    Type: {invoice.type_}
    Billing setup ID: '{invoice.billing_setup}'
    Payments account ID (also known as Billing Account Number): '{invoice.payments_account_id}'
    Payments profile ID (also known as Billing ID): '{invoice.payments_profile_id}'
    Issue date (also known as Invoice Date): {invoice.issue_date}
    Due date: {invoice.due_date}
    Currency code: {invoice.currency_code}
    Service date range (inclusive): from {invoice.service_date_range.start_date} to {invoice.service_date_range.end_date}
    Adjustments:
        subtotal {_micros_to_currency(invoice.adjustments_subtotal_amount_micros)}
        tax {_micros_to_currency(invoice.adjustments_tax_amount_micros)}
        total {_micros_to_currency(invoice.adjustments_total_amount_micros)}
    Regulatory costs:
        subtotal {_micros_to_currency(invoice.regulatory_costs_subtotal_amount_micros)}
        tax {_micros_to_currency(invoice.regulatory_costs_tax_amount_micros)}
        total {_micros_to_currency(invoice.regulatory_costs_total_amount_micros)}
    Replaced invoices: {invoice.replaced_invoices.join(", ") if invoice.replaced_invoices else "none"}
    Amounts:
        subtotal {_micros_to_currency(invoice.subtotal_amount_micros)}
        tax {_micros_to_currency(invoice.tax_amount_micros)}
        total {_micros_to_currency(invoice.total_amount_micros)}
    Corrected invoice: {invoice.corrected_invoice or "none"}
    PDF URL: {invoice.pdf_url}
    Account budgets:
    """
        )
        for account_budget_summary in invoice.account_budget_summaries:
            print(
                f"""
                  - Account budget '{account_budget_summary.account_budget}':
                      Name (also known as Account Budget): '{account_budget_summary.account_budget_name}'
                      Customer (also known as Account ID): '{account_budget_summary.customer}'
                      Customer descriptive name (also known as Account): '{account_budget_summary.customer_descriptive_name}'
                      Purchase order number (also known as Purchase Order): '{account_budget_summary.purchase_order_number}'
                      Billing activity date range (inclusive):
                        from #{account_budget_summary.billable_activity_date_range.start_date}
                        to #{account_budget_summary.billable_activity_date_range.end_date}
                      Amounts:
                        subtotal '{_micros_to_currency(account_budget_summary.subtotal_amount_micros)}'
                        tax '{_micros_to_currency(account_budget_summary.tax_amount_micros)}'
                        total '{_micros_to_currency(account_budget_summary.total_amount_micros)}'
                """
            )


def micros_to_currency(micros):
    return micros / 1000000.0 if micros is not None else None


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Retrieves the invoices issued last month for a given billing setup."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    parser.add_argument(
        "-b",
        "--billing_setup_id",
        type=str,
        required=True,
        help="The billing setup ID.",
    )
    args = parser.parse_args()

    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v17")

    try:
        main(googleads_client, args.customer_id, args.billing_setup_id)
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This code example retrieves the invoices issued last month for a given
# billing setup.

require 'optparse'
require 'google/ads/google_ads'

def get_invoices(customer_id, billing_setup_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  # Gets the date one month before now.
  last_month = Date.today.prev_month

  # Issues a request to list invoices.
  response = client.service.invoice.list_invoices(
    customer_id: customer_id,
    billing_setup: client.path.billing_setup(customer_id, billing_setup_id),
    # The year needs to be 2019 or later.
    issue_year: last_month.year.to_s,
    # '%^B' option returns the uppercased full month name (e.g. 'JANUARY').
    issue_month: last_month.strftime("%^B").to_sym,
  )

  # Iterates over all invoices retrieved and prints their information.
  response.invoices.each do |invoice|
    puts <<~OUTPUT
    - Found the invoice '#{invoice.resource_name}'
      ID (also known as Invoice Number): '#{invoice.id}'
      Type: #{invoice.type}
      Billing Setup ID: '#{invoice.billing_setup}'
      Payments account ID (also known as Billing Account Number): '#{invoice.payments_account_id}'
      Payments profile ID (also known as Billing ID): '#{invoice.payments_profile_id}'
      Issue date (also known as Invoice Date): #{invoice.issue_date}
      Due date: #{invoice.due_date}
      Currency code: #{invoice.currency_code}
      Service date range (inclusive):
        from #{invoice.service_date_range.start_date}
        to #{invoice.service_date_range.end_date}
      Adjustments:
        subtotal '#{micro_to_base(invoice.adjustments_subtotal_amount_micros)}'
        tax '#{micro_to_base(invoice.adjustments_tax_amount_micros)}'
        total '#{micro_to_base(invoice.adjustments_total_amount_micros)}'
      Regulatory costs:
        subtotal '#{micro_to_base(invoice.regulatory_costs_subtotal_amount_micros)}'
        tax '#{micro_to_base(invoice.regulatory_costs_tax_amount_micros)}'
        total '#{micro_to_base(invoice.regulatory_costs_total_amount_micros)}'
      Replaced invoices: '#{invoice.replaced_invoices ? invoice.replaced_invoices.join(", ") : 'none'}'
      Amounts:
        subtotal '#{micro_to_base(invoice.subtotal_amount_micros)}'
        tax '#{micro_to_base(invoice.tax_amount_micros)}'
        total '#{micro_to_base(invoice.total_amount_micros)}'
      Corrected invoice: '#{invoice.corrected_invoices ? invoice.corrected_invoices : 'none'}'
      PDF URL: '#{invoice.pdf_url}'
      Account budgets:
    OUTPUT
    invoice.account_budget_summaries.each do |account_budget_summary|
      puts <<~OUTPUT
      \tAccount budget '#{account_budget_summary.account_budget}':
      \t  Name (also known as Account Budget): '#{account_budget_summary.account_budget_name}'
      \t  Customer (also known as Account ID): '#{account_budget_summary.customer}'
      \t  Customer descriptive name (also known as Account): '#{account_budget_summary.customer_descriptive_name}'
      \t  Purchase order number (also known as Purchase Order): '#{account_budget_summary.purchase_order_number}'
      \t  Billing activity date range (inclusive):
      \t    from #{account_budget_summary.billable_activity_date_range.start_date}
      \t    to #{account_budget_summary.billable_activity_date_range.end_date}
      \t  Amounts:
      \t    subtotal '#{micro_to_base(account_budget_summary.subtotal_amount_micros)}'
      \t    tax '#{micro_to_base(account_budget_summary.tax_amount_micros)}'
      \t    total '#{micro_to_base(account_budget_summary.total_amount_micros)}'
      OUTPUT
    end
  end
end

# Converts an amount from the micro unit to the base unit.
def micro_to_base(amount)
  amount ? (amount / 1000000.0) : 0.0
end

if __FILE__ == $0
  PAGE_SIZE = 1000

  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:billing_setup_id] = 'INSERT_BILLING_SETUP_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-B', '--billing-setup-id BILLING-SETUP-ID', String, 'Customer ID') do |v|
      options[:billing_setup_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    get_invoices(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:billing_setup_id),
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

      

Perl

#!/usr/bin/perl -w
#
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example retrieves the invoices issued last month for a given billing
# setup.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd   qw(abs_path);
use POSIX qw(strftime mktime);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id      = "INSERT_CUSTOMER_ID_HERE";
my $billing_setup_id = "INSERT_BILLING_SETUP_ID_HERE";

sub get_invoices {
  my ($api_client, $customer_id, $billing_setup_id) = @_;

  # Get the date one month before now.
  my @current_month = localtime(time);
  $current_month[4] -= 1;
  my @last_month = localtime(mktime(@current_month));

  # Issue the request.
  my $response = $api_client->InvoiceService()->list({
      customerId   => $customer_id,
      billingSetup =>
        Google::Ads::GoogleAds::V17::Utils::ResourceNames::billing_setup(
        ($customer_id, $billing_setup_id)
        ),
      # The year needs to be 2019 or later.
      issueYear  => strftime("%Y", @last_month),
      issueMonth => uc(strftime("%B", @last_month))});

  # Iterate over all invoices retrieved and print their information.
  foreach my $invoice (@$response) {
    printf "- Found the invoice '%s':\n" .
      "  ID (also known as Invoice Number): '%s'\n" .
      "  Type: %s\n" .
      "  Billing setup ID: '%s'\n" .
      "  Payments account ID (also known as Billing Account Number): '%s'\n" .
      "  Payments profile ID (also known as Billing ID): '%s'\n" .
      "  Issue date (also known as Invoice Date): %s\n" .
      "  Due date: %s\n" .
      "  Currency code: %s\n" .
      "  Service date range (inclusive): from %s to %s\n" .
      "  Adjustments: subtotal '%.2f', tax '%.2f', total '%.2f'\n" .
      "  Regulatory costs: subtotal '%.2f', tax '%.2f', total '%.2f'\n" .
      "  Replaced invoices: '%s'\n" .
      "  Amounts: subtotal '%.2f', tax '%.2f', total '%.2f'\n" .
      "  Corrected invoice: '%s'\n" .
      "  PDF URL: '%s'\n" .
      "  Account budgets:\n",
      $invoice->{resourceName},
      $invoice->{id},
      $invoice->{type},
      $invoice->{billingSetup},
      $invoice->{paymentsAccountId},
      $invoice->{paymentsProfileId},
      $invoice->{issueDate},
      $invoice->{dueDate},
      $invoice->{currencyCode},
      $invoice->{serviceDateRange}{startDate},
      $invoice->{serviceDateRange}{endDate},
      micro_to_base($invoice->{adjustmentsSubtotalAmountMicros}),
      micro_to_base($invoice->{adjustmentsTaxAmountMicros}),
      micro_to_base($invoice->{adjustmentsTotalAmountMicros}),
      micro_to_base($invoice->{regulatoryCostsSubtotalAmountMicros}),
      micro_to_base($invoice->{regulatoryCostsTaxAmountMicros}),
      micro_to_base($invoice->{regulatoryCostsTotalAmountMicros}),
      $invoice->{replacedInvoices}
      ? join(',', @{$invoice->{replacedInvoices}})
      : "none",
      micro_to_base($invoice->{subtotalAmountMicros}),
      micro_to_base($invoice->{taxAmountMicros}),
      micro_to_base($invoice->{totalAmountMicros}),
      $invoice->{correctedInvoice} ? $invoice->{correctedInvoice} : "none",
      $invoice->{pdfUrl};

    foreach my $account_budget_summary (@{$invoice->{accountBudgetSummaries}}) {
      printf "  - Account budget '%s':\n" .
        "      Name (also known as Account Budget): '%s'\n" .
        "      Customer (also known as Account ID): '%s'\n" .
        "      Customer descriptive name (also known as Account): '%s'\n" .
        "      Purchase order number (also known as Purchase Order): '%s'\n" .
        "      Billing activity date range (inclusive): from %s to %s\n" .
        "      Amounts: subtotal '%.2f', tax '%.2f', total '%.2f'\n",
        $account_budget_summary->{accountBudget},
        $account_budget_summary->{accountBudgetName}
        ? $account_budget_summary->{accountBudgetName}
        : "none",
        $account_budget_summary->{customer},
        $account_budget_summary->{customerDescriptiveName}
        ? $account_budget_summary->{customerDescriptiveName}
        : "none",
        $account_budget_summary->{purchaseOrderNumber}
        ? $account_budget_summary->{purchaseOrderNumber}
        : "none",
        $account_budget_summary->{billableActivityDateRange}{startDate},
        $account_budget_summary->{billableActivityDateRange}{endDate},
        $account_budget_summary->{subtotalAmountMicros},
        $account_budget_summary->{taxAmountMicros},
        $account_budget_summary->{totalAmountMicros};
    }
  }

  return 1;
}

# Converts an amount from the micro unit to the base unit.
sub micro_to_base() {
  my $amount = shift;
  return $amount ? $amount / 1000000.0 : 0.0;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"      => \$customer_id,
  "billing_setup_id=i" => \$billing_setup_id
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($customer_id, $billing_setup_id);

# Call the example.
get_invoices($api_client, $customer_id =~ s/-//gr, $billing_setup_id);

=pod

=head1 NAME

get_invoices

=head1 DESCRIPTION

This code example retrieves the invoices issued last month for a given billing setup.

=head1 SYNOPSIS

get_invoices.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -billing_setup_id           The billing setup ID to filter the invoices on.

=cut