طلب بيانات من واجهة برمجة التطبيقات

يتطلب هذا الدليل العديد من الإعدادات المطلوبة مسبقًا التي تم ضبطها في الخطوات السابقة. ابدأ بـ مقدمة إذا لم تكن قد فعلت ذلك.

يستخدم هذا الدليل أيضًا الرموز المميزة لإعادة التحميل، وهي سير عمل يمكن من خلاله للمستخدم الذي لديه إذن وصول كافٍ إلى حساب "إعلانات Google" تفويض تطبيقك، من خلال إعداد لمرّة واحدة، لإجراء طلبات بيانات من واجهة برمجة التطبيقات بلا اتصال بالإنترنت إلى الحساب بدون أيّ تدخّل إضافي من المستخدم. يمكنك استخدام الرموز المميّزة لإعادة التحميل لإنشاء سير العمل بلا اتصال بالإنترنت، مثل مهام cron أو مسارات البيانات وعمليات سير العمل التفاعلية، مثل تطبيقات الويب أو التطبيقات المتوافقة مع الأجهزة الجوّالة.

استرجاع رمز مميّز لإعادة التحميل

تستخدم Google Ads API بروتوكول OAuth 2.0 كآلية تفويض. تصدر مصادقة OAuth 2.0 تلقائيًا رمز دخول ينتهي بعد فترة محدودة. لتجديد رمز الدخول تلقائيًا، يجب إصدار رمز مميّز لإعادة التحميل بدلاً من ذلك.

  1. أنشئ الرمز المميّز لإعادة التحميل من خلال تشغيل أداة oauth2l:

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

    ينتمي ملف credentials.json إلى خطوة سابقة.

  2. يفتح الأمر oauth2l نافذة تسجيل الدخول إلى حساب Google في نافذة متصفح جديدة وينقلك خلال خطوات مصادقة OAuth 2.0.

    تأكد من تسجيل الدخول باستخدام عنوان البريد الإلكتروني من الخطوة التي حددت فيها الرقم التعريفي للعميل لتسجيل الدخول.

    إذا لم يتم التحقق من تطبيقك، قد تظهر لك شاشة تحذير. في مثل هذه الحالات، يمكنك النقر على الرابط إظهار الإعدادات المتقدمة والنقر على خيار الانتقال إلى PROJECT_NAME (لم يتم التحقق منه).

  3. بعد التحقّق من النطاقات، امنح الإذن بالنقر على الزر متابعة.

    يتم عرض إشعار في المتصفِّح يتضمّن النص التالي:

    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"
    }
    

طلب بيانات من واجهة برمجة التطبيقات

اختر العميل الذي تختاره للحصول على إرشادات حول كيفية الاتصال بواجهة برمجة التطبيقات:

Java

ويتم نشر عناصر مكتبة العميل في مستودع Maven المركزي. أضف مكتبة البرامج كتبعية إلى مشروعك على النحو التالي:

تبعية Maven هي:

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

تبعية Gradle هي:

implementation 'com.google.api-ads:google-ads:28.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 17.0.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.V15.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:21.1.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::V15::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;
}

راحة

ابدأ باستخدام عميل 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/v15/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"
}