Partilhar via


Autenticação com os SDKs

Este artigo aborda a autenticação e as chamadas de serviço básicas com os SDKs de Anúncios do Bing.

Configurar o Sandbox

O SDK utiliza o ambiente de produção por predefinição. Com os SDKs .NET e Java, pode alterá-lo para sandbox com uma configuração global. Enquanto a configuração global não está disponível com PHP e SDKs Python, pode criar uma configuração global ou outra solução personalizada.

// Set the BingAdsEnvironment key to Sandbox within the <appSettings> node 
// of your project root's Web.config file (for web apps) or App.config file (for native apps).
<add key="BingAdsEnvironment" value ="Sandbox"/>
// Create a new text file named bingads.properties within your project source root directory 
// e.g. **ProjectName\src\bingads.properties** and add only the following text. 
// If the sandbox environment setting is malformed or missing, the default environment is production.
environment=Sandbox

Também pode definir o parâmetro de ambiente da API de instâncias individuais de Service Manager em Massa, Cliente de Serviço e Service Manager de Relatórios. Definir a apiAmbiente substitui a definição global apenas para as instâncias ou instâncias de cliente de serviço especificadas. Salvo a intenção em contrário, deve ter o cuidado de não configurar inadvertidamente um conjunto misto de ambientes.

Nota

O BulkServiceManager e o ReportingServiceManager estão disponíveis com os SDKs .NET, Java e Python.

BulkServiceManager BulkService = new BulkServiceManager(authorizationData, ApiEnvironment.Sandbox);

ServiceClient<ICustomerManagementService> Service = new ServiceClient<ICustomerManagementService>(authorizationData, ApiEnvironment.Sandbox);
    
ReportingServiceManager ReportingService = new ReportingServiceManager(authorizationData, ApiEnvironment.Sandbox);
BulkServiceManager BulkService = new BulkServiceManager(authorizationData, ApiEnvironment.SANDBOX);

ServiceClient<ICustomerManagementService> CustomerService = 
    new ServiceClient<ICustomerManagementService>(
        authorizationData,
        ApiEnvironment.SANDBOX,
        ICustomerManagementService.class
    );
    
ReportingServiceManager ReportingService = new ReportingServiceManager(authorizationData, ApiEnvironment.SANDBOX);
$customerProxy = new ServiceClient(ServiceClientType::CustomerManagementVersion13, $authorizationData, ApiEnvironment::Sandbox);
# Set the environment property of each ServiceClient instance to 'sandbox' (not case sensitive). 
# If the sandbox environment setting is malformed or missing, the default environment is production.
# Once the environment is initialized you may not reset it for the service client instance. 
# To switch between sandbox and production, you must create a new service client instance.

bulk_service_manager = BulkServiceManager(
    authorization_data=authorization_data, 
    version = 13,
    poll_interval_in_milliseconds = 5000, 
    environment = 'sandbox',
)

customer_service = ServiceClient(
    'CustomerManagementService', 
    version = 13,
    authorization_data=authorization_data, 
    environment = 'sandbox',
)

reporting_service_manager = ReportingServiceManager(
    authorization_data=authorization_data, 
    version = 13,
    poll_interval_in_milliseconds = 5000, 
    environment = 'sandbox',
)

Utilizar o OAuth

Os SDKs de Anúncios do Bing suportam o fluxo OAuth 2.0 padrão, conforme definido em detalhe no OAuth 2.0 Authorization Framework. As classes OAuth no SDK abstraem os detalhes de autorização de utilizador de baixo nível, como formatar os URIs de autorização e redirecionamento, definir os cabeçalhos do pedido e analisar o fluxo de resposta e tráfego de redirecionamento. Para utilizar o OAuth com o SDK .NET de Anúncios do Bing, a propriedade Autenticação do objeto AuthorizationData tem de ser definida para uma classe derivada da autenticação, como OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant ou OAuthDesktopMobileImplicitGrant.

Para autenticação de repetição ou de longo prazo, deve seguir o fluxo de concessão de código de autorização para obter um token de acesso. Os passos abaixo seguem o fluxo de concessão do código de autorização. Para obter mais detalhes sobre o registo de uma aplicação e o fluxo de concessão de código de autorização, veja Authentication with OAuth (Autenticação com OAuth).

  1. Crie uma instância de OAuthWebAuthCodeGrant, que será utilizada para gerir a autorização de utilizador da Conta Microsoft. Substitua o ID de cliente (ID da aplicação registada), o segredo do cliente (palavra-passe registada) e o URI de redirecionamento pelos valores configurados quando registou a aplicação.

    var oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new Uri(RedirectionUri), ApiEnvironment);
    
    // It is recommended that you specify a non guessable 'state' request parameter to help prevent
    // cross site request forgery (CSRF). 
    oAuthWebAuthCodeGrant.State = "ClientStateGoesHere";
    
    OAuthWebAuthCodeGrant oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new URL(RedirectionUri), ApiEnvironment);
    
    // It is recommended that you specify a non guessable 'state' request parameter to help prevent
    // cross site request forgery (CSRF). 
    oAuthWebAuthCodeGrant.setState("ClientStateGoesHere");
    
    // Prepare the OAuth object for use with the authorization code grant flow. 
    // It is recommended that you specify a non guessable 'state' request parameter to help prevent
    // cross site request forgery (CSRF). 
    $authentication = (new OAuthWebAuthCodeGrant())
        ->withClientId(ClientId)
        ->withClientSecret(ClientSecret)
        ->withEnvironment(ApiEnvironment)
        ->withRedirectUri('https://' . $_SERVER['HTTP_HOST'] . RedirectUri)
        ->withState(rand(0,999999999)); 
    
    // Assign this authentication instance to the global authorization_data. 
    
    $_SESSION['AuthorizationData'] = (new AuthorizationData())
        ->withAuthentication($authentication)
        ->withDeveloperToken(AuthHelper::DeveloperToken);
    
    $_SESSION['state'] = $_SESSION['AuthorizationData']->Authentication->State;
    
    oauth_web_auth_code_grant = OAuthWebAuthCodeGrant(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        env=ENVIRONMENT,
        redirection_uri=REDIRECTION_URI
    )
    
    # It is recommended that you specify a non guessable 'state' request parameter to help prevent
    # cross site request forgery (CSRF). 
    oauth_web_auth_code_grant.state="ClientStateGoesHere"
    
  2. Peça o consentimento do utilizador ao ligar ao ponto final de autorização da Conta Microsoft através de um controlo de browser. Chame o método GetAuthorizationEndpoint da instância OAuthWebAuthCodeGrant que criou no passo anterior.

    return Redirect(oAuthWebAuthCodeGrant.GetAuthorizationEndpoint().ToString());
    
    URL authorizationEndpoint = oAuthWebAuthCodeGrant.getAuthorizationEndpoint();
    response.sendRedirect(authorizationEndpoint.toString());
    
    // The user needs to provide consent for the application to access their Microsoft Advertising accounts.
    header('Location: '. $_SESSION['AuthorizationData']->Authentication->GetAuthorizationEndpoint());
    
    oauth_web_auth_code_grant.get_authorization_endpoint()
    

    O utilizador será solicitado através do controlo do browser de autorização da Conta Microsoft para conceder permissões para a sua aplicação gerir as respetivas contas do Microsoft Advertising.

    O serviço de autorização chama de volta para a sua aplicação com o URI de redirecionamento, que inclui um código de autorização se o utilizador tiver autorizado a sua aplicação a gerir as respetivas contas do Microsoft Advertising. Por exemplo, o URL de chamada de retorno inclui um código de autorização da seguinte forma se o utilizador tiver concedido permissões para a sua aplicação gerir as respetivas contas do Microsoft Advertising: ;https://contoso.com/redirect/?code=CODE& state=ClientStateGoesHere. Se o utilizador tiver concedido permissões à sua aplicação para gerir as respetivas contas do Microsoft Advertising, deverá utilizar o código imediatamente no próximo passo. A curta duração do código de autorização, aproximadamente 5 minutos, está sujeita a alterações.

    Se o utilizador tiver negado as permissões da aplicação para gerir as respetivas contas do Microsoft Advertising, o URI de chamada de retorno inclui um campo de descrição de erros e erros da seguinte forma: REDIRECTURI?error=access_denied&error_description=ERROR_DESCRIPTION&state=ClientStateGoesHere.

  3. Utilize o código de autorização para pedir o token de acesso e atualizar o token. Transmita o URI de chamada de retorno completo ao utilizar a instância OAuthWebAuthCodeGrant para pedir o token de acesso e atualizar o token.

    if (Request["code"] != null)
    {
        await oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(Request.Url);
    }
    
    if (request.getParameter("code") != null)
    {
        oAuthWebAuthCodeGrant.requestAccessAndRefreshTokens(new URL(request.getRequestURL() + "?" + request.getQueryString()));
    }
    
    if($_GET['code'] != null)
    {   
        $_SESSION['AuthorizationData']->Authentication->RequestOAuthTokensByResponseUri($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    
        header('Location: '. '/CallBingAdsServices.php');
    }
    
    oauth_web_auth_code_grant.request_oauth_tokens_by_response_uri(RESPONSE_URI)
    oauth_tokens = oauth_web_auth_code_grant.oauth_tokens
    access_token = oauth_tokens.access_token
    

    Se este passo for bem-sucedido, a sua aplicação tem permissões para gerir as contas do Microsoft Advertising do utilizador. Para chamar as operações de serviço da API de Anúncios do Bing, deve inicializar o Cliente de Serviço, a Service Manager em Massa ou a Service Manager de Relatórios com AuthorizationData que contém a sua instância OAuthWebAuthCodeGrant.

    Para obter mais informações, veja Utilizar AuthorizationData, Utilizar o Cliente de Serviço, Utilizar o BulkServiceManager e Utilizar o ReportingServiceManager.

    Nota

    O BulkServiceManager e o ReportingServiceManager estão disponíveis com os SDKs .NET, Java e Python.

  4. Ao chamar operações de serviço da API de Anúncios do Bing com o Cliente de Serviço, Service Manager em Massa ou Service Manager de Relatórios, é importante guardar o token de atualização mais recente sempre que forem recebidos novos tokens OAuth.

    // If you already have a refresh token, use it to request new access and refresh tokens.
    
    if (GetRefreshToken(out refreshToken))
    {
        oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(refreshToken);
    }
    
    // When calling Bing Ads API service operations with Service Client, Bulk Service Manager, or Reporting Service Manager, 
    // each instance will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code. 
    // It is important to save the most recent refresh token whenever new OAuth tokens are received. 
    // You will want to subscribe to the NewOAuthTokensReceived event handler.
    
    oAuthWebAuthCodeGrant.NewOAuthTokensReceived += 
        (sender, args) => SaveRefreshToken(args.NewRefreshToken);
    
    // If you already have a refresh token, use it to request new access and refresh tokens.
    
    if (refreshToken != null)
    {
        oAuthWebAuthCodeGrant.requestAccessAndRefreshTokens(refreshToken);
    }
    
    // When calling Bing Ads API service operations with Service Client, Bulk Service Manager, or Reporting Service Manager, 
    // each instance will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code. 
    // It is important to save the most recent refresh token whenever new OAuth tokens are received. 
    // You will want to implement event handling using the NewOAuthTokensReceivedListener.
    
    oAuthWebAuthCodeGrant.setNewTokensListener(new NewOAuthTokensReceivedListener() {
        @Override
        public void onNewOAuthTokensReceived(OAuthTokens newTokens) {
               saveRefreshToken(newTokens.getRefreshToken());
        }
    });
    
    // If you already have a refresh token, use it to request new access and refresh tokens.
    $_SESSION['AuthorizationData']->Authentication->RequestOAuthTokensByRefreshToken($refreshToken);
    
    # When calling Bing Ads API service operations with Service Client, Bulk Service Manager, or Reporting Service Manager, 
    # each instance will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code. 
    # It is important to save the most recent refresh token whenever new OAuth tokens are received. 
    # You will want to register a callback function to automatically save the refresh token anytime it is refreshed. 
    # For example if you defined have a save_refresh_token() method that securely stores your refresh token, 
    # set the authentication token_refreshed_callback property of each OAuthWebAuthCodeGrant instance.
    
    oauth_web_auth_code_grant.token_refreshed_callback=save_refresh_token
    
    # If you already have a refresh token, use it to request new access and refresh tokens.
    
    if refresh_token is not None:
        oauth_web_auth_code_grant.request_oauth_tokens_by_refresh_token(refresh_token)
    

    Importante

    Um token de atualização pode durar até 90 dias. Independentemente disso, deverá começar novamente a partir do Passo 1 e pedir o consentimento do utilizador se, por exemplo, o utilizador da Conta Microsoft tiver alterado a palavra-passe, removido um dispositivo da lista de dispositivos fidedignos ou removido as permissões para a sua aplicação se autenticar em seu nome.

Utilizar AuthorizationData

A classe AuthorizationData contém propriedades que o Microsoft Advertising utiliza para autorizar um utilizador. As classes Cliente de Serviço, Service Manager em Massa e Relatórios Service Manager processam os campos de cabeçalho do pedido comuns automaticamente, permitindo-lhe especificar as propriedades Autenticação, CustomerId, AccountId e DeveloperToken no objeto AuthorizationData uma vez para cada serviço.

Nota

O BulkServiceManager e o ReportingServiceManager estão disponíveis com os SDKs .NET, Java e Python.

O bloco de código seguinte mostra como criar uma instância de AuthorizationData e definir as propriedades Autenticação, CustomerId, AccountId e DeveloperToken .

var authorizationData = new AuthorizationData
{
    Authentication = <AuthenticationGoesHere>, 
    CustomerId = <CustomerIdGoesHere>,
    AccountId = <AccountIdGoesHere>,
    DeveloperToken = "<DeveloperTokenGoesHere>"
};
static AuthorizationData authorizationData = new AuthorizationData();
authorizationData.setAuthentication(<AuthenticationGoesHere>);
authorizationData.setCustomerId("<CustomerIdGoesHere>");
authorizationData.setAccountId("<AccountIdGoesHere>");
authorizationData.setDeveloperToken("<DeveloperTokenGoesHere>");
$authorizationData = (new AuthorizationData())
    ->withAuthentication($AuthenticationGoesHere)
    ->withCustomerId($CustomerIdGoesHere)
    ->withAccountId($AccountIdGoesHere)
    ->withDeveloperToken($DeveloperTokenGoesHere);
authorization_data = AuthorizationData(
    authentication = <AuthenticationGoesHere>,
    customer_id = <CustomerIdGoesHere>,
    account_id = <AccountIdGoesHere>,
    developer_token = '<DeveloperTokenGoesHere>'
)

A propriedade Autenticação tem de ser definida para uma classe derivada da autenticação, como OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant ou OAuthDesktopMobileImplicitGrant.

Alguns serviços, como a Gestão de Clientes, não aceitam cabeçalhos CustomerId e CustomerAccountId , pelo que serão ignorados se os tiver especificado no objeto AuthorizationData .

Utilizar o Cliente de Serviço

Pode utilizar uma instância da classe ServiceClient para chamar quaisquer métodos de um dos serviços Web Microsoft Advertising. A classe ServiceClient processa os campos de cabeçalho do pedido comuns automaticamente, permitindo especificar as propriedades Autenticação, CustomerId, AccountId e DeveloperToken no objeto AuthorizationData uma vez para cada serviço.

Sugestão

Se estiver a utilizar o Bulk or Reporting Services, utilize o Service Manager em massa ou a Service Manager de Relatórios em vez do ServiceClient. Por exemplo, o Service Manager em massa submeterá o seu pedido de transferência para o serviço em massa, consultará o serviço até estar concluído e transferirá o ficheiro para o diretório local que especificou no pedido. Poupará ainda mais tempo porque não tem de escrever ou analisar os ficheiros de carregamento ou resultados.

// The primary method of the ServiceClient class is CallAsync. The method parameter is the delegate 
// for the service operation that you want to call. The request parameter of this method must be a 
// request message corresponding to the name of the service operation specified by the first request parameter. 
// The request message must match the service operation that is specified as the delegate in the first request.

public async Task<TResponse> CallAsync<TRequest, TResponse>(
    Func<TService, TRequest, Task<TResponse>> method, TRequest request)

// In the following sample, the method delegate is (s, r) => s.GetUserAsync(r) which takes a GetUserRequest 
// message as the request parameter (TRequest) and returns a GetUserResponse message (TResponse).

private async Task<User> GetUserAsync(long? userId)
{
    var request = new GetUserRequest
    {
        UserId = userId
    };

    return (await _customerService.CallAsync((s, r) => s.GetUserAsync(r), request)).User;
}
// You can use the Customer Management service to get the current authenticated user.

ServiceClient<ICustomerManagementService> CustomerService = new ServiceClient<ICustomerManagementService>(
		authorizationData, 
		ICustomerManagementService.class);

java.lang.Long userId = null;
final GetUserRequest getUserRequest = new GetUserRequest();
getUserRequest.setUserId(userId);

// If you updated the authorization data such as account ID or you want to call a new operation, 
// you must call getService to set the latest request headers. 
// As a best practice you should use getService when calling any service operation.
User user = CustomerService.getService().getUser(getUserRequest).getUser();
// You can use a single instance of the ServiceClient class to call any methods in the service, 
// for example you can set the CustomerManagementVersion13 service client type as follows.

$customerProxy = new ServiceClient(ServiceClientType::CustomerManagementVersion13, $authorizationData, ApiEnvironment::Sandbox);
)
# You can use the Customer Management service to get the current authenticated user.

customer_service = ServiceClient(
    'CustomerManagementService', 
    version = 13,
    authorization_data=authorization_data, 
    environment = ENVIRONMENT,
)

user = customer_service.GetUser(UserId = None).User

Importante

Se definir os elementos de cabeçalho AuthenticationToken, CustomerId, AccountId ou DeveloperToken no parâmetro do pedido, por exemplo, GetUserRequest, estes serão ignorados. O Cliente de Serviço utiliza sempre o AuthorizationData fornecido com a respetiva inicialização.

See Also

Sandbox
Exemplos de Código da API de Anúncios do Bing
Endereços do Serviço Web da API de Anúncios do Bing