逐步解說:Java 中的 Bing 廣告 API Web 應用程式

此範例 Java Web 應用程式會透過您提供的認證提示使用者同意,然後取得經過驗證的使用者可以存取的帳戶。

您必須先註冊應用程式,並記下用戶端識別碼 (登錄的應用程式識別碼) 、用戶端密碼 (登錄的密碼) ,以及重新導向 URI。 如需註冊應用程式和授權碼授與流程的詳細資訊,請參閱 使用 OAuth 驗證。

您也需要生產開發人員 權杖。 您可以如下所述逐步建立範例,或從 GitHub 下載更多範例。

注意事項

此範例示範生產環境中的 OAuth 驗證。 如需設定沙箱的相關資訊,請參閱 設定沙箱。

Web 應用程式驗證範例 Walk-Through

  1. 開啟 Eclipse 開發環境。

  2. 透過 File ->New ->Project ->Maven -Maven Project> 建立新專案,然後按一下 Next。

  3. 在「 新增Maven專案 」對話方塊中,確定未選取「 建立簡單專案 (跳過原型選取) 」選項,然後按一下 「下一步」。 您將在下一個步驟中選取Maven原型。

  4. 在 「新增Maven專案 」對話方塊中,選取Maven Web應用程式原型,然後按一下 「下一步」。 群組識別碼是org.apache.maven.archetypes,而成品識別碼是maven-archetype-webapp。

  5. 在「新增Maven專案」對話方塊中,指定專案的成品參數,然後按一下「完成」。 例如,您可以將 群組識別碼 設定為 com.microsoft.bingads.examples, 並將成品識別碼 設定為 BingAdsWebApp。

  6. 如果必要的 javax servlet JAR 尚未位於 Java 建置路徑中,請將它們新增至專案程式庫。 在 [專案總管] 中,以滑鼠右鍵按一下 BingAdsWebApp 專案,然後按一下 [屬性]。 在 [屬性] 對話方塊中,移至 [Java 建置路徑 ->程式庫] 索引標籤,按一下 [新增外部 JAR],然後瀏覽至 {EclipseInstallationPath}/plugins/,例如,選取 javax.servlet.jsp_2.2.0.v201112011158 和 javax.servlet_3.0.0.v201112011016。

  7. 將 Servlet JAR 包含在專案的訂單和匯出項目中。 在「Java 建置路徑 ->順序及匯出」頁籤中,按一下「全選」 (至少選取 Servlet JAR) ,然後按一下「完成」。

  8. 在專案的 Web 部署組件中包括 Servlet JAR。 在 [專案總管] 中,以滑鼠右鍵按一下 BingAdsWebApp 專案,然後選取 [屬性]。 在 「內容」 對話方塊中,移至 「部署組件 」->「新增」,選取「 Java 建置路徑項目」,然後按一下 「下一步」。 選取您在先前步驟中新增的所有 JAR,按一下 [新增組件指令] 對話方塊中的 [完成],然後按一下 [屬性] 對話方塊中的 [套用]。

  9. 在 專案總管中,以滑鼠右鍵按一下 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 服務發佈 Web 應用程式。 如需詳細資訊,請參閱 部署 Web 應用程式。 啟動應用程式時,系統預設會提示您輸入 Microsoft 帳戶認證,以在生產環境中進行驗證。

部署 Web 應用程式

如果您使用 Microsoft Azure 部署 Web 應用程式,則需要下列項目。

  • Java 型 Web 伺服器或應用程式伺服器的發行版,例如 Apache Tomcat、GlassFish、JBoss Application Server、Jetty 或 IBM® WebSphere® Application Server Liberty Core。

  • 可從 https://azure.microsoft.com/pricing/purchase-options/取得的 Azure 訂閱。

  • 您可以選擇性地安裝 Microsoft Open Technologies (的 Azure Toolkit for Eclipse 的) ,並使用 Azure 雲端服務部署 Web 應用程式。 如需詳細資訊,請參閱安裝適用於 Eclipse 的 Azure 工具組。

另請參閱

沙箱
Bing Ads API 程式碼範例
Bing 廣告 API Web 服務位址