クライアント ライブラリの基本的な使用方法は次のとおりです。
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でセッター メソッドを呼び出します。
詳細については、構成ガイドをご覧ください。
明示的な設定で GoogleAdsClient オブジェクトを構成するには、OAuth2TokenBuilder オブジェクトと GoogleAdsClientBuilder オブジェクトを作成し、適切なセッター メソッドを呼び出します。
// 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
);
}