次の方法で共有


SDK を使用した認証

この記事では、Bing広告 SDK での認証と基本的なサービス呼び出しについて説明します。

サンドボックスの構成

SDK では、既定で運用環境が使用されます。 .NET SDK と Java SDK を使用すると、グローバル構成でサンドボックスに変更できます。 グローバル構成は PHP と Python SDK では使用できませんが、グローバル構成やその他のカスタム ソリューションを作成できます。

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

また、個々の Bulk Service ManagerService ClientReporting Service Manager インスタンスの API 環境パラメーターを設定することもできます。 apiEnvironment を設定すると、指定されたサービス クライアント インスタンスまたはインスタンスに対してのみグローバル設定がオーバーライドされます。 特に意図しない限り、混在する環境のセットを誤って構成しないように注意する必要があります。

注:

BulkServiceManagerReportingServiceManager は、.NET、Java、Python SDK で使用できます。

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 の使用

Bing広告 SDK では、OAuth 2.0 承認フレームワークで詳細に定義されている標準 の OAuth 2.0 フローがサポートされています。SDK の OAuth クラスは、承認とリダイレクト URI の書式設定、要求ヘッダーの設定、リダイレクト トラフィックと応答ストリームの解析など、低レベルのユーザー承認の詳細を抽象化します。 Bing Ads .NET SDK で OAuth を使用するには、AuthorizationData オブジェクトの Authentication プロパティを、OAuthWebAuthCodeGrant、OAuthDesktopMobileAuthCodeGrantOAuthDesktopMobileImplicitGrant などの認証派生クラスに設定する必要があります。

繰り返し認証または長期認証の場合は、アクセス トークンを取得するための承認コード付与フローに従う必要があります。 次の手順は、承認コード付与フローに従います。 アプリケーションの登録と承認コード付与フローの詳細については、「 OAuth による認証」を参照してください。

  1. OAuthWebAuthCodeGrant のインスタンスを作成します。このインスタンスは、Microsoft アカウント ユーザーの承認を管理するために使用されます。 クライアント ID (登録済みアプリケーション ID)、クライアント シークレット (登録済みパスワード)、リダイレクト URI は、アプリケーションの登録時に構成された値に置き換えます。

    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. Web ブラウザー コントロールを使用して Microsoft アカウント承認エンドポイントに接続して、ユーザーの同意を要求します。 前の手順で作成した OAuthWebAuthCodeGrant インスタンスの GetAuthorizationEndpoint メソッドを呼び出します。

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

    ユーザーは、Microsoft アカウント承認 Web ブラウザー コントロールを通じて、アプリケーションが Microsoft Advertising アカウントを管理するためのアクセス許可を付与するように求められます。

    承認サービスは、リダイレクト URI を使用してアプリケーションに呼び戻します。これには、ユーザーが Microsoft Advertising アカウントの管理をアプリケーションに承認した場合の承認コードが含まれます。 たとえば、ユーザーがアプリケーションに Microsoft Advertising アカウントを管理するためのアクセス許可を付与した場合、コールバック URL には次のような承認コードが含まれます https://contoso.com/redirect/?code=CODE&。state=ClientStateGoesHere。 ユーザーが Microsoft Advertising アカウントを管理するためのアクセス許可をアプリケーションに付与した場合は、次の手順ですぐにコードを使用する必要があります。 承認コードの短い期間 (約 5 分) は変更される可能性があります。

    ユーザーが Microsoft Advertising アカウントを管理するためのアプリケーションのアクセス許可を拒否した場合、コールバック URI には、 REDIRECTURI?error=access_denied&error_description=ERROR_DESCRIPTION&state=ClientStateGoesHere というエラーとエラーの説明フィールドが含まれます。

  3. アクセス トークンと更新トークンを要求するには、承認コードを使用します。 OAuthWebAuthCodeGrant インスタンスを使用してアクセス トークンと更新トークンを要求する場合は、完全なコールバック URI を渡します。

    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
    

    この手順が成功した場合、アプリケーションにはユーザーの Microsoft Advertising アカウントを管理するためのアクセス許可があります。 Bing Ads API サービス操作を呼び出すには、OAuthWebAuthCodeGrant インスタンスを含む AuthorizationData を使用して、Service ClientBulk Service ManagerReporting Service Managerのいずれかを初期化する必要があります。

    詳細については、「 AuthorizationData の使用」、「 サービス クライアントの使用」、「 BulkServiceManager の使用」、「 ReportingServiceManager の使用」を参照してください。

    注:

    BulkServiceManagerReportingServiceManager は、.NET、Java、Python SDK で使用できます。

  4. Service ClientBulk Service ManagerReporting Service Manager を使用して Bing Ads API サービス操作を呼び出す場合は、新しい 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)
    

    重要

    更新トークンの有効期限は最大 90 日間です。 いずれの場合も、手順 1 からやり直し、Microsoft アカウント ユーザーがパスワードを変更した場合、信頼されたデバイスの一覧からデバイスを削除した場合、またはアプリケーションが自分の代わりに認証するためのアクセス許可を削除した場合は、ユーザーの同意を要求する必要があります。

AuthorizationData の使用

AuthorizationData クラスには、Microsoft Advertising がユーザーの承認に使用するプロパティが含まれています。 Service ClientBulk Service ManagerReporting Service Manager クラスは、一般的な要求ヘッダー フィールドを処理するため、AuthorizationData オブジェクトの AuthenticationCustomerIdAccountIdDeveloperToken の各プロパティをサービスごとに 1 回指定できます。

注:

BulkServiceManagerReportingServiceManager は、.NET、Java、Python SDK で使用できます。

次のコード ブロックは 、AuthorizationData のインスタンスを作成し、 その AuthenticationCustomerIdAccountIdDeveloperToken プロパティを設定する方法を 示しています。

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 プロパティは、OAuthWebAuthCodeGrantOAuthDesktopMobileAuthCodeGrant、OAuthDesktopMobileImplicitGrant などの認証派生クラスに設定する必要があります。

Customer Management などの一部のサービスは CustomerId ヘッダーと CustomerAccountId ヘッダーを 受け入れないため、 AuthorizationData オブジェクトで指定した場合は無視されます。

サービス クライアントの使用

ServiceClient クラスのインスタンスを使用して、Microsoft Advertising Web サービスのいずれかのメソッドを呼び出すことができます。 ServiceClient クラスは一般的な要求ヘッダー フィールドを処理するため、AuthorizationData オブジェクトの AuthenticationCustomerIdAccountIdDeveloperToken の各プロパティをサービスごとに 1 回指定できます。

ヒント

一括またはレポート サービスを使用している場合は、ServiceClient の代わりに一括Service Managerまたは Reporting Service Managerを使用します。 たとえば、一括Service Managerは一括サービスにダウンロード要求を送信し、完了するまでサービスをポーリングし、要求で指定したローカル ディレクトリにファイルをダウンロードします。 アップロードファイルや結果ファイルを書き込んだり解析したりする必要がないため、さらに時間を節約できます。

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

重要

要求パラメーターに AuthenticationTokenCustomerIdAccountId、または DeveloperToken ヘッダー要素 ( GetUserRequest など) を設定した場合、それらは無視されます。 サービス クライアントでは 、初期化時に提供される AuthorizationData が常に使用されます。

関連項目

サンドボックス
Bing Ads API のコード例
Bing 広告 API Web サービス アドレス