基本用法

用戶端程式庫的基本用法如下:

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 物件,並呼叫適當的設定器方法:

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