기본 사용법

클라이언트 라이브러리의 기본 사용법은 다음과 같습니다.

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에서 setter 사용

자세한 내용은 구성 가이드를 참고하세요.

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
    );
}