本指南也會使用重新整理權杖,也就是使用者充分瞭解的工作流程 只要設定 Google Ads 帳戶的存取權,系統就能一次授權給您的應用程式 離線 API 呼叫帳戶,不需任何進一步的使用者操作。 您可以使用更新權杖建構離線工作流程,例如 Cron 工作 和互動式工作流程,例如網路或行動應用程式
擷取更新權杖
Google Ads API 採用 OAuth 2.0 授權機制,根據預設 2.0 驗證會發出存取權杖,而該權杖會在有限制時過期 讓應用程式從可以最快做出回應的位置 回應使用者要求如要自動更新存取權杖,請發出重新整理 權杖。
執行 oauth2l 工具:
oauth2l fetch --credentials credentials.json --scope adwords \ --output_format refresh_token
credentials.json
檔案來自先前 步驟。oauth2l
指令會在新的瀏覽器中開啟 Google 帳戶登入視窗 視窗中,系統會引導您完成 OAuth 2.0 驗證步驟。請務必透過您在 識別您的登入客戶 ID。
如果應用程式未經驗證,系統可能會顯示警告畫面。此時 您可以按一下 [顯示進階] 連結 「前往 PROJECT_NAME (未驗證)」選項。
驗證範圍後,請點選 [繼續] 按鈕。
瀏覽器中會顯示下列文字的提示:
Authorization code granted. Please close this tab.
oauth2l
指令會輸出下列 JSON 程式碼片段:{ "client_id": "******.apps.googleusercontent.com", "client_secret": "******", "token_uri": "https://oauth2.googleapis.com/token", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "refresh_token": "******", "type": "authorized_user" }
發出 API 呼叫
請選取所選用戶端,瞭解如何發出 API 呼叫:
Java
用戶端程式庫構件會發布至 Maven 中央 存放區新增 用戶端程式庫做為專案的依附元件,如下所示:
Maven 依附元件如下:
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>google-ads</artifactId>
<version>33.0.0</version>
</dependency>
Gradle 依附元件如下:
implementation 'com.google.api-ads:google-ads:33.0.0'
建立含有以下內容的檔案 ~/ads.properties
:
api.googleads.clientId=INSERT_CLIENT_ID_HERE
api.googleads.clientSecret=INSERT_CLIENT_SECRET_HERE
api.googleads.refreshToken=INSERT_REFRESH_TOKEN_HERE
api.googleads.developerToken=INSERT_DEVELOPER_TOKEN_HERE
api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE
建立 GoogleAdsClient
物件,如下所示:
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n",
fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
接著,請使用
GoogleAdsService.SearchStream
敬上
擷取帳戶中的廣告活動。本指南並未涵蓋
報表的詳細資料。
private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
String query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id";
// Constructs the SearchGoogleAdsStreamRequest.
SearchGoogleAdsStreamRequest request =
SearchGoogleAdsStreamRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setQuery(query)
.build();
// Creates and issues a search Google Ads stream request that will retrieve all campaigns.
ServerStream<SearchGoogleAdsStreamResponse> stream =
googleAdsServiceClient.searchStreamCallable().call(request);
// Iterates through and prints all of the results in the stream response.
for (SearchGoogleAdsStreamResponse response : stream) {
for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
System.out.printf(
"Campaign with ID %d and name '%s' was found.%n",
googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
}
}
}
}
C#
用戶端程式庫套件會發布至 Nuget.org
存放區請先新增
Google.Ads.GoogleAds
套件的 Nuget 參照。
dotnet add package Google.Ads.GoogleAds --version 18.1.0
使用相關設定建立 GoogleAdsConfig
物件,然後用來
建立 GoogleAdsClient
物件
GoogleAdsConfig config = new GoogleAdsConfig()
{
DeveloperToken = "******",
OAuth2Mode = "APPLICATION",
OAuth2ClientId = "******.apps.googleusercontent.com",
OAuth2ClientSecret = "******",
OAuth2RefreshToken = "******",
LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);
接著,請使用
GoogleAdsService.SearchStream
敬上
擷取帳戶中的廣告活動。本指南並未涵蓋
報表的詳細資料。
public void Run(GoogleAdsClient client, long customerId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V17.GoogleAdsService);
// Create a query that will retrieve all campaigns.
string query = @"SELECT
campaign.id,
campaign.name,
campaign.network_settings.target_content_network
FROM campaign
ORDER BY campaign.id";
try
{
// Issue a search request.
googleAdsService.SearchStream(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse resp)
{
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
}
}
);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
PHP
用戶端程式庫套件會發布至 Packagist。
存放區變更為
然後執行下列指令,以安裝
請前往應用程式的 vendor/
目錄,查看程式庫及其所有依附元件
新增至專案的根目錄
composer require googleads/google-ads-php:22.0.0
建立
google_ads_php.ini
敬上
檔案並修改,加入憑證。
[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
[OAUTH2]
clientId = "INSERT_OAUTH2_CLIENT_ID_HERE"
clientSecret = "INSERT_OAUTH2_CLIENT_SECRET_HERE"
refreshToken = "INSERT_OAUTH2_REFRESH_TOKEN_HERE"
建立 GoogleAdsClient
物件的執行個體。
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile('/path/to/google_ads_php.ini')
->build();
$googleAdsClient = (new GoogleAdsClientBuilder())
->fromFile('/path/to/google_ads_php.ini')
->withOAuth2Credential($oAuth2Credential)
->build();
接著,請使用
GoogleAdsService.SearchStream
敬上
擷取帳戶中的廣告活動。本指南並未涵蓋
報表的詳細資料。
public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves all campaigns.
$query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
// Issues a search stream request.
/** @var GoogleAdsServerStreamDecorator $stream */
$stream = $googleAdsServiceClient->searchStream(
SearchGoogleAdsStreamRequest::build($customerId, $query)
);
// Iterates over all rows in all messages and prints the requested field values for
// the campaign in each row.
foreach ($stream->iterateAllElements() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */
printf(
"Campaign with ID %d and name '%s' was found.%s",
$googleAdsRow->getCampaign()->getId(),
$googleAdsRow->getCampaign()->getName(),
PHP_EOL
);
}
}
Python
用戶端程式庫在 PyPI 上發布
可以透過 pip
指令安裝
如下所示:
python -m pip install google-ads==21.3.0
建立 google-ads.yaml
的副本
檔案並修改,加入憑證。
client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
建立 GoogleAdsClient
例項,方法是呼叫
GoogleAdsClient.load_from_storage
方法。將路徑傳遞到
在呼叫方法時,將 google-ads.yaml
做為字串:
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")
接著,請使用
GoogleAdsService.SearchStream
敬上
擷取帳戶中的廣告活動。本指南並未涵蓋
報表的詳細資料。
def main(client, customer_id):
ga_service = client.get_service("GoogleAdsService")
query = """
SELECT
campaign.id,
campaign.name
FROM campaign
ORDER BY campaign.id"""
# Issues a search request using streaming.
stream = ga_service.search_stream(customer_id=customer_id, query=query)
for batch in stream:
for row in batch.results:
print(
f"Campaign with ID {row.campaign.id} and name "
f'"{row.campaign.name}" was found.'
)
小茹
用戶端程式庫的 Ruby Gems 會發布到 Rubygems Gem 代管網站。建議做法 安裝是使用 bundler。在 Gemfile 中新增一行:
gem 'google-ads-googleads', '~> 30.0.0'
接著執行:
bundle install
建立
google_ads_config.rb
敬上
檔案並修改,加入憑證。
Google::Ads::GoogleAds::Config.new do |c|
c.client_id = 'INSERT_CLIENT_ID_HERE'
c.client_secret = 'INSERT_CLIENT_SECRET_HERE'
c.refresh_token = 'INSERT_REFRESH_TOKEN_HERE'
c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
end
將路徑傳遞至您保留此項目的位置,建立 GoogleAdsClient
例項
檔案。
client = Google::Ads::GoogleAds::GoogleAdsClient.new('path/to/google_ads_config.rb')
接著,請使用
GoogleAdsService.SearchStream
敬上
擷取帳戶中的廣告活動。本指南並未涵蓋
報表的詳細資料。
def get_campaigns(customer_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
responses = client.service.google_ads.search_stream(
customer_id: customer_id,
query: 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id',
)
responses.each do |response|
response.results.each do |row|
puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
end
end
end
Perl
程式庫的發布位置
CPAN。請先複製
位於您選擇的目錄中的 google-ads-perl
存放區。
git clone https://github.com/googleads/google-ads-perl.git
切換至 google-ads-perl
目錄,然後在以下位置執行下列指令:
顯示使用程式庫所需的所有依附元件。
cd google-ads-perl
cpan install Module::Build
perl Build.PL
perl Build installdeps
建立
googleads.properties
敬上
檔案並修改,加入憑證。
clientId=INSERT_OAUTH2_CLIENT_ID_HERE
clientSecret=INSERT_OAUTH2_CLIENT_SECRET_HERE
refreshToken=INSERT_OAUTH2_REFRESH_TOKEN_HERE
developerToken=INSERT_DEVELOPER_TOKEN_HERE
loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE
將路徑傳遞到您儲存這個檔案的位置,建立 Client
例項。
my $properties_file = "/path/to/googleads.properties";
my $api_client = Google::Ads::GoogleAds::Client->new({
properties_file => $properties_file
});
接著,請使用
GoogleAdsService.SearchStream
敬上
擷取帳戶中的廣告活動。本指南並未涵蓋
報表的詳細資料。
sub get_campaigns {
my ($api_client, $customer_id) = @_;
# Create a search Google Ads stream request that will retrieve all campaigns.
my $search_stream_request =
Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
->new({
customerId => $customer_id,
query =>
"SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id"
});
# Get the GoogleAdsService.
my $google_ads_service = $api_client->GoogleAdsService();
my $search_stream_handler =
Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
service => $google_ads_service,
request => $search_stream_request
});
# Issue a search request and process the stream response to print the requested
# field values for the campaign in each row.
$search_stream_handler->process_contents(
sub {
my $google_ads_row = shift;
printf "Campaign with ID %d and name '%s' was found.\n",
$google_ads_row->{campaign}{id}, $google_ads_row->{campaign}{name};
});
return 1;
}
REST
請先使用 HTTP 用戶端擷取 OAuth 2.0 存取權杖。本指南
使用 curl
指令
curl \
--data "grant_type=refresh_token" \
--data "client_id=CLIENT_ID" \
--data "client_secret=CLIENT_SECRET" \
--data "refresh_token=REFRESH_TOKEN" \
https://www.googleapis.com/oauth2/v3/token
接著,請使用
GoogleAdsService.SearchStream
敬上
擷取帳戶中的廣告活動。本指南並未涵蓋
報表的詳細資料。
curl -i -X POST https://googleads.googleapis.com/v17/customers/CUSTOMER_ID/googleAds:searchStream \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "developer-token: DEVELOPER_TOKEN" \
-H "login-customer-id: LOGIN_CUSTOMER_ID" \
--data-binary "@query.json"
query.json
的內容如下所示:
{
"query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}