Authentification avec les Kits de développement logiciel (SDK)

Cet article traite de l’authentification et des appels de service de base avec les Kits de développement logiciel (SDK) Bing Ads.

Configuration du bac à sable

Le Kit de développement logiciel (SDK) utilise l’environnement de production par défaut. Avec les sdk .NET et Java, vous pouvez le remplacer par un bac à sable avec une configuration globale. Alors que la configuration globale n’est pas disponible avec les SDK PHP et Python, vous pouvez créer une configuration globale ou une autre solution personnalisée.

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

Vous pouvez également définir le paramètre d’environnement d’API des instances de Service Manager de Service Manager en bloc, de client de service et de création de rapports. La définition d’apiEnvironment remplace le paramètre global uniquement pour le client de service spécifié instance ou les instances. Sauf indication contraire, vous devez veiller à ne pas configurer par inadvertance un ensemble mixte d’environnements.

Remarque

BulkServiceManager et ReportingServiceManager sont disponibles avec les sdk .NET, Java et 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',
)

Utilisation d’OAuth

Les Kits de développement logiciel (SDK) Bing Ads prennent en charge le flux OAuth 2.0 standard, tel que défini en détail dans the OAuth 2.0 Authorization Framework. Les classes OAuth dans le Kit de développement logiciel (SDK) abstraitnt les détails d’autorisation utilisateur de bas niveau, tels que la mise en forme des URI d’autorisation et de redirection, la définition des en-têtes de requête et l’analyse du trafic de redirection et du flux de réponse. Pour utiliser OAuth avec le Kit de développement logiciel (SDK) Bing Ads .NET, la propriété Authentication de votre objet AuthorizationData doit être définie sur une classe dérivée de Authentication telle que OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant ou OAuthDesktopMobileImplicitGrant.

Pour une authentification répétée ou à long terme, vous devez suivre le flux d’octroi du code d’autorisation pour obtenir un jeton d’accès. Les étapes ci-dessous suivent le flux d’octroi du code d’autorisation. Pour plus d’informations sur l’inscription d’une application et le flux d’octroi du code d’autorisation, consultez Authentification avec OAuth.

  1. Créez un instance de OAuthWebAuthCodeGrant, qui sera utilisé pour gérer l’autorisation utilisateur du compte Microsoft. Remplacez l’ID client (ID d’application inscrit), la clé secrète client (mot de passe inscrit) et l’URI de redirection par les valeurs configurées lors de l’inscription de votre application.

    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. Demandez le consentement de l’utilisateur en vous connectant au point de terminaison d’autorisation du compte Microsoft via un contrôle de navigateur web. Appelez la méthode GetAuthorizationEndpoint de la instance OAuthWebAuthCodeGrant que vous avez créée à l’étape précédente.

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

    L’utilisateur sera invité par le biais du contrôle de navigateur web d’autorisation de compte Microsoft à accorder des autorisations pour que votre application gère ses comptes Microsoft Advertising.

    Le service d’autorisation rappelle à votre application avec l’URI de redirection, qui inclut un code d’autorisation si l’utilisateur a autorisé votre application à gérer ses comptes Microsoft Advertising. Par exemple, l’URL de rappel inclut un code d’autorisation comme suit si l’utilisateur a accordé des autorisations à votre application pour gérer ses comptes Microsoft Advertising : https://contoso.com/redirect/?code=CODE& state=ClientStateGoesHere. Si l’utilisateur a accordé à votre application des autorisations pour gérer ses comptes Microsoft Advertising, vous devez utiliser le code immédiatement à l’étape suivante. La courte durée du code d’autorisation, environ 5 minutes, est susceptible d’être modifiée.

    Si l’utilisateur a refusé les autorisations de votre application pour gérer ses comptes Microsoft Advertising, l’URI de rappel inclut un champ de description d’erreur et d’erreur comme suit : REDIRECTURI ?error=access_denied&error_description=ERROR_DESCRIPTION&state=ClientStateGoesHere.

  3. Utilisez le code d’autorisation pour demander le jeton d’accès et le jeton d’actualisation. Transmettez l’URI de rappel complet lors de l’utilisation de la instance OAuthWebAuthCodeGrant pour demander le jeton d’accès et le jeton d’actualisation.

    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
    

    Si cette étape a réussi, votre application dispose des autorisations nécessaires pour gérer les comptes Microsoft Advertising de l’utilisateur. Pour appeler les opérations du service d’API Bing Ads, vous devez initialiser client de service, Service Manager en bloc ou création de rapports Service Manager avec AuthorizationData qui contient votre instance OAuthWebAuthCodeGrant.

    Pour plus d’informations, consultez Using AuthorizationData, Using Service Client, Using BulkServiceManager et Using ReportingServiceManager.

    Remarque

    BulkServiceManager et ReportingServiceManager sont disponibles avec les sdk .NET, Java et Python.

  4. Lors de l’appel d’opérations du service d’API Bing Ads avec Client de service, Service Manager en bloc ou Reporting Service Manager, il est important d’enregistrer le jeton d’actualisation le plus récent chaque fois que de nouveaux jetons OAuth sont reçus.

    // 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 jeton d’actualisation peut durer jusqu’à 90 jours. Quoi qu’il en soit, vous devez vous attendre à recommencer à partir de l’étape 1 et demander le consentement de l’utilisateur si, par exemple, l’utilisateur du compte Microsoft a modifié son mot de passe, supprimé un appareil de sa liste d’appareils approuvés ou supprimé les autorisations permettant à votre application de s’authentifier en son nom.

Utilisation d’AuthorizationData

La classe AuthorizationData contient les propriétés que Microsoft Advertising utilise pour autoriser un utilisateur. Les classes Service Client, Bulk Service Manager et Reporting Service Manager gèrent les champs d’en-tête de requête courants pour vous, ce qui vous permet de spécifier les propriétés Authentication, CustomerId, AccountId et DeveloperToken dans l’objet AuthorizationData une fois pour chaque service.

Remarque

BulkServiceManager et ReportingServiceManager sont disponibles avec les sdk .NET, Java et Python.

Le bloc de code suivant montre comment créer un instance d’AuthorizationData et définir ses propriétés Authentication, CustomerId, AccountId et 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 propriété Authentication doit être définie sur une classe dérivée de l’authentification telle que OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant ou OAuthDesktopMobileImplicitGrant.

Certains services tels que Gestion des clients n’acceptent pas les en-têtes CustomerId et CustomerAccountId . Ils seront donc ignorés si vous les avez spécifiés dans l’objet AuthorizationData .

Utilisation du client de service

Vous pouvez utiliser un instance de la classe ServiceClient pour appeler n’importe quelle méthode de l’un des services web Microsoft Advertising. La classe ServiceClient gère les champs d’en-tête de requête courants pour vous, ce qui vous permet de spécifier les propriétés Authentication, CustomerId, AccountId et DeveloperToken dans l’objet AuthorizationData une fois pour chaque service.

Conseil

Si vous utilisez les services en bloc ou Reporting Services, utilisez l’Service Manager de Service Manager en bloc ou reporting au lieu de ServiceClient. Par exemple, le Service Manager en bloc envoie votre demande de téléchargement au service en bloc, interroge le service jusqu’à ce qu’il soit terminé et télécharge le fichier dans le répertoire local que vous avez spécifié dans la demande. Vous gagnerez encore plus de temps, car vous n’avez pas besoin d’écrire ou d’analyser les fichiers de chargement ou de résultats.

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

Si vous définissez les éléments d’en-tête AuthenticationToken, CustomerId, AccountId ou DeveloperToken dans le paramètre de requête, par exemple , GetUserRequest, ils seront ignorés. Le client de service utilise toujours l’objet AuthorizationData fourni avec son initialisation.

Voir aussi

Bac à sable
Exemples de code de l’API Bing Ads
Adresses du service web de l’API Bing Ads