클라이언트 라이브러리의 기본 사용법은 다음과 같습니다.
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에서 setter 메서드를 호출합니다.
자세한 내용은 구성 가이드를 참고하세요.
명시적 설정으로 GoogleAdsClient 객체를 구성하려면 OAuth2TokenBuilder 객체와 GoogleAdsClientBuilder 객체를 만들고 적절한 setter 메서드를 호출합니다.
// 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
);
}