Aracılığıyla paylaş


SDK'larla Kimlik Doğrulaması

Bu makale, Bing Ads SDK'ları ile kimlik doğrulaması ve temel hizmet çağrılarını kapsar.

Korumalı Alanı Yapılandırma

SDK varsayılan olarak üretim ortamını kullanır. .NET ve Java SDK'ları ile bunu genel bir yapılandırmayla korumalı alan olarak değiştirebilirsiniz. Genel yapılandırma PHP ve Python SDK'larında kullanılamasa da genel bir yapılandırma veya başka bir özel çözüm oluşturabilirsiniz.

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

Ayrıca tek tek Toplu Service Manager, Hizmet İstemcisi ve Raporlama Service Manager örneklerinin API ortam parametresini de ayarlayabilirsiniz. apiEnvironment ayarı yalnızca belirtilen hizmet istemci örneği veya örnekleri için genel ayarı geçersiz kılar. Aksi amaçlanmadığı sürece, yanlışlıkla karma bir ortam kümesi yapılandırmamaya dikkat etmelisiniz.

Not

BulkServiceManager ve ReportingServiceManager .NET, Java ve Python SDK'larıyla kullanılabilir.

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',
)

OAuth kullanma

Bing Ads SDK'ları, OAuth 2.0 Yetkilendirme Çerçevesi'nde ayrıntılı olarak açıklandığı gibi standart OAuth 2.0 akışını destekler. SDK'daki OAuth sınıfları, yetkilendirme ve yeniden yönlendirme URI'lerini biçimlendirme, istek üst bilgilerini ayarlama ve yeniden yönlendirme trafiğini ve yanıt akışını ayrıştırma gibi düşük düzey kullanıcı yetkilendirme ayrıntılarını soyutlar. Bing Ads .NET SDK'sı ile OAuth kullanmak için AuthorizationData nesnenizin Authentication özelliği OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant veya OAuthDesktopMobileImplicitGrant gibi Authentication türetilmiş bir sınıfa ayarlanmalıdır.

Yineleme veya uzun süreli kimlik doğrulaması için, erişim belirteci almak için yetkilendirme kodu verme akışını izlemeniz gerekir. Aşağıdaki adımlar yetkilendirme kodu verme akışını izler. Bir uygulamayı kaydetme ve yetkilendirme kodu verme akışı hakkında daha fazla bilgi için bkz. OAuth ile kimlik doğrulaması.

  1. Microsoft Hesabı kullanıcı yetkilendirmesini yönetmek için kullanılacak bir OAuthWebAuthCodeGrant örneği oluşturun. İstemci kimliğini (kayıtlı uygulama kimliği), istemci gizli anahtarını (kayıtlı parola) ve yeniden yönlendirme URI'sini uygulamanızı kaydettiğinizde yapılandırılan değerlerle değiştirin.

    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. Bir web tarayıcısı denetimi aracılığıyla Microsoft Hesabı yetkilendirme uç noktasına bağlanarak kullanıcı onayı isteyin. Önceki adımda oluşturduğunuz OAuthWebAuthCodeGrant örneğinin GetAuthorizationEndpoint yöntemini çağırın.

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

    Kullanıcıdan Microsoft Hesabı yetkilendirme web tarayıcısı denetimi aracılığıyla uygulamanızın Microsoft Advertising hesaplarını yönetmesi için izin vermesi istenir.

    Yetkilendirme hizmeti, yeniden yönlendirme URI'si ile uygulamanıza geri çağrıda bulunur ve kullanıcı uygulamanızı Microsoft Advertising hesaplarını yönetmesi için yetkilendirdiyse bir yetkilendirme kodu içerir. Örneğin geri çağırma URL'si, kullanıcı uygulamanızın Microsoft Advertising hesaplarını yönetmesine izin verdiyse aşağıdaki gibi bir yetkilendirme kodu içerir: https://contoso.com/redirect/?code=CODE& state=ClientStateGoesHere. Kullanıcı uygulamanıza Microsoft Advertising hesaplarını yönetmek için izin verdiyse, sonraki adımda kodu hemen kullanmanız gerekir. Yetkilendirme kodunun kısa süresi (yaklaşık 5 dakika) değiştirilebilir.

    Kullanıcı Microsoft Advertising hesaplarını yönetmek için uygulama izinlerinizi reddettiyse, geri çağırma URI'sinde şu şekilde bir hata ve hata açıklaması alanı bulunur: REDIRECTURI?error=access_denied&error_description=ERROR_DESCRIPTION&state=ClientStateGoesHere.

  3. Erişim belirtecini istemek ve belirteci yenilemek için yetkilendirme kodunu kullanın. Erişim belirtecini istemek ve belirteci yenilemek için OAuthWebAuthCodeGrant örneğini kullanırken tam geri çağırma URI'sini geçirin.

    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
    

    Bu adım başarılı olursa, uygulamanızın kullanıcının Microsoft Advertising hesaplarını yönetme izinleri vardır. Bing Ads API'si hizmet işlemlerini çağırmak için OAuthWebAuthCodeGrant örneğinizi içeren AuthorizationData ile Hizmet İstemcisi, Toplu Service Manager veya Raporlama Service Manager başlatmanız gerekir.

    Daha fazla bilgi için bkz. AuthorizationData Kullanma, Hizmet İstemcisi Kullanma, BulkServiceManager Kullanma ve ReportingServiceManager Kullanma.

    Not

    BulkServiceManager ve ReportingServiceManager .NET, Java ve Python SDK'larıyla kullanılabilir.

  4. Hizmet İstemcisi, Toplu Service Manager veya Raporlama Service Manager ile Bing Ads API hizmet işlemlerini çağırırken, yeni OAuth belirteçleri alındığında en son yenileme belirtecinin kaydedilmesi önemlidir.

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

    Önemli

    Yenileme belirteci 90 güne kadar sürebilir. Ne olursa olsun, 1. Adım'dan yeniden başlamayı ve örneğin Microsoft Hesabı kullanıcısının parolasını değiştirmesi, bir cihazı güvenilir cihazlar listesinden kaldırması veya uygulamanızın kendi adına kimlik doğrulaması için izinlerini kaldırması durumunda kullanıcı onayı istemeniz gerekir.

AuthorizationData kullanma

AuthorizationData sınıfı, Microsoft Advertising'in bir kullanıcıyı yetkilendirmek için kullandığı özellikleri içerir. Hizmet İstemcisi, Toplu Service Manager ve Raporlama Service Manager sınıfları yaygın istek üst bilgisi alanlarını sizin için işler ve her hizmet için AuthorizationData nesnesinde Authentication, CustomerId, AccountId ve DeveloperToken özelliklerini bir kez belirtmenize olanak sağlar.

Not

BulkServiceManager ve ReportingServiceManager .NET, Java ve Python SDK'larıyla kullanılabilir.

Aşağıdaki kod bloğunda AuthorizationData örneğinin nasıl oluşturulacağı ve Authentication, CustomerId, AccountId ve DeveloperToken özelliklerinin nasıl ayarlanacağı gösterilmektedir.

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

Authentication özelliği, OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant veya OAuthDesktopMobileImplicitGrant gibi Authentication türetilmiş bir sınıfa ayarlanmalıdır.

Müşteri Yönetimi gibi bazı hizmetler CustomerId ve CustomerAccountId üst bilgilerini kabul etmez, bu nedenle Bunları AuthorizationData nesnesinde belirttiyseniz bunlar yoksayılır.

Hizmet İstemcisi Kullanma

Microsoft Advertising web hizmetlerinden birinin yöntemlerini çağırmak için ServiceClient sınıfının bir örneğini kullanabilirsiniz. ServiceClient sınıfı ortak istek üst bilgisi alanlarını sizin için işler ve her hizmet için AuthorizationData nesnesinde Authentication, CustomerId, AccountId ve DeveloperToken özelliklerini bir kez belirtmeye olanak sağlar.

İpucu

Toplu veya Raporlama hizmetlerini kullanıyorsanız ServiceClient yerine Toplu Service Manager veya Raporlama Service Manager kullanın. Örneğin Toplu Service Manager indirme isteğinizi toplu hizmete gönderir, tamamlanana kadar hizmeti yoklar ve dosyayı istekte belirttiğiniz yerel dizine indirir. Karşıya yükleme veya sonuç dosyalarını yazmak veya ayrıştırmak zorunda kalmadığınızdan daha da fazla zaman kazanacaksınız.

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

Önemli

İstek parametresinde AuthenticationToken, CustomerId, AccountId veya DeveloperToken üst bilgi öğelerini ayarlarsanız (örneğin, GetUserRequest) bunlar yoksayılır. Hizmet İstemcisi her zaman, başlatılmasıyla birlikte sağlanan AuthorizationData'sını kullanır.

Ayrıca Bkz

Sandbox
Bing Ads API Kod Örnekleri
Bing Ads API Web Hizmeti Adresleri