במדריך הזה נדרשות כמה הגדרות מוקדמות שהוגדרו בשלבים הקודמים. אם עדיין לא עשיתם זאת, תחילה כדאי לקרוא את המאמר מבוא.
במדריך הזה נעשה שימוש גם באסימוני רענון, תהליך עבודה שבו משתמש עם הרשאת גישה מספיקה לחשבון Google Ads יכול לאשר לאפליקציה, בהגדרה חד-פעמית, לבצע קריאות ל-API אופליין בחשבון ללא התערבות נוספת של המשתמש. אפשר להשתמש באסימוני רענון כדי לבנות תהליכי עבודה אופליין, כמו משימות cron או צינורות עיבוד נתונים, וגם תהליכי עבודה אינטראקטיביים כמו אפליקציות לאינטרנט או לנייד.
אחזור אסימון רענון
Google Ads API משתמש ב-OAuth 2.0 כמנגנון ההרשאה. כברירת מחדל, באימות OAuth 2.0 נוצר אסימון גישה שהתוקף שלו פג אחרי פרק זמן מוגבל. כדי לחדש את אסימון הגישה באופן אוטומטי, צריך להנפיק אסימון רענון במקום זאת.
כדי ליצור את אסימון הרענון, מריצים את הכלי oauth2l:
oauth2l fetch --credentials credentials.json --scope adwords \ --output_format refresh_token
הקובץ
credentials.json
הוא משלב קודם.הפקודה
oauth2l
פותחת חלון התחברות לחשבון Google בחלון דפדפן חדש, ומנחה אתכם במהלך שלבי האימות של OAuth 2.0.חשוב לוודא שנכנסתם באמצעות כתובת האימייל מהשלב שבו זיהיתם את מספר הלקוח להתחברות.
אם האפליקציה לא מאומתת, יכול להיות שיוצג מסך אזהרה. במקרים כאלה, אפשר ללחוץ על הקישור Show Advanced ואז על האפשרות Go to PROJECT_NAME (unVerify) (לא מאומת).
אחרי שמאמתים את ההיקפים, מעניקים את ההרשאה על ידי לחיצה על הלחצן Continue.
תוצג בדפדפן הנחיה עם הטקסט הבא:
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>32.0.0</version>
</dependency>
תלות Gradle היא:
implementation 'com.google.api-ads:google-ads:32.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. קודם כול, מוסיפים הפניה ל-nuget לחבילת Google.Ads.GoogleAds
.
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
ממאגר GitHub ושנו אותו כך שיכלול את פרטי הכניסה שלכם.
[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
ממאגר GitHub ושנו אותו כך שיכלול את פרטי הכניסה שלכם.
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
אבני החן של Ruby בספריית הלקוח מתפרסמות באתר אירוח אבני החן של Rubygems. הדרך המומלצת להתקנה היא באמצעות Bundler. מוסיפים שורה לקובץ ה-Gemfile:
gem 'google-ads-googleads', '~> 23.1.0'
לאחר מכן מפעילים את הפקודה:
bundle install
צרו עותק של הקובץ google_ads_config.rb
ממאגר GitHub ושנו אותו כך שיכלול את פרטי הכניסה שלכם.
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
ממאגר GitHub ושנו אותו כך שיכלול את פרטי הכניסה שלכם.
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"
}