การใช้งานพื้นฐานของไลบรารีของไคลเอ็นต์มีดังนี้
use Google\Ads\GoogleAds\Lib\V25\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V25\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V25\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
คลาสที่สำคัญที่สุดในไลบรารี Google Ads API PHP คือคลาส GoogleAdsClient ซึ่งช่วยให้คุณสร้างออบเจ็กต์ไคลเอ็นต์ของบริการที่กำหนดค่าไว้ล่วงหน้าซึ่งใช้สำหรับการเรียก API ได้ GoogleAdsClient มีวิธีต่างๆ ในการสร้างอินสแตนซ์ ดังนี้
- ใช้ไฟล์
google_ads_php.ini - ใช้ตัวแปรสภาพแวดล้อม
- ใช้ Setter ใน
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\V25\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
);
}