แชร์ผ่าน


การฝึกปฏิบัติ: แอปพลิเคชันเว็บ Bing Ads API ใน Java

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

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

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

หมายเหตุ

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

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

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

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

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

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

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

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

  7. รวม JAR บริการไปยังใบสั่งของโครงการและรายการที่ส่งออก ในแท็บ Java Build Path ->ลําดับและส่งออก คลิกเลือกทั้งหมด (อย่างน้อยเลือก JARs บริการ) แล้วคลิกเสร็จสิ้น

  8. รวม JAR บริการใน แอสเซมบลีการปรับใช้เว็บของโครงการ ใน Project Explorer ให้คลิกขวาที่โครงการ BingAdsWebApp และเลือก คุณสมบัติ ในกล่องโต้ตอบคุณสมบัติ ไปที่แอสเซมบลีการปรับใช้ ->เพิ่ม เลือกรายการเส้นทางการสร้าง Java และคลิกถัดไป เลือก JARs ทั้งหมดที่คุณเพิ่มในขั้นตอนก่อนหน้า คลิก เสร็จสิ้น ในกล่องโต้ตอบ คําสั่งแอสเซมบลีใหม่ แล้วคลิก นําไปใช้ ในกล่องโต้ตอบ คุณสมบัติ

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

    หมายเหตุ

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

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

ดูเพิ่มเติม

กระบะทราย
ตัวอย่างรหัส API ของโฆษณา Bing
ที่อยู่ของบริการเว็บ API ของ Bing Ads