用戶端程式庫的基本用法如下:
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上使用設定器。
詳情請參閱設定指南。
如要設定 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
);
}