API çağrısı yapma

Bu kılavuz, önceki adımlarda yapılandırılan bazı ön koşul ayarlarını gerektirir. Henüz yapmadıysanız Giriş ile başlayın.

Bu kılavuzda yenileme jetonları da kullanılmaktadır. Bu iş akışı, Google Ads hesabına yeterli erişimi olan bir kullanıcının uygulamanızı başka kullanıcı müdahalesi olmadan hesaba tek seferlik bir şekilde çevrimdışı API çağrıları yapması için yetkilendirebilir. Hem cron işleri veya veri ardışık düzenleri gibi çevrimdışı iş akışları hem de web veya mobil uygulamalar gibi etkileşimli iş akışları oluşturmak için yenileme jetonlarını kullanabilirsiniz.

Yenileme jetonu getir

Google Ads API, yetkilendirme mekanizması olarak OAuth 2.0'ı kullanır. Varsayılan olarak OAuth 2.0 kimlik doğrulaması, sınırlı bir süre sonra süresi dolan bir erişim jetonu yayınlar. Erişim jetonunu otomatik olarak yenilemek için bunun yerine bir yenileme jetonu yayınlamanız gerekir.

  1. oauth2l aracını çalıştırarak yenileme jetonunu oluşturun:

    oauth2l fetch --credentials credentials.json --scope adwords \
        --output_format refresh_token
    

    credentials.json dosyası önceki bir adıma aittir.

  2. oauth2l komutu, yeni bir tarayıcı penceresinde Google Hesabı giriş penceresini açar ve sizi OAuth 2.0 kimlik doğrulama adımlarına yönlendirir.

    Giriş müşteri kimliğinizi tanımladığınız adımdaki e-posta adresini kullanarak oturum açtığınızdan emin olun.

    Uygulamanız doğrulanmamışsa bir uyarı ekranı görebilirsiniz. Bu gibi durumlarda Gelişmiş Göster bağlantısını ve PROJECT_NAME sitesine git (doğrulanmamış) seçeneğini güvenle tıklayabilirsiniz.

  3. Kapsamları doğruladıktan sonra Devam düğmesini tıklayarak izin verin.

    Tarayıcıda aşağıdaki metni içeren bir istem görüntülenir:

    Authorization code granted. Please close this tab.
    

    oauth2l komutu aşağıdaki JSON snippet'ini çıkarır:

    {
      "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 çağrısı yapma

API çağrısı yapmayla ilgili talimatlar için istediğiniz istemcinizi seçin:

Java

İstemci kitaplığı yapıları Maven merkezi deposunda yayınlanır. İstemci kitaplığını projenize bağımlılık olarak aşağıdaki şekilde ekleyin:

Maven bağımlılığı:

<dependency>
  <groupId>com.google.api-ads</groupId>
  <artifactId>google-ads</artifactId>
  <version>30.0.0</version>
</dependency>

Gradle bağımlılığı:

implementation 'com.google.api-ads:google-ads:30.0.0'

Aşağıdaki içeriğe sahip bir ~/ads.properties dosyası oluşturun:

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

Aşağıdaki gibi bir GoogleAdsClient nesnesi oluşturun:

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

Ardından, hesabınızdaki kampanyaları almak için GoogleAdsService.SearchStream yöntemini kullanarak bir kampanya raporu çalıştırın. Bu kılavuzda raporlama ayrıntıları ele alınmamaktadır.

  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#

İstemci kitaplığı paketleri Nuget.org deposunda yayınlanır. Google.Ads.GoogleAds paketine bir nuget referansı ekleyerek başlayın.

dotnet add package Google.Ads.GoogleAds --version 18.1.0

İlgili ayarlarla bir GoogleAdsConfig nesnesi oluşturun ve bunu bir GoogleAdsClient nesnesi oluşturmak için kullanın.

GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = "APPLICATION",
    OAuth2ClientId = "******.apps.googleusercontent.com",
    OAuth2ClientSecret = "******",
    OAuth2RefreshToken = "******",
    LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);

Ardından, hesabınızdaki kampanyaları almak için GoogleAdsService.SearchStream yöntemini kullanarak bir kampanya raporu çalıştırın. Bu kılavuzda raporlama ayrıntıları ele alınmamaktadır.

  public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V16.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

İstemci kitaplığı paketleri Packagist deposunda yayınlanır. Projenizin kök dizinine geçin ve aşağıdaki komutu çalıştırarak kitaplığı ve tüm bağımlılıklarını projenizin kök dizininin vendor/ dizinine yükleyin.

composer require googleads/google-ads-php:22.0.0

GitHub deposundan google_ads_php.ini dosyasının bir kopyasını oluşturun ve bu kopyayı kimlik bilgilerinizi içerecek şekilde değiştirin.

[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 nesnesinin bir örneğini oluşturun.

$oAuth2Credential = (new OAuth2TokenBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->build();

$googleAdsClient = (new GoogleAdsClientBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->withOAuth2Credential($oAuth2Credential)
    ->build();

Ardından, hesabınızdaki kampanyaları almak için GoogleAdsService.SearchStream yöntemini kullanarak bir kampanya raporu çalıştırın. Bu kılavuzda raporlama ayrıntıları ele alınmamaktadır.

  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

İstemci kitaplığı PyPI'da dağıtılır; aşağıdaki gibi pip komutu kullanılarak yüklenebilir:

python -m pip install google-ads==21.3.0

GitHub deposunda google-ads.yaml dosyasının bir kopyasını oluşturun ve bu kopyayı kimlik bilgilerinizi içerecek şekilde değiştirin.

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.load_from_storage yöntemini çağırarak bir GoogleAdsClient örneği oluşturun. google-ads.yaml öğesi için yolu, çağırırken yönteme bir dize olarak iletin:

from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")

Ardından, hesabınızdaki kampanyaları almak için GoogleAdsService.SearchStream yöntemini kullanarak bir kampanya raporu çalıştırın. Bu kılavuzda raporlama ayrıntıları ele alınmamaktadır.

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

İstemci kitaplığı için Ruby mücevherleri, Rubygems gem barındırma sitesinde yayınlanır. Yükleme için önerilen yol, paketleyici kullanmaktır. Gemfile'ınıza bir satır ekleyin:

gem 'google-ads-googleads', '~> 23.1.0'

Ardından şu komutu çalıştırın:

bundle install

GitHub deposundan google_ads_config.rb dosyasının bir kopyasını oluşturun ve bu kopyayı kimlik bilgilerinizi içerecek şekilde değiştirin.

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

Bu dosyayı sakladığınız yolu geçirerek bir GoogleAdsClient örneği oluşturun.

client = Google::Ads::GoogleAds::GoogleAdsClient.new('path/to/google_ads_config.rb')

Ardından, hesabınızdaki kampanyaları almak için GoogleAdsService.SearchStream yöntemini kullanarak bir kampanya raporu çalıştırın. Bu kılavuzda raporlama ayrıntıları ele alınmamaktadır.

  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

Kitaplık CPAN'de dağıtılır. google-ads-perl deposunu istediğiniz dizinde klonlayarak başlayın.

git clone https://github.com/googleads/google-ads-perl.git

google-ads-perl dizinine geçin ve kitaplığı kullanmak için gereken tüm bağımlılıkları yüklemek üzere komut isteminde aşağıdaki komutu çalıştırın.

cd google-ads-perl
cpan install Module::Build
perl Build.PL
perl Build installdeps

GitHub deposundan googleads.properties dosyasının bir kopyasını oluşturun ve bu kopyayı kimlik bilgilerinizi içerecek şekilde değiştirin.

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

Bu dosyayı sakladığınız yolun yolunu ileterek bir Client örneği oluşturun.

my $properties_file = "/path/to/googleads.properties";

my $api_client = Google::Ads::GoogleAds::Client->new({
  properties_file => $properties_file
});

Ardından, hesabınızdaki kampanyaları almak için GoogleAdsService.SearchStream yöntemini kullanarak bir kampanya raporu çalıştırın. Bu kılavuzda raporlama ayrıntıları ele alınmamaktadır.

  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::V16::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

OAuth 2.0 erişim jetonu almak için bir HTTP istemcisi kullanarak başlayın. Bu kılavuzda curl komutu kullanılmaktadır.

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

Ardından, hesabınızdaki kampanyaları almak için GoogleAdsService.SearchStream yöntemini kullanarak bir kampanya raporu çalıştırın. Bu kılavuzda raporlama ayrıntıları ele alınmamaktadır.

curl -i -X POST https://googleads.googleapis.com/v16/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 içeriği aşağıdaki gibidir:

{
  "query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}