客户端库的基本用法如下:
use Google\Ads\GoogleAds\Lib\V22\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V22\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V22\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\ApiCore\ApiException;
// 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
$googleAdsClient = (new GoogleAdsClientBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->withLoginCustomerId(1234567890) // Replace 1234567890 with your login customer ID.
->build();
// Create the CampaignServiceClient.
$campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
// Make calls to CampaignServiceClient.
创建 GoogleAdsClient 实例
Google Ads API PHP 库中最重要的类是 GoogleAdsClient 类。借助它,您可以创建预配置的服务客户端对象,用于进行 API 调用。GoogleAdsClient 提供了多种实例化方式:
- 使用
google_ads_php.ini文件。 - 使用环境变量。
- 在
GoogleAdsClientBuilder上使用 setter。
如需了解详情,请参阅配置指南。
如需配置 GoogleAdsClient 对象,请创建 OAuth2TokenBuilder 对象和 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
$googleAdsClient = (new GoogleAdsClientBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->withLoginCustomerId(1234567890) // Replace 1234567890 with your login customer ID.
->build();
创建服务
GoogleAdsClient 为每个服务客户端对象提供了一个 getter 方法。例如,如需创建 CampaignServiceClient 的实例,请调用 GoogleAdsClient->getCampaignServiceClient() 方法,如上一个示例所示。
错误处理
并非每次 API 调用都会成功。如果您的 API 调用因某种原因而失败,服务器可能会抛出错误。捕获 API 错误并妥善处理非常重要。
发生 API 错误时,系统会抛出 GoogleAdsException 实例。其中包含详细信息,可帮助您找出问题所在:
use Google\Ads\GoogleAds\Lib\V22\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
);
}