設定

Google Ads API 用戶端程式庫提供多項設定,可供您自訂程式庫行為。

在執行階段設定程式庫

設定用戶端程式庫的偏好方式是在執行階段初始化 GoogleAdsConfig 物件:

GoogleAdsConfig config = new GoogleAdsConfig()
{
    OAuth2Mode = OAuth2Flow.APPLICATION,
    OAuth2ClientId = "INSERT_CLIENT_ID.apps.googleusercontent.com",
    OAuth2ClientSecret = "INSERT_CLIENT_SECRET",
    OAuth2RefreshToken = "INSERT_REFRESH_TOKEN"
};

GoogleAdsClient client = new GoogleAdsClient(config);

其他設定選項

這個程式庫也提供其他選項,可載入設定。如要啟用這些功能,請在專案中將 NuGet 參照新增至 Google.Ads.GoogleAds.Extensions 套件。

如果您使用其中一個選項,系統不會自動擷取設定,您必須明確載入設定,如下列章節所示。從外部檔案或串流載入設定時,請務必處理檔案 I/O 例外狀況 (例如 FileNotFoundException 或 UnauthorizedAccessException)。

使用 App.config

所有 Google Ads API 專屬設定都儲存在 App.config 檔案的 GoogleAdsApi 節點中。一般設定 App.config 如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="GoogleAdsApi"
             type="System.Configuration.DictionarySectionHandler" />
  </configSections>
  <GoogleAdsApi>
    <!-- Set the service timeout in milliseconds. -->
    <add key="Timeout" value="2000" />

    <!-- Proxy settings for library. -->
    <add key="ProxyServer" value="http://localhost:8888" />
    <add key="ProxyUser" value="" />
    <add key="ProxyPassword" value="" />
    <add key="ProxyDomain" value="" />

    <!-- OAuth2 settings -->
    <add key="OAuth2Mode" value="APPLICATION" />
    <add key="OAuth2ClientId"
         value="INSERT_CLIENT_ID.apps.googleusercontent.com" />
    <add key="OAuth2ClientSecret" value="INSERT_CLIENT_SECRET" />
    <add key="OAuth2RefreshToken" value="INSERT_REFRESH_TOKEN" />
  </GoogleAdsApi>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
</configuration>

如要從 App.config 檔案載入設定,請對 GoogleAdsConfig 物件呼叫 LoadFromDefaultAppConfigSection 方法:

GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromDefaultAppConfigSection();
GoogleAdsClient client = new GoogleAdsClient(config);

指定個別的 App.config 檔案

如果不想讓 App.config 雜亂無章,可以使用 configSource 屬性,將特定程式庫的設定移至專屬設定檔:

  1. 在 App.config 中指定 configSource。修改 App.config,參照外部設定檔:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="GoogleAdsApi"
                 type="System.Configuration.DictionarySectionHandler" />
      </configSections>
      <GoogleAdsApi configSource="GoogleAdsApi.config" />
    </configuration>
    
  2. 指定設定檔的內容。建立另一個設定檔,名稱與 configSource 中指定的名稱相同 (GoogleAdsApi.config),並將 GoogleAdsApi 設定節點從 App.config 移至這個檔案:

    <?xml version="1.0" encoding="utf-8" ?>
    <GoogleAdsApi>
      <!-- More settings. -->
    </GoogleAdsApi>
    
  3. 更新 .csproj 中的建構規則。在專案中加入新的設定檔,並將其「複製到輸出目錄」屬性設為「一律複製」。重新建構並執行專案,讓應用程式從新的設定檔中擷取值。

使用自訂 JSON 檔案

您可以使用 IConfigurationRoot 例項設定用戶端程式庫。

建立 JSON 檔案

建立名為 GoogleAdsApi.json 的 JSON 檔案,結構與 App.config 檔案類似:

{
  "Timeout": "2000",
  "ProxyServer": "http://localhost:8888",
  "ProxyUser": "",
  "ProxyPassword": "",
  "ProxyDomain": "",
  "OAuth2Mode": "APPLICATION",
  "OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
  "OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
  "OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
}

載入設定

接著,將 JSON 檔案載入 IConfigurationRoot:

ConfigurationBuilder builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("GoogleAdsApi.json");
IConfigurationRoot configRoot = builder.Build();

GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromConfigurationRoot(configRoot);
GoogleAdsClient client = new GoogleAdsClient(config);

使用 settings.json

這個程序與使用自訂 JSON 檔案類似,但金鑰應位於名為 GoogleAdsApi 的區段內:

{
  "GoogleAdsApi": {
    "OAuth2Mode": "APPLICATION",
    "OAuth2ClientId": "INSERT_CLIENT_ID.apps.googleusercontent.com",
    "OAuth2ClientSecret": "INSERT_CLIENT_SECRET",
    "OAuth2RefreshToken": "INSERT_REFRESH_TOKEN"
  }
}

接著,從應用程式的 GoogleAdsApi 執行個體 (例如由 ASP.NET Core 插入或以 IConfiguration 建構) 擷取 ConfigurationBuilder 區段:

IConfigurationSection section = configuration.GetSection("GoogleAdsApi");
GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromConfigurationSection(section);
GoogleAdsClient client = new GoogleAdsClient(config);

或者,您也可以使用 config.LoadFromSettingsJson(filePath, "GoogleAdsApi"),直接從路徑載入 settings.json 檔案,或使用 config.TryLoadFromEnvironmentFilePath,從 GOOGLE_ADS_CONFIGURATION_FILE_PATH 環境變數 (EnvironmentVariableNames.CONFIG_FILE_PATH) 載入檔案。

使用環境變數

您也可以使用環境變數初始化 GoogleAdsClient:

GoogleAdsConfig config = new GoogleAdsConfig();
config.LoadFromEnvironmentVariables();
GoogleAdsClient client = new GoogleAdsClient(config);

請參閱支援環境變數的完整清單。

使用一般串流

您也可以從一般串流 (包括加密串流) 載入設定或部分設定:

GoogleAdsConfig config = new GoogleAdsConfig()
{
    // Set some configuration properties in code.
    OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
};

// Load your encrypted data from a file and dispose of the streams properly.
using (CryptoStream strm = GetEncryptedCredentialsStream())
using (StreamReader rdr = new StreamReader(strm))
{
    // Configure the OAuth credentials from the encrypted stream.
    config.LoadOAuth2SecretsFromStream(rdr);
}

GoogleAdsClient client = new GoogleAdsClient(config);

設定欄位

以下各節列出 Google Ads .NET 程式庫支援的設定。

連線設定

  • Timeout:使用這個鍵以毫秒為單位設定服務逾時。預設值是根據 googleads_grpc_service_config.json 中的 method_config/timeout 設定而定。如需強制縮短 API 呼叫的最長時間限制,請設定較低的值。您可以將逾時時間設為 2 小時以上,但對於執行時間極長的要求,API 仍可能逾時並傳回 DEADLINE_EXCEEDED 錯誤。
  • ProxyServer:如果您使用 Proxy 連線至網際網路,請將此項設為 HTTP Proxy 伺服器網址。
  • ProxyUser:將此值設為向 Proxy 伺服器驗證時所需的使用者名稱。如果不需要使用者名稱,請將這個欄位留空。
  • ProxyPassword:如果為 ProxyUser 設定值,請將此項設為 ProxyUser 的密碼。
  • ProxyDomain:如果 Proxy 伺服器需要設定網域,請將此項設為 ProxyUser 的網域。
  • MaxReceiveMessageLengthInBytes:使用這項設定可增加用戶端程式庫可處理的 API 回應大小上限。預設值為 64 MB。
  • MaxMetadataSizeInBytes:使用這項設定,可增加用戶端程式庫可處理的 API 錯誤回應大小上限。預設值為 16 MB。

調整 MaxReceiveMessageLengthInBytes 和 MaxMetadataSizeInBytes 設定,修正特定 ResourceExhausted 錯誤。這些設定可解決以下形式的錯誤:

Status(StatusCode="ResourceExhausted",Detail="Received
message larger than max (423184132 versus 67108864)"

在這個範例中,錯誤是因為訊息大小 (423184132 bytes) 大於程式庫可處理的大小 (67108864 bytes)。請將 MaxReceiveMessageLengthInBytes 增加至 500000000,避免發生這項錯誤。請注意,這項錯誤也表示程式碼處理了相當大的回應物件 (例如大型 SearchGoogleAdsResponse)。這可能會對程式碼效能造成影響,因為 .NET 的大型物件堆積。如果這成為效能問題,您可能必須探索如何重組 API 呼叫,或重新設計應用程式的部分內容。

OAuth2 設定

使用 OAuth 2.0 授權對 Google Ads API 伺服器發出的呼叫時,請設定下列設定鍵:

  • AuthorizationMethod:設為 OAuth2。
  • OAuth2Mode:設為 APPLICATION 或 SERVICE_ACCOUNT。
  • OAuth2ClientId:將這個值設為 OAuth 2.0 用戶端 ID。
  • OAuth2ClientSecret:將這個值設為 OAuth 2.0 用戶端密鑰。
  • OAuth2Scope:如要授權多個 API 的 OAuth 2.0 權杖,請將這個值設為不同範圍。這項設定為選用項目。
  • UseApplicationDefaultCredentials:將這個值設為 true,即可使用應用程式預設憑證進行驗證 (支援 Google.Ads.GoogleAds v24.1.0 以上版本;config.LoadFromEnvironmentVariables() 會讀取未加前置字元的 USE_APPLICATION_DEFAULT_CREDENTIALS 環境變數)。
  • Credentials:(僅限執行階段,支援 v27.0.0 以上版本) 在執行階段將預先建構的 ICredential 或 GoogleCredential 例項直接注入 GoogleAdsConfig。

如果您使用 OAuth2Mode == APPLICATION,則需要設定下列額外的設定鍵:

  • OAuth2RefreshToken:如要重複使用 OAuth 2.0 權杖,請將這個值設為預先產生的 OAuth 2.0 更新權杖。這項設定為選用項目。
  • OAuth2RedirectUri:將這個值設為 OAuth 2.0 重新導向網址。這項設定為選用項目。

詳情請參閱下列指南:

如果您使用 OAuth2Mode == SERVICE_ACCOUNT,則必須設定下列額外設定金鑰:

  • OAuth2SecretsJsonPath:將這個值設為 OAuth 2.0 JSON 金鑰檔案的路徑。
  • OAuth2PrnEmail:使用 Google Workspace 網域範圍授權時,請將這個值設為您要模擬的帳戶電子郵件地址。這項設定為選用項目。

詳情請參閱 OAuth 服務帳戶流程指南。

交通運輸設定

  • UseGrpcCore:將這項設定設為 true,即可使用 Grpc.Core 程式庫做為基礎傳輸層。請參閱「使用 Grpc.Core 程式庫」。

Google Ads API 設定

下列設定適用於 Google Ads API:

  • DeveloperToken:v27.3.0 以上版本為選用項目 (GOOGLE_ADS_DEVELOPER_TOKEN)。開發人員權杖已於 2026 年 9 月 9 日停用;在 API 伺服器上,存取層級是由 Google Cloud 專案決定,與用戶端程式庫版本無關,且 API 伺服器會忽略 developer-token 標頭 (直到 Google Ads API 的未來主要版本拒絕為止)。如要從設定中省略或移除 DeveloperToken,請使用 Google.Ads.GoogleAds v27.3.0 以上版本,因為這些版本已移除本機用戶端 DeveloperToken 驗證 (舊版需要非空白的 DeveloperToken 才能進行本機驗證)。
  • LoginCustomerId:這是授權客戶的客戶 ID,用於要求中,不含連字號 (-)。
  • LinkedCustomerId:透過 Google Ads 使用者介面中的已連結帳戶授權時,只有在更新實體的資源時,才需要這個標頭 (Google Ads API 中的 AccountLink 資源)。將這個值設為資料提供者的客戶 ID,該資料提供者會更新指定客戶 ID 的資源。設定時請勿使用連字號 (-)。 進一步瞭解已連結帳戶。