บทสรุป: แอปพลิเคชันเว็บ Bing Ads API ใน Java

แอปพลิเคชันบนเว็บ Java ตัวอย่างนี้พร้อมท์เพื่อขอความยินยอมจากผู้ใช้ผ่านข้อมูลประจําตัวที่คุณให้ไว้ จากนั้นรับบัญชีที่ผู้ใช้ที่ได้รับการรับรองความถูกต้องสามารถเข้าถึงได้

คุณต้องลงทะเบียนแอปพลิเคชันก่อนและจดบันทึก ID ไคลเอ็นต์ (ID แอปพลิเคชันที่ลงทะเบียน) ความลับของไคลเอ็นต์ (รหัสผ่านที่ลงทะเบียน) และ URI การเปลี่ยนเส้นทาง สําหรับรายละเอียดเพิ่มเติมเกี่ยวกับการลงทะเบียนแอปพลิเคชันและขั้นตอนการให้รหัสการตรวจสอบ ให้ดู การรับรองความถูกต้องด้วย OAuth

คุณจะต้องมี โทเค็นนักพัฒนาการผลิตของคุณ คุณสามารถสร้างตัวอย่างทีละขั้นตอนตามที่อธิบายไว้ด้านล่าง หรือดาวน์โหลดตัวอย่างเพิ่มเติมจาก GitHub

หมายเหตุ

ตัวอย่างนี้สาธิตการรับรองความถูกต้อง OAuth ในการผลิต สําหรับข้อมูลเกี่ยวกับการกําหนดค่า Sandbox โปรดดู การกําหนดค่า Sandbox

ตัวอย่างการรับรองความถูกต้องของแอปพลิเคชันเว็บ Walk-Through

  1. เปิดสภาพแวดล้อมการพัฒนา Eclipse

  2. สร้างโครงการใหม่ผ่านทาง File ->New ->Project -Maven> ->Maven Project แล้วคลิกถัดไป

  3. ในกล่องโต้ตอบโครงการ Maven ใหม่ ตรวจสอบให้แน่ใจว่าไม่ได้เลือกตัวเลือกเพื่อสร้างโครงการอย่างง่าย (ข้ามการเลือกต้นแบบ) แล้วคลิกถัดไป คุณจะเลือกต้นแบบ Maven ในขั้นตอนถัดไป

  4. ในกล่องโต้ตอบโครงการ Maven ใหม่ ให้เลือกต้นแบบเว็บแอป Maven แล้วคลิกถัดไป รหัสกลุ่มคือ org.apache.maven.archetypes และรหัสอาร์ทิแฟกต์คือ maven-archetype-webapp

  5. ในกล่องโต้ตอบ โครงการ Maven ใหม่ ให้ระบุพารามิเตอร์อาร์ทิแฟกต์ของโครงการของคุณ แล้วคลิกเสร็จสิ้น ตัวอย่างเช่น คุณสามารถตั้งค่า รหัสกลุ่ม เป็น com.microsoft.bingads.examples และ รหัสอาร์ทิแฟกต์ เป็น BingAdsWebApp

  6. เพิ่ม javax servlet JAR ที่จําเป็นลงในไลบรารีโครงการของคุณ ถ้าไม่ได้อยู่ในพาธบิลด์ Java ของคุณ ใน Project Explorer ให้คลิกขวาที่โครงการ BingAdsWebApp แล้วคลิกคุณสมบัติ ในกล่องโต้ตอบคุณสมบัติ ให้ไปที่แท็บ Java Build Path ->Libraries คลิกเพิ่ม JAR ภายนอก แล้วไปที่ {EclipseInstallationPath}/plugins/ แล้วเลือก เช่น ทั้ง javax.servlet.jsp_2.2.0.v201112011158 และ javax.servlet_3.0.0.v20111201101016

  7. รวม JAR ของเซอร์ฟレットลงในลําดับของโครงการและรายการที่ส่งออก ในแท็บ Java Build Path ->Order and Export ให้คลิก เลือกทั้งหมด (อย่างน้อยให้เลือก Servlet JARs) แล้วคลิก เสร็จสิ้น

  8. รวม Servlet JAR ใน Web Deployment Assembly ของโครงการ ใน Project Explorer ให้คลิกขวาที่โครงการ BingAdsWebApp แล้วเลือกคุณสมบัติ ในกล่องโต้ตอบคุณสมบัติ ไปที่ Deployment Assembly ->Add, เลือก Java Build Path Entries แล้วคลิก ถัดไป เลือก JAR ทั้งหมดที่คุณเพิ่มในขั้นตอนก่อนหน้า คลิก Finish ในกล่องโต้ตอบ New Assembly Directive แล้วคลิก Apply ในกล่องโต้ตอบ คุณสมบัติ

  9. ใน Project Explorer ให้คลิกขวาที่ไฟล์ pom.xml แล้วเลือก เปิดด้วย -ตัว>แก้ไขข้อความ เพิ่มการขึ้นต่อกันของ com.microsoft.bingads ตามที่แสดงในตัวอย่างต่อไปนี้ และบันทึก pom.xml

    หมายเหตุ

    สําหรับรายละเอียดเกี่ยวกับเวอร์ชันการขึ้นต่อกันของ SDK ล่าสุด โปรดดู README.md GitHub ของ Bing Ads Java SDK

    <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. ใน Project Explorer ให้คลิกขวาที่โฟลเดอร์เนื้อหาบนเว็บของโครงการ BingAdsWebApp ของคุณ แล้วเลือกไฟล์ ->JSP ใหม่ ตั้งชื่อไฟล์ index.jsp แล้วคลิกเสร็จสิ้น

  11. เปิดไฟล์ Index.jsp และแทนที่เนื้อหาด้วยบล็อกโค้ดต่อไปนี้ คุณต้องแก้ไขตัวอย่างด้านล่างด้วย ClientId, ClientSecret และ RedirectionUri ที่เตรียมใช้งานเมื่อคุณลงทะเบียนแอปพลิเคชันของคุณ นอกจากนี้ คุณจะต้องแก้ไขตัวอย่างด้วย โทเค็นนักพัฒนาการผลิตของคุณ ถ้าคุณใช้ Sandbox คุณจําเป็นต้องทําตามขั้นตอนใน การกําหนดค่า Sandbox

    <%@ 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. แอปพลิเคชันพร้อมที่จะปรับใช้กับเซิร์ฟเวอร์ ตัวอย่างเช่น คุณสามารถเผยแพร่ Web App โดยใช้ Azure App Service สําหรับข้อมูลเพิ่มเติม ให้ดูที่ การปรับใช้แอปพลิเคชันบนเว็บ เมื่อคุณเริ่มต้นแอปพลิเคชัน คุณจะได้รับพร้อมท์ตามค่าเริ่มต้นสําหรับข้อมูลประจําตัวของบัญชี Microsoft เพื่อรับรองความถูกต้องในการผลิต

การปรับใช้เว็บแอปพลิเคชัน

ถ้าคุณกําลังใช้ Microsoft Azure ในการปรับใช้แอปพลิเคชันบนเว็บของคุณ จําเป็นต้องมีสิ่งต่อไปนี้

  • การแจกจ่ายเว็บเซิร์ฟเวอร์หรือแอปพลิเคชันเซิร์ฟเวอร์ที่ใช้ Java เช่น Apache Tomcat, GlassFish, JBoss Application Server, Jetty หรือ IBM® WebSphere® Application Server Liberty Core

  • การสมัครใช้งาน Azure ซึ่งสามารถรับได้จากhttps://azure.microsoft.com/pricing/purchase-options/

  • หรือคุณสามารถติดตั้ง Azure Toolkit for Eclipse (โดย Microsoft Open Technologies) และปรับใช้เว็บแอปพลิเคชันของคุณโดยใช้บริการระบบคลาวด์ของ Azure สําหรับข้อมูลเพิ่มเติม โปรดดูการติดตั้งชุดเครื่องมือ Azure สําหรับ Eclipse

ดูเพิ่มเติม

Sandbox
ตัวอย่างโค้ด API ของ Bing Ads
ที่อยู่บริการเว็บ Bing Ads API