O uso básico da biblioteca de cliente é o seguinte:
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.
Inicialização do cliente e do serviço
Para fazer solicitações à API Google Ads, primeiro inicialize uma instância de cliente e use-a para criar um cliente de serviço.
Criar uma instância GoogleAdsClient
A classe mais importante na biblioteca da API Google Ads para PHP é a GoogleAdsClient. Ele permite criar objetos de cliente de serviço pré-configurados que podem ser usados
para fazer chamadas de API. O GoogleAdsClient oferece várias maneiras de configurar e
instanciar:
- Usar um arquivo
google_ads_php.ini. - Definir variáveis de ambiente.
- Chame métodos setter em
GoogleAdsClientBuilder.
Consulte o guia de configuração para saber mais.
Para configurar um objeto GoogleAdsClient com definições explícitas, crie um objeto OAuth2TokenBuilder e um objeto GoogleAdsClientBuilder e chame os métodos setter adequados:
// 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();
Criar um serviço
GoogleAdsClient fornece um método getter para cada objeto de cliente de serviço.
Por exemplo, para criar uma instância de CampaignServiceClient, chame o
método $googleAdsClient->getCampaignServiceClient(), conforme mostrado no
exemplo anterior.
Tratamento de erros
Nem todas as chamadas de API são bem-sucedidas. O servidor pode gerar erros se as chamadas de API falharem por algum motivo. É importante capturar erros de API e tratá-los adequadamente.
Uma instância GoogleAdsException é gerada quando ocorre um erro de API. Ele contém
detalhes para ajudar você a descobrir o que deu errado:
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
);
}