Share via


Autenticazione con gli SDK

Questo articolo illustra l'autenticazione e le chiamate al servizio di base con gli SDK di Bing Ads.

Configurazione della sandbox

L'SDK usa l'ambiente di produzione per impostazione predefinita. Con gli SDK .NET e Java è possibile modificarlo in sandbox con una configurazione globale. Mentre la configurazione globale non è disponibile con GLI SDK PHP e Python, è possibile creare una configurazione globale o un'altra soluzione personalizzata.

// 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

È anche possibile impostare il parametro dell'ambiente API delle singole istanze di Service Manager bulk, client del servizio e creazione di report Service Manager. L'impostazione dell'apiEnvironment esegue l'override dell'impostazione globale solo per l'istanza o le istanze del client del servizio specificate. Se non diversamente previsto, è necessario prestare attenzione a non configurare inavvertitamente un set misto di ambienti.

Nota

BulkServiceManager e ReportingServiceManager sono disponibili con gli SDK .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',
)

Uso di OAuth

Gli SDK di Bing Ads supportano il flusso OAuth 2.0 standard come definito in dettaglio nel framework di autorizzazione OAuth 2.0. Le classi OAuth nell'SDK astraggono i dettagli di autorizzazione utente di basso livello, ad esempio la formattazione degli URI di autorizzazione e reindirizzamento, l'impostazione delle intestazioni della richiesta e l'analisi del traffico di reindirizzamento e del flusso di risposta. Per usare OAuth con Bing Ads .NET SDK, la proprietà Authentication dell'oggetto AuthorizationData deve essere impostata su una classe derivata dall'autenticazione, ad esempio OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant o OAuthDesktopMobileImplicitGrant.

Per l'autenticazione ripetuta o a lungo termine, è necessario seguire il flusso di concessione del codice di autorizzazione per ottenere un token di accesso. I passaggi seguenti seguono il flusso di concessione del codice di autorizzazione. Per altre informazioni sulla registrazione di un'applicazione e sul flusso di concessione del codice di autorizzazione, vedere Autenticazione con OAuth.

  1. Creare un'istanza di OAuthWebAuthCodeGrant, che verrà usata per gestire l'autorizzazione utente dell'account Microsoft. Sostituire l'ID client (ID applicazione registrata), il segreto client (password registrata) e l'URI di reindirizzamento con i valori configurati al momento della registrazione dell'applicazione.

    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. Richiedere il consenso dell'utente connettendosi all'endpoint di autorizzazione dell'account Microsoft tramite un controllo Web browser. Chiamare il metodo GetAuthorizationEndpoint dell'istanza di OAuthWebAuthCodeGrant creata nel passaggio precedente.

    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()
    

    All'utente verrà richiesto tramite il controllo web browser per l'autorizzazione dell'account Microsoft di concedere all'applicazione le autorizzazioni necessarie per gestire gli account Microsoft Advertising.

    Il servizio di autorizzazione richiama l'applicazione con l'URI di reindirizzamento, che include un codice di autorizzazione se l'utente ha autorizzato l'applicazione a gestire gli account Microsoft Advertising. Ad esempio, l'URL di callback include un codice di autorizzazione come indicato di seguito se l'utente ha concesso all'applicazione le autorizzazioni per gestire i propri account Microsoft Advertising: https://contoso.com/redirect/?code=CODE& state=ClientStateGoesHere. Se l'utente ha concesso all'applicazione le autorizzazioni per gestire i propri account Microsoft Advertising, è consigliabile usare il codice immediatamente nel passaggio successivo. La breve durata del codice di autorizzazione, circa 5 minuti, è soggetta a modifiche.

    Se l'utente ha negato le autorizzazioni dell'applicazione per gestire gli account Microsoft Advertising, l'URI di callback include un campo di descrizione degli errori e degli errori come indicato di seguito: REDIRECTURI?error=access_denied&error_description=ERROR_DESCRIPTION&state=ClientStateGoesHere.

  3. Usare il codice di autorizzazione per richiedere il token di accesso e il token di aggiornamento. Passare l'URI di callback completo quando si usa l'istanza di OAuthWebAuthCodeGrant per richiedere il token di accesso e il token di aggiornamento.

    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 questo passaggio ha avuto esito positivo, l'applicazione ha le autorizzazioni per gestire gli account Microsoft Advertising dell'utente. Per chiamare le operazioni del servizio API Bing Ads, è necessario inizializzare client del servizio, Service Manager bulk o reporting Service Manager con AuthorizationData che contiene l'istanza di OAuthWebAuthCodeGrant.

    Per altre informazioni, vedere Using AuthorizationData, Using Service Client, Using BulkServiceManager e Using ReportingServiceManager.For more information, see Using AuthorizationData, Using Service Client, Using BulkServiceManager, and Using ReportingServiceManager.

    Nota

    BulkServiceManager e ReportingServiceManager sono disponibili con gli SDK .NET, Java e Python.

  4. Quando si chiamano le operazioni del servizio API Bing Ads con client di servizio, Service Manager bulk o reporting Service Manager, è importante salvare il token di aggiornamento più recente ogni volta che vengono ricevuti nuovi token 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

    Un token di aggiornamento può durare fino a 90 giorni. Indipendentemente da ciò, è consigliabile ricominciare dal passaggio 1 e richiedere il consenso dell'utente se, ad esempio, l'utente dell'account Microsoft ha modificato la password, ha rimosso un dispositivo dall'elenco di dispositivi attendibili o ha rimosso le autorizzazioni per l'autenticazione dell'applicazione per suo conto.

Uso di AuthorizationData

La classe AuthorizationData contiene le proprietà usate da Microsoft Advertising per autorizzare un utente. Le classi Client del servizio, Service Manager bulk e Reporting Service Manager gestiscono automaticamente i campi di intestazione della richiesta comuni, consentendo di specificare una volta le proprietà Authentication, CustomerId, AccountId e DeveloperToken nell'oggetto AuthorizationData per ogni servizio.

Nota

BulkServiceManager e ReportingServiceManager sono disponibili con gli SDK .NET, Java e Python.

Il blocco di codice seguente illustra come creare un'istanza di AuthorizationData e impostare le relative proprietà Authentication, 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>'
)

La proprietà Authentication deve essere impostata su una classe derivata dall'autenticazione, ad esempio OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant o OAuthDesktopMobileImplicitGrant.

Alcuni servizi, ad esempio Gestione clienti, non accettano intestazioni CustomerId e CustomerAccountId , quindi verranno ignorati se sono stati specificati nell'oggetto AuthorizationData .

Uso del client del servizio

È possibile usare un'istanza della classe ServiceClient per chiamare qualsiasi metodo di uno dei servizi Web di Microsoft Advertising. La classe ServiceClient gestisce automaticamente i campi di intestazione della richiesta comuni, consentendo di specificare le proprietà Authentication, CustomerId, AccountId e DeveloperToken nell'oggetto AuthorizationData una volta per ogni servizio.

Consiglio

Se si usa Bulk o Reporting Services, usare bulk Service Manager o reporting Service Manager anziché ServiceClient. Ad esempio, il Service Manager bulk invierà la richiesta di download al servizio bulk, eseguirà il polling del servizio fino al completamento e scaricherà il file nella directory locale specificata nella richiesta. Si risparmierà ancora più tempo perché non è necessario scrivere o analizzare i file di caricamento o risultati.

// 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 si impostano gli elementi di intestazione AuthenticationToken, CustomerId, AccountId o DeveloperToken nel parametro di richiesta, ad esempio GetUserRequest, verranno ignorati. Il client del servizio usa sempre l'oggetto AuthorizationData fornito con l'inizializzazione.

Vedere anche

Sandbox
Esempi di codice API Bing Ads
Indirizzi del servizio Web dell'API Bing Ads