基本用法

客户端库的基本用法如下:

use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V25\GoogleAdsClientBuilder;

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

// Construct a Google Ads client configured from a properties file and the
// OAuth 2.0 credentials.
$googleAdsClient = (new GoogleAdsClientBuilder())
    ->fromFile()
    ->withOAuth2Credential($oAuth2Credential)
    // Replace 1234567890 with your login customer ID.
    ->withLoginCustomerId(1234567890)
    ->build();

// Create the CampaignServiceClient.
$campaignServiceClient = $googleAdsClient->getCampaignServiceClient();

// Make calls to CampaignServiceClient.

客户端和服务初始化

如需向 Google Ads API 发出请求,请先初始化一个客户端实例,然后使用该实例创建服务客户端。

创建 GoogleAdsClient 实例

Google Ads API PHP 库中最重要的类是 GoogleAdsClient 类。借助此库,您可以创建预配置的服务客户端对象,用于进行 API 调用。GoogleAdsClient 提供了多种配置和实例化方式:

  • 使用 google_ads_php.ini 文件。
  • 设置环境变量。
  • 对 GoogleAdsClientBuilder 调用 setter 方法。

如需了解详情,请参阅配置指南。

如需使用明确的设置来配置 GoogleAdsClient 对象,请创建 OAuth2TokenBuilder 对象和 GoogleAdsClientBuilder 对象,并调用相应的 setter 方法:

// Generate a refreshable OAuth 2.0 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
    ->withClientId('INSERT_CLIENT_ID_HERE')
    ->withClientSecret('INSERT_CLIENT_SECRET_HERE')
    ->withRefreshToken('INSERT_REFRESH_TOKEN_HERE')
    ->build();

// Construct a Google Ads client configured from explicit settings and the
// OAuth 2.0 credentials.
$googleAdsClient = (new GoogleAdsClientBuilder())
    ->withOAuth2Credential($oAuth2Credential)
    // Replace 1234567890 with your login customer ID.
    ->withLoginCustomerId(1234567890)
    ->build();

创建服务

GoogleAdsClient 为每个服务客户端对象提供了一个 getter 方法。例如,如需创建 CampaignServiceClient 的实例,请调用 $googleAdsClient->getCampaignServiceClient() 方法,如上例所示。

错误处理

并非每次 API 调用都会成功。如果您的 API 调用因某种原因而失败,服务器可能会抛出错误。捕获 API 错误并妥善处理非常重要。

当发生 API 错误时,系统会抛出 GoogleAdsException 实例。其中包含详细信息,可帮助您找出问题所在:

use Google\Ads\GoogleAds\Lib\V25\GoogleAdsException;
use Google\ApiCore\ApiException;

try {
    // Make your API call here.
} 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
    ) {
        printf(
            "\t%s: %s%s",
            $error->getErrorCode()->getErrorCode(),
            $error->getMessage(),
            PHP_EOL
        );
    }
} catch (ApiException $apiException) {
    printf(
        "ApiException was thrown with message '%s'.%s",
        $apiException->getMessage(),
        PHP_EOL
    );
}