השימוש הבסיסי בספריית הלקוח הוא כדלקמן:
use Google\Ads\GoogleAds\Lib\V22\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V22\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V22\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\ApiCore\ApiException;
// Generate a refreshable OAuth 2.0 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// Construct a Google Ads client configured from a properties file and the
$googleAdsClient = (new GoogleAdsClientBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->withLoginCustomerId(1234567890) // Replace 1234567890 with your login customer ID.
->build();
// Create the CampaignServiceClient.
$campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
// Make calls to CampaignServiceClient.
יצירת מופע של GoogleAdsClient
המחלקות הכי חשובות בספריית PHP של Google Ads API הן המחלקות GoogleAdsClient. היא מאפשרת ליצור אובייקטים של לקוחות שירות שהוגדרו מראש, שאפשר להשתמש בהם כדי לבצע קריאות ל-API. GoogleAdsClient מספק דרכים שונות ליצירת מופע שלו:
- משתמשים בקובץ
google_ads_php.ini. - שימוש במשתני סביבה.
- שימוש ב-setters ב-
GoogleAdsClientBuilder.
מידע נוסף זמין במדריך ההגדרה.
כדי להגדיר אובייקט GoogleAdsClient, יוצרים אובייקט OAuth2TokenBuilder ואובייקט GoogleAdsClientBuilder ומגדירים את ההגדרות הנדרשות:
// Generate a refreshable OAuth 2.0 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// Construct a Google Ads client configured from a properties file
$googleAdsClient = (new GoogleAdsClientBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->withLoginCustomerId(1234567890) // Replace 1234567890 with your login customer ID.
->build();
יצירת שירות
GoogleAdsClient מספקת שיטת getter לכל אובייקט של לקוח שירות.
לדוגמה, כדי ליצור מופע של CampaignServiceClient, צריך להפעיל את המתודה GoogleAdsClient->getCampaignServiceClient(), כמו בדוגמה הקודמת.
טיפול בשגיאות
לא כל קריאה ל-API תצליח. השרת יכול להחזיר שגיאות אם הקריאות ל-API נכשלות מסיבה כלשהי. חשוב לתעד שגיאות ב-API ולטפל בהן בצורה מתאימה.
מופעלת מופע GoogleAdsException כשמתרחשת שגיאה ב-API. הוא כולל פרטים שיעזרו לכם להבין מה השתבש:
use Google\Ads\GoogleAds\Lib\V22\GoogleAdsException;
use Google\ApiCore\ApiException;
try {
// Make your API call here.
} catch (GoogleAdsException $googleAdsException) {
printf(
"Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
$googleAdsException->getRequestId(),
PHP_EOL,
PHP_EOL
);
foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
printf(
"\t%s: %s%s",
$error->getErrorCode()->getErrorCode(),
$error->getMessage(),
PHP_EOL
);
}
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
}