這個範例 Java Web 應用程式會透過您提供的認證提示使用者同意,然後取得已驗證的使用者可以存取的帳戶。
您必須先註冊應用程式,並記下用戶端標識碼 (已註冊的應用程式標識碼) 、客戶端密碼 (已註冊的密碼) ,以及重新導向 URI。 如需註冊應用程式和授權碼授與流程的詳細資訊,請參閱 使用 OAuth 進行驗證。
您也需要生產 開發人員令牌。 您可以依照下面所述逐步建立範例,或從 GitHub 下載更多範例。
注意事項
此範例示範生產環境中的 OAuth 驗證。 如需設定沙箱的相關信息,請參閱 設定沙箱。
Web 應用程式驗證範例 Walk-Through
開啟 Eclipse 開發環境。
透過檔案 -New -Project ->>Maven ->>Maven 專案建立新專案,然後按 [下一步]。
在 [ 新增 Maven 專案 ] 對話框中,確定未選取 [ 建立簡單專案 (略過原型選取) ] 的選項,然後按 [ 下一步]。 您將在下一個步驟中選取 Maven 原型。
在 [ 新增 Maven 專案 ] 對話框中,選取 [Maven Web 應用程式原型],然後按 [ 下一步]。 群組標識符為 org.apache.maven.archetypes,而成品標識符為 maven-archetype-webapp。
在 [ 新增 Maven 專案 ] 對話框中,指定專案的成品參數,然後按兩下 [ 完成]。 例如,您可以將 [群組標識 符] 設定為 com.microsoft.bingads.examples,並將 [ 成品標識 符] 設定為 BingAdsWebApp。
如果 JAVA 建置路徑中還沒有必要的 javax servlet JAR,請將這些 JAR 新增至項目連結庫。 在 [專案總管] 中,以滑鼠右鍵按兩下 BingAdsWebApp 專案,然後按兩下 [ 屬性]。 在 [ 屬性] 對話框中,移至 [ Java 組建路徑 ->連結庫] 索引卷標,按兩下 [ 新增外部 JAR],然後流覽至 {EclipseInstallationPath}/plugins/ ,然後選取 例如 javax.servlet.jsp_2.2.0.v2011112011158 和 javax.servlet_3.0.0.v201112011016。
將 servlet JAR 包含在專案的順序和匯出的專案中。 在 [ Java 組建路徑 ->訂單和導 出] 索引標籤中,按兩下 [ 選取所有 (至少選取 [servlet JAR) ],然後按兩下 [ 完成]。
在專案的 Web 部署元件中包含 servlet JAR。 在 [專案總管] 中,以滑鼠右鍵按兩下 BingAdsWebApp 專案,然後選取 [ 屬性]。 在 [屬性] 對話框中,移至 [部署元件 ->新增],選取 [Java 組建路徑專案],然後按 [下一步]。 選取您在先前步驟中新增的所有 JAR,按兩下 [新增元件指示詞] 對話方塊中的 [完成],然後按兩下 [屬性] 對話框中的 [套用]。
在 [專案總管] 中,以滑鼠右鍵按兩下 pom.xml 檔案,然後選取 [以 ->Text 開啟編輯器] 。 新增 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>在 [專案總管] 中,以滑鼠右鍵按兩下 BingAdsWebApp 專案的 [Web 內容] 資料夾,然後選取 [新增 ->JSP 檔案]。 將檔案 命名index.jsp ,然後按兩下 [ 完成]。
開啟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>應用程式已準備好部署至伺服器。 例如,您可以使用 Azure App 服務 發佈 Web 應用程式。 如需詳細資訊,請 參閱部署 Web 應用程式。 當您啟動應用程式時,預設會提示您Microsoft帳戶認證在生產環境中進行驗證。
部署 Web 應用程式
如果您使用 Microsoft Azure 來部署 Web 應用程式,則需要下列專案。
以 Java 為基礎的 Web 伺服器或應用程式伺服器的散發,例如 Apache Tomcat、GlassFish、JBoss Application Server、Jetty 或 IBM® WebSphere® Application Server 擴充核心。
可從 取得的 Azure 訂用 https://azure.microsoft.com/pricing/purchase-options/帳戶。
您可以選擇性地安裝 Azure Toolkit for Eclipse (,方法是Microsoft Open Technologies) ,並使用 Azure 雲端服務部署 Web 應用程式。 如需詳細資訊,請 參閱安裝適用於 Eclipse 的 Azure 工具組。