本指南需要在先前步驟中設定的幾項必要條件。如果尚未完成,請先參閱簡介。
發出 API 呼叫
請選取所需用戶端,瞭解如何發出 API 呼叫:
Java
用戶端程式庫構件會發布至 Maven Central 存放區。將用戶端程式庫新增為專案的依附元件,如下所示:
Maven 依附元件如下:
<dependency>
<groupId>com.google.api-ads</groupId>
<artifactId>google-ads</artifactId>
<version>35.0.0</version>
</dependency>
Gradle 依附元件如下:
implementation 'com.google.api-ads:google-ads:35.0.0'
api.googleads.serviceAccountSecretsPath=JSON_KEY_FILE_PATH
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 存放區。首先,請將 nuget 參照新增至 Google.Ads.GoogleAds
套件。
dotnet add package Google.Ads.GoogleAds --version 18.1.0
使用相關設定建立 GoogleAdsConfig
物件,然後使用該物件建立 GoogleAdsClient
物件。
GoogleAdsConfig config = new GoogleAdsConfig()
{
DeveloperToken = "******",
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);
接著,請使用 GoogleAdsService.SearchStream
方法執行廣告活動報表,擷取帳戶中的廣告活動。本指南不涵蓋回報的詳細資訊。
public void Run(GoogleAdsClient client, long customerId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V18.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:25.0.0
從 GitHub 存放區複製 google_ads_php.ini
檔案,然後修改檔案以納入您的憑證。
[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
[OAUTH2]
jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE"
scopes = "https://www.googleapis.com/auth/adwords"
建立 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
從 GitHub 存放區複製 google-ads.yaml
檔案,然後修改檔案以納入您的憑證。
developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
json_key_file_path: JSON_KEY_FILE_PATH_HERE
呼叫 GoogleAdsClient.load_from_storage
方法來建立 GoogleAdsClient
例項。在呼叫 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 寶石會發布至 Rubygems gem 主機網站。建議您使用 Bundler 安裝。在 Gemfile 中新增一行:
gem 'google-ads-googleads', '~> 30.0.0'
接著執行:
bundle install
從 GitHub 存放區複製 google_ads_config.rb
檔案,然後修改檔案以納入您的憑證。
Google::Ads::GoogleAds::Config.new do |c|
c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
c.keyfile = 'JSON_KEY_FILE_PATH'
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
從 GitHub 存放區複製 googleads.properties
檔案,然後修改檔案以納入您的憑證。
jsonKeyFilePath=JSON_KEY_FILE_PATH
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::V18::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 存取權杖。
gcloud auth \
print-access-token \
--scopes='https://www.googleapis.com/auth/adwords'
接著,請使用 GoogleAdsService.SearchStream
方法執行廣告活動報表,擷取帳戶中的廣告活動。本指南不涵蓋回報的詳細資訊。
curl -i -X POST https://googleads.googleapis.com/v18/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"
}