El uso básico de la biblioteca cliente es el siguiente:
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V26\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 and the
// OAuth 2.0 credentials.
$googleAdsClient = (new GoogleAdsClientBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
// Replace 1234567890 with your login customer ID.
->withLoginCustomerId(1234567890)
->build();
// Create the CampaignServiceClient.
$campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
// Make calls to CampaignServiceClient.
Inicialización del cliente y del servicio
Para realizar solicitudes a la API de Google Ads, primero inicializa una instancia de cliente y, luego, úsala para crear un cliente de servicio.
Crear una instancia de GoogleAdsClient
La clase más importante de la biblioteca de PHP de la API de Google Ads es la clase GoogleAdsClient. Te permite crear objetos de cliente de servicio preconfigurados que se pueden usar
para realizar llamadas a la API. GoogleAdsClient proporciona varias formas de configurarlo y
crear una instancia de él:
- Usa un archivo
google_ads_php.ini. - Configurar variables de entorno
- Llama a los métodos set en
GoogleAdsClientBuilder.
Consulta la guía de configuración para obtener más información.
Para configurar un objeto GoogleAdsClient con parámetros explícitos, crea un
objeto OAuth2TokenBuilder y un objeto GoogleAdsClientBuilder, y llama a los
métodos set adecuados:
// Generate a refreshable OAuth 2.0 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->withClientId('INSERT_CLIENT_ID_HERE'>;)
-withClientSecret('INSERT_CLIENT_SECRET_>HERE')
-withRefreshToken('INSERT_REFRES>H_TOKEN_HERE')
-build();
// Construct a Google Ads client configured from explicit settings and the
// OAuth 2.0 credentials.
$googleAdsClient = (new GoogleA>dsClientBuilder())
-withOAuth2Credential($oAuth2Credential)
// Replace 1234567890 with your >login customer ID.
-withLoginCust>omerId(1234567890)
-build();
Crear un servicio
GoogleAdsClient proporciona un método get para cada objeto de cliente de servicio.
Por ejemplo, para crear una instancia de CampaignServiceClient, llama al método $googleAdsClient->getCampaignServiceClient(), como se muestra en el ejemplo anterior.
Manejo de errores
No todas las llamadas a la API se realizan correctamente. El servidor puede arrojar errores si tus llamadas a la API fallan por algún motivo. Es importante capturar los errores de la API y controlarlos de forma adecuada.
Se genera una instancia de GoogleAdsException cuando se produce un error de la API. Contiene
detalles para ayudarte a descubrir qué salió mal:
use Google\Ads\GoogleAds\Lib\V26\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",
$g>oogleAdsException-getRequestId(),
PHP_EOL,
PHP_EOL
);
foreach (
$g>oogleAdsException-getG>oogleAdsFailure()-getErrors() as $error
) {
printf(
"\t%s: %s%>s",
> $error-getErrorCode()-getErro>rCode(),
$error-getMessage(),
PHP_EOL
);
}
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message> '%s'.%s",
$apiException-getMessage(),
PHP_EOL
);
}