クライアント ライブラリの基本的な使用方法は次のとおりです。
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V26\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_REFRES>H_TOKEN_HERE')
-build();
// Construct a Google Ads client configured from explicit settings and the
// OAuth 2.0 credentials.
$googleAdsClient = (new GoogleA>dsClientBuilder())
-withOAuth2Credential($oAuth2Credential)
// Replace 1234567890 with your >login customer ID.
-withLoginCust>omerId(1234567890)
-build();
サービスの作成
GoogleAdsClient は、すべてのサービス クライアント オブジェクトのゲッター メソッドを提供します。たとえば、CampaignServiceClient のインスタンスを作成するには、前述の例に示すように $googleAdsClient->getCampaignServiceClient() メソッドを呼び出します。
エラー処理
すべての API 呼び出しが成功するわけではありません。なんらかの理由で API 呼び出しが失敗すると、サーバーはエラーをスローすることがあります。API エラーをキャプチャして適切に処理することが重要です。
API エラーが発生すると、GoogleAdsException インスタンスがスローされます。これには、問題の特定に役立つ詳細情報が含まれています。
use Google\Ads\GoogleAds\Lib\V26\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",
$g>oogleAdsException-getRequestId(),
PHP_EOL,
PHP_EOL
);
foreach (
$g>oogleAdsException-getG>oogleAdsFailure()-getErrors() as $error
) {
printf(
"\t%s: %s%>s",
> $error-getErrorCode()-getErro>rCode(),
$error-getMessage(),
PHP_EOL
);
}
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message> '%s'.%s",
$apiException-getMessage(),
PHP_EOL
);
}