クライアント ライブラリの基本的な使用方法は次のとおりです。
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
);
}