チュートリアル: Java での Bing Ads API Web アプリケーション

このJavaWebアプリケーションの例では、指定した資格情報を使用してユーザーの同意を求め、認証されたユーザーがアクセスできるアカウントを取得します。

最初にアプリケーションを登録し、クライアント ID (登録済みアプリケーション ID)、クライアント シークレット (登録済みパスワード)、およびリダイレクト URI をメモする必要があります。 アプリケーションの登録と認証コード付与フローの詳細については、「 OAuth による認証」を参照してください。

また、運用 開発者トークンも必要です。 以下で説明するように段階的に例を作成するか、 GitHub からさらに例をダウンロードできます。

注:

この例では、実稼働での OAuth 認証を示します。 サンドボックスの構成の詳細については、「 サンドボックスの構成」を参照してください。

Web アプリケーション認証の例 Walk-Through

  1. Eclipse 開発環境を開きます。

  2. [ファイル] #>新規 ->プロジェクト ->Maven ->Maven プロジェクト から新しいプロジェクトを作成し、[次へ] をクリックします。

  3. 「新しい Maven プロジェクト」ダイアログで、「単純なプロジェクトを作成する (アーキタイプの選択をスキップする)」オプションが選択されていないことを確認し、「次へ」をクリックします。 次のステップで Maven アーキタイプを選択します。

  4. [ 新しい Maven プロジェクト ] ダイアログで、Maven Web アプリのアーキタイプを選択し、[ 次へ] をクリックします。 グループ ID は org.apache.maven.archetypes で、アーティファクト ID は maven-archetype-webapp です。

  5. 「 新規Maven プロジェクト」ダイアログで、プロジェクトのアーティファクト・パラメーターを指定し、「 完了」をクリックします。 たとえば、 グループ ID を com.microsoft.bingads.examples に、 成果物 ID を BingAdsWebApp に設定できます。

  6. 必要な javax サーブレット JAR が Java ビルドパスにまだない場合は、プロジェクトライブラリに追加します。 プロジェクト エクスプローラーで、BingAdsWebApp プロジェクトを右クリックし、[プロパティ] をクリックします。 [プロパティ] ダイアログで、[Java ビルド パス] > [ライブラリ] タブに移動し、[外部 JAR の追加] をクリックし、[{EclipseInstallationPath}/plugins/] に移動して、たとえば javax.servlet.jsp_2.2.0.v201112011158 とjavax.servlet_3.0.0.v201112011016 の両方を選択します。

  7. サーブレット JAR をプロジェクトの順序とエクスポートされたエントリーに含めます。 「Java ビルド・パス - >順序およびエクスポート」タブで、「すべて選択」(少なくともサーブレット JAR を選択し)、「完了」をクリックします。

  8. プロジェクトの Web デプロイメント・アセンブリーにサーブレット JAR を含めます。 プロジェクト エクスプローラーで、BingAdsWebApp プロジェクトを右クリックし、[プロパティ] を選択します。 「 プロパティ」 ダイアログで、「 デプロイメント・アセンブリ」 ->「追加」に移動し、「 Java ビルド・パス・エントリ」を選択して、「 次へ」をクリックします。 前の手順で追加したすべての JAR を選択し、[新しいアセンブリ ディレクティブ] ダイアログで [完了] をクリックし、[プロパティ] ダイアログで [適用] をクリックします。

  9. Project エクスプローラー で、pom.xml ファイルを右クリックし、[プログラムから開く] -[>テキスト エディター] を選択します。 次の例に示すように、 com.microsoft.bingads 依存関係を追加し、pom.xml を保存します。

    注:

    最新の SDK 依存関係バージョンの詳細については、 Bing Ads Java SDK GitHub README.md を参照してください。

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.microsoft.bingads.examples</groupId>
      <artifactId>BingAdsWebApp</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>BingAdsWebApp Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>com.microsoft.bingads</groupId>
          <artifactId>microsoft.bingads</artifactId>
          <version>13.0.17</version>
        </dependency>
      </dependencies>
      <build>
        <finalName>BingAdsWebApp</finalName>
      </build>
    </project>
    
  10. プロジェクト エクスプローラー で、BingAdsWebApp プロジェクトの [Web コンテンツ] フォルダーを右クリックし、[新規作成] ->JSP ファイルを選択します。 ファイルに index.jsp という名前 を付け、[ 完了] をクリックします。

  11. Index.jsp ファイルを開き、その内容を次のコード ブロックに置き換えます。 アプリケーションの登録時にプロビジョニングされた ClientId、ClientSecret、および RedirectionUri を使用して、以下のサンプルを編集する必要があります。 また、運用 開発者トークンを使用して例を編集する必要があります。 サンドボックスを使用している場合は、「 サンドボックスの構成」の手順に従う必要があります。

    <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
    <%@ page import="java.net.URL" %>
    <%@ page import="com.microsoft.bingads.*" %>
    <%@ page import="com.microsoft.bingads.v13.customermanagement.*" %>
    
    <%! 
    	static AuthorizationData authorizationData;
    	static ServiceClient<ICustomerManagementService> CustomerService; 
    
    	private static java.lang.String DeveloperToken = "<DeveloperTokenGoesHere>";
    	private static java.lang.String ClientId = "<ClientIdGoesHere>";
    	private static java.lang.String ClientSecret = "<ClientSecretGoesHere>";
        private static java.lang.String RedirectUri = "<RedirectUriGoesHere>";
    
    	static long accountsCount = 0;
     %>
    
     <%! 
    	//Gets a User object by the specified Microsoft Advertising user identifier.
    
    	 static User getUser(java.lang.Long userId) throws Exception
    	 {
    	     GetUserRequest request = new GetUserRequest();
    
    	     request.setUserId(userId);
    
    	     return CustomerService.getService().getUser(request).getUser();
    	 }
    
    	 // Searches by UserId for accounts that the user can manage.
    
    	 static ArrayOfAdvertiserAccount searchAccountsByUserId(java.lang.Long userId) throws AdApiFaultDetail_Exception, ApiFault_Exception{       
    
    	     ArrayOfPredicate predicates = new ArrayOfPredicate();
    	     Predicate predicate = new Predicate();
    	     predicate.setField("UserId");
    	     predicate.setOperator(PredicateOperator.EQUALS);
    	     predicate.setValue("" + userId);
    	     predicates.getPredicates().add(predicate);
    
    	     Paging paging = new Paging();
    	     paging.setIndex(0);
    	     paging.setSize(10);
    
    	     final SearchAccountsRequest searchAccountsRequest = new SearchAccountsRequest();
    	     searchAccountsRequest.setPredicates(predicates);
    	     searchAccountsRequest.setPageInfo(paging);
    
    	     return CustomerService.getService().searchAccounts(searchAccountsRequest).getAccounts();
    	 }
    
    	 // Outputs the account and parent customer identifiers for the specified accounts.
    
    	 static void printAccounts(ArrayOfAdvertiserAccount accounts) throws Exception
    	 {
    	     for (Account account : accounts.getAccounts())
    	     {
    	     	System.out.printf("AccountId: %d\n", account.getId());
    	     	System.out.printf("CustomerId: %d\n", account.getParentCustomerId());
    	     }
    	 }
     %>
    
    <%
    	// Main execution  
    
      try {
    
          	OAuthWebAuthCodeGrant oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(
    			ClientId, 
    			ClientSecret, 
    			new URL(RedirectUri)
            );
    
          	oAuthWebAuthCodeGrant.setNewTokensListener(new NewOAuthTokensReceivedListener() {
                @Override
                public void onNewOAuthTokensReceived(OAuthTokens newTokens) {
                       java.lang.String newAccessToken = newTokens.getAccessToken();
                       java.lang.String newRefreshToken = newTokens.getRefreshToken();
                       java.lang.String refreshTime = new java.text.SimpleDateFormat(
                    		   "MM/dd/yyyy HH:mm:ss").format(new java.util.Date());
    
                       System.out.printf("Token refresh time: %s\n", refreshTime);
                       System.out.printf("New access token: %s\n", newAccessToken);
                       System.out.printf("You should securely store this new refresh token: %s\n", newRefreshToken);
    
                }
            });
    
          	if (authorizationData == null) {
              	if (request.getParameter("code") == null) {				
    				URL authorizationUrl = oAuthWebAuthCodeGrant.getAuthorizationEndpoint();
    				response.sendRedirect(authorizationUrl.toString());
    				return;
    			} else {		
    				OAuthTokens tokens = oAuthWebAuthCodeGrant.requestAccessAndRefreshTokens(
    					new URL(request.getRequestURL() + "?" + request.getQueryString()));
    
    				authorizationData = new AuthorizationData();
    				authorizationData.setDeveloperToken(DeveloperToken);
    				authorizationData.setAuthentication(oAuthWebAuthCodeGrant);
    			}
    		}
    
    		CustomerService = new ServiceClient<ICustomerManagementService>(
    			authorizationData, 
    			ICustomerManagementService.class);
    
    		User user = getUser(null);
    
          // Search for the accounts that the user can access.
    
          ArrayOfAdvertiserAccount accounts = searchAccountsByUserId(user.getId());
          accountsCount = accounts.getAccounts().size();
    
          System.out.println("The user can access the following Microsoft Advertising accounts: \n");
          printAccounts(accounts);
    
    	// Customer Management service operations can throw AdApiFaultDetail.
        } catch (AdApiFaultDetail_Exception ex) {
            System.out.println("The operation failed with the following faults:\n");
    
            for (AdApiError error : ex.getFaultInfo().getErrors().getAdApiErrors())
            {
                System.out.printf("AdApiError\n");
                System.out.printf("Code: %d\nError Code: %s\nMessage: %s\n\n", 
                    error.getCode(), error.getErrorCode(), error.getMessage()
                );
            }
    
        // Customer Management service operations can throw ApiFault.
        } catch (ApiFault_Exception ex) {
            System.out.println("The operation failed with the following faults:\n");
    
            for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors())
            {
                System.out.printf("OperationError\n");
                System.out.printf("Code: %d\nMessage: %s\n\n", 
                    error.getCode(), error.getMessage()
                );
            }
        } catch (Exception ex) {
            // Ignore fault exceptions that we already caught.
    
            if (ex.getCause() instanceof AdApiFaultDetail_Exception ||
                ex.getCause() instanceof ApiFault_Exception )
            {
                ;
            }
            else
            {
                System.out.println("Error encountered: ");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }	
    %>
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <title>Microsoft Advertising Web Application Example</title>
        <link rel="stylesheet" href="styles/styles.css" type="text/css" media="screen">
    </head>
    <body>
        <div id="content" class="container">
        	<div>
        		<br/>   		    		
        		<b>You have <%= accountsCount %> accounts</b>    		
    
        	</div> 
        </div>
    </body>
    </html>
    
  12. アプリケーションをサーバーにデプロイする準備ができました。 たとえば、Azure App Service を使用して Web アプリを公開できます。 詳細については、「 Web アプリケーションの展開」を参照してください。 アプリケーションを起動すると、運用環境での認証を行うために、既定で Microsoft アカウントの資格情報を入力するよう求められます。

Web アプリケーションの展開

Microsoft Azure を使用して Web アプリケーションをデプロイする場合は、次のものが必要です。

  • Apache Tomcat、GlassFish、JBoss Application Server、Jetty、IBM® WebSphere® Application Server Liberty Core などの Java ベースの Web サーバーまたはアプリケーション・サーバーのディストリビューション。

  • https://azure.microsoft.com/pricing/purchase-options/ から取得できる Azure サブスクリプション。

  • 必要に応じて、(Microsoft Open Technologies による) Azure Toolkit for Eclipse をインストールし、Azure クラウド サービスを使用して Web アプリケーションをデプロイできます。 詳細については、「Azure Toolkit for Eclipse のインストール」を参照してください。

関連項目

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