共用方式為


使用 SDK 進行驗證

本文涵蓋 Bing 廣告 SDK 的驗證和基本服務呼叫。

設定沙箱

SDK 預設會使用生產環境。 使用 .NET 和 Java SDK,您可以使用全域設定將其變更為沙箱。 雖然 PHP 和 Python SDK 無法使用全域設定,但您可以建立全域設定或其他自定義解決方案。

// Set the BingAdsEnvironment key to Sandbox within the <appSettings> node 
// of your project root's Web.config file (for web apps) or App.config file (for native apps).
<add key="BingAdsEnvironment" value ="Sandbox"/>
// Create a new text file named bingads.properties within your project source root directory 
// e.g. **ProjectName\src\bingads.properties** and add only the following text. 
// If the sandbox environment setting is malformed or missing, the default environment is production.
environment=Sandbox

您也可以設定個別大量 Service Manager服務客戶端和報告 Service Manager 實例的 API 環境參數。 設定 apiEnvironment 只會覆寫指定之服務客戶端實例或實例的全域設定。 除非另有用,否則您應該小心不要不小心設定混合的環境集。

注意事項

BulkServiceManagerReportingServiceManager 可搭配 .NET、Java 和 Python SDK 使用。

BulkServiceManager BulkService = new BulkServiceManager(authorizationData, ApiEnvironment.Sandbox);

ServiceClient<ICustomerManagementService> Service = new ServiceClient<ICustomerManagementService>(authorizationData, ApiEnvironment.Sandbox);
    
ReportingServiceManager ReportingService = new ReportingServiceManager(authorizationData, ApiEnvironment.Sandbox);
BulkServiceManager BulkService = new BulkServiceManager(authorizationData, ApiEnvironment.SANDBOX);

ServiceClient<ICustomerManagementService> CustomerService = 
    new ServiceClient<ICustomerManagementService>(
        authorizationData,
        ApiEnvironment.SANDBOX,
        ICustomerManagementService.class
    );
    
ReportingServiceManager ReportingService = new ReportingServiceManager(authorizationData, ApiEnvironment.SANDBOX);
$customerProxy = new ServiceClient(ServiceClientType::CustomerManagementVersion13, $authorizationData, ApiEnvironment::Sandbox);
# Set the environment property of each ServiceClient instance to 'sandbox' (not case sensitive). 
# If the sandbox environment setting is malformed or missing, the default environment is production.
# Once the environment is initialized you may not reset it for the service client instance. 
# To switch between sandbox and production, you must create a new service client instance.

bulk_service_manager = BulkServiceManager(
    authorization_data=authorization_data, 
    version = 13,
    poll_interval_in_milliseconds = 5000, 
    environment = 'sandbox',
)

customer_service = ServiceClient(
    'CustomerManagementService', 
    version = 13,
    authorization_data=authorization_data, 
    environment = 'sandbox',
)

reporting_service_manager = ReportingServiceManager(
    authorization_data=authorization_data, 
    version = 13,
    poll_interval_in_milliseconds = 5000, 
    environment = 'sandbox',
)

使用 OAuth

Bing 廣告 SDK 支援 OAuth 2.0 授權架構中詳細定義的標準 OAuth 2.0 流程。SDK 中的 OAuth 類別會擷取低階使用者授權詳細數據,例如格式化授權和重新導向 URI、設定要求標頭,以及剖析重新導向流量和回應數據流。 若要搭配 Bing Ads .NET SDK 使用 OAuth,您的 AuthorizationData 物件的 Authentication 屬性必須設定為 Authentication 衍生類別,例如 OAuthWebAuthCodeGrantOAuthDesktopMobileAuthCodeGrantOAuthDesktopMobileImplicitGrant

針對重複或長期驗證,您應該遵循授權碼授與流程來取得存取令牌。 下列步驟會遵循授權碼授與流程。 如需註冊應用程式和授權碼授與流程的詳細資訊,請參閱 使用 OAuth 進行驗證

  1. 建立將用來管理 Microsoft 帳戶用戶授權的 OAuthWebAuthCodeGrant 實例。 將用戶端識別碼 (已註冊的應用程式標識碼) 、用戶端密碼 (已註冊的密碼) ,以及將 URI 重新導向為您註冊應用程式時所設定的值。

    var oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new Uri(RedirectionUri), ApiEnvironment);
    
    // It is recommended that you specify a non guessable 'state' request parameter to help prevent
    // cross site request forgery (CSRF). 
    oAuthWebAuthCodeGrant.State = "ClientStateGoesHere";
    
    OAuthWebAuthCodeGrant oAuthWebAuthCodeGrant = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new URL(RedirectionUri), ApiEnvironment);
    
    // It is recommended that you specify a non guessable 'state' request parameter to help prevent
    // cross site request forgery (CSRF). 
    oAuthWebAuthCodeGrant.setState("ClientStateGoesHere");
    
    // Prepare the OAuth object for use with the authorization code grant flow. 
    // It is recommended that you specify a non guessable 'state' request parameter to help prevent
    // cross site request forgery (CSRF). 
    $authentication = (new OAuthWebAuthCodeGrant())
        ->withClientId(ClientId)
        ->withClientSecret(ClientSecret)
        ->withEnvironment(ApiEnvironment)
        ->withRedirectUri('https://' . $_SERVER['HTTP_HOST'] . RedirectUri)
        ->withState(rand(0,999999999)); 
    
    // Assign this authentication instance to the global authorization_data. 
    
    $_SESSION['AuthorizationData'] = (new AuthorizationData())
        ->withAuthentication($authentication)
        ->withDeveloperToken(AuthHelper::DeveloperToken);
    
    $_SESSION['state'] = $_SESSION['AuthorizationData']->Authentication->State;
    
    oauth_web_auth_code_grant = OAuthWebAuthCodeGrant(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        env=ENVIRONMENT,
        redirection_uri=REDIRECTION_URI
    )
    
    # It is recommended that you specify a non guessable 'state' request parameter to help prevent
    # cross site request forgery (CSRF). 
    oauth_web_auth_code_grant.state="ClientStateGoesHere"
    
  2. 透過網頁瀏覽器控件連線到 Microsoft 帳戶授權端點,以要求使用者同意。 呼叫您在先前步驟中建立之 OAuthWebAuthCodeGrant 實例的 GetAuthorizationEndpoint 方法。

    return Redirect(oAuthWebAuthCodeGrant.GetAuthorizationEndpoint().ToString());
    
    URL authorizationEndpoint = oAuthWebAuthCodeGrant.getAuthorizationEndpoint();
    response.sendRedirect(authorizationEndpoint.toString());
    
    // The user needs to provide consent for the application to access their Microsoft Advertising accounts.
    header('Location: '. $_SESSION['AuthorizationData']->Authentication->GetAuthorizationEndpoint());
    
    oauth_web_auth_code_grant.get_authorization_endpoint()
    

    系統會透過 Microsoft 帳戶授權網頁瀏覽器控件提示使用者,以授與應用程式管理其 Microsoft Advertising 帳戶的許可權。

    如果使用者授權您的應用程式管理其 Microsoft Advertising 帳戶,授權服務會使用重新導向 URI 回呼您的應用程式,其中包含授權碼。 例如,如果使用者授與應用程式管理其 Microsoft Advertising 帳戶的許可權,回呼 URL 會包含授權碼,如下所示: https://contoso.com/redirect/?code=CODE&state=ClientStateGoesHere。 如果使用者授與應用程式管理其 Microsoft Advertising 帳戶的許可權,您應該在下一個步驟中立即使用程式代碼。 授權碼的簡短持續時間大約為 5 分鐘,可能會變更。

    如果使用者拒絕應用程式管理其 Microsoft Advertising 帳戶的許可權,回呼 URI 會包含錯誤和錯誤描述字段,如下所示: REDIRECTURI?error=access_denied&error_description=ERROR_DESCRIPTION&state=ClientStateGoesHere

  3. 使用授權碼來要求存取令牌和重新整理令牌。 使用 OAuthWebAuthCodeGrant 實例來要求存取令牌和重新整理令牌時,請傳遞完整的回呼 URI。

    if (Request["code"] != null)
    {
        await oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(Request.Url);
    }
    
    if (request.getParameter("code") != null)
    {
        oAuthWebAuthCodeGrant.requestAccessAndRefreshTokens(new URL(request.getRequestURL() + "?" + request.getQueryString()));
    }
    
    if($_GET['code'] != null)
    {   
        $_SESSION['AuthorizationData']->Authentication->RequestOAuthTokensByResponseUri($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    
        header('Location: '. '/CallBingAdsServices.php');
    }
    
    oauth_web_auth_code_grant.request_oauth_tokens_by_response_uri(RESPONSE_URI)
    oauth_tokens = oauth_web_auth_code_grant.oauth_tokens
    access_token = oauth_tokens.access_token
    

    如果此步驟成功,您的應用程式將有權管理使用者的 Microsoft Advertising 帳戶。 若要呼叫 Bing 廣告 API 服務作業,您應該使用包含 OAuthWebAuthCodeGrant 實例的 AuthorizationData,初始化 Service ClientBulk Service ManagerReporting Service Manager

    如需詳細資訊,請 參閱使用 AuthorizationData使用服務用戶端使用 BulkServiceManager使用 ReportingServiceManager

    注意事項

    BulkServiceManagerReportingServiceManager 可搭配 .NET、Java 和 Python SDK 使用。

  4. 使用 Service ClientBulk Service ManagerReporting Service Manager 呼叫 Bing Ads API 服務作業時,每當收到新的 OAuth 令牌時,請務必儲存最新的重新整理令牌。

    // If you already have a refresh token, use it to request new access and refresh tokens.
    
    if (GetRefreshToken(out refreshToken))
    {
        oAuthWebAuthCodeGrant.RequestAccessAndRefreshTokensAsync(refreshToken);
    }
    
    // When calling Bing Ads API service operations with Service Client, Bulk Service Manager, or Reporting Service Manager, 
    // each instance will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code. 
    // It is important to save the most recent refresh token whenever new OAuth tokens are received. 
    // You will want to subscribe to the NewOAuthTokensReceived event handler.
    
    oAuthWebAuthCodeGrant.NewOAuthTokensReceived += 
        (sender, args) => SaveRefreshToken(args.NewRefreshToken);
    
    // If you already have a refresh token, use it to request new access and refresh tokens.
    
    if (refreshToken != null)
    {
        oAuthWebAuthCodeGrant.requestAccessAndRefreshTokens(refreshToken);
    }
    
    // When calling Bing Ads API service operations with Service Client, Bulk Service Manager, or Reporting Service Manager, 
    // each instance will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code. 
    // It is important to save the most recent refresh token whenever new OAuth tokens are received. 
    // You will want to implement event handling using the NewOAuthTokensReceivedListener.
    
    oAuthWebAuthCodeGrant.setNewTokensListener(new NewOAuthTokensReceivedListener() {
        @Override
        public void onNewOAuthTokensReceived(OAuthTokens newTokens) {
               saveRefreshToken(newTokens.getRefreshToken());
        }
    });
    
    // If you already have a refresh token, use it to request new access and refresh tokens.
    $_SESSION['AuthorizationData']->Authentication->RequestOAuthTokensByRefreshToken($refreshToken);
    
    # When calling Bing Ads API service operations with Service Client, Bulk Service Manager, or Reporting Service Manager, 
    # each instance will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code. 
    # It is important to save the most recent refresh token whenever new OAuth tokens are received. 
    # You will want to register a callback function to automatically save the refresh token anytime it is refreshed. 
    # For example if you defined have a save_refresh_token() method that securely stores your refresh token, 
    # set the authentication token_refreshed_callback property of each OAuthWebAuthCodeGrant instance.
    
    oauth_web_auth_code_grant.token_refreshed_callback=save_refresh_token
    
    # If you already have a refresh token, use it to request new access and refresh tokens.
    
    if refresh_token is not None:
        oauth_web_auth_code_grant.request_oauth_tokens_by_refresh_token(refresh_token)
    

    重要事項

    重新整理令牌最多可持續 90 天。 不論是哪一個,您應該預期會從步驟 1 重新開始,並在 Microsoft 帳戶使用者變更其密碼、從其受信任裝置清單中移除裝置,或移除應用程式代表其進行驗證的許可權時,要求使用者同意。

使用 AuthorizationData

AuthorizationData 類別包含 Microsoft Advertising 用來授權用戶的屬性。 Service ClientBulk Service ManagerReporting Service Manager 類別會為您處理一般要求標頭字段,讓您在 AuthorizationData 物件中為每個服務指定 AuthenticationCustomerIdAccountIdDeveloperToken 属性一次。

注意事項

BulkServiceManagerReportingServiceManager 可搭配 .NET、Java 和 Python SDK 使用。

下列程式代碼區塊示範如何建立 AuthorizationData 的實例,並設定其 AuthenticationCustomerIdAccountIdDeveloperToken 屬性。

var authorizationData = new AuthorizationData
{
    Authentication = <AuthenticationGoesHere>, 
    CustomerId = <CustomerIdGoesHere>,
    AccountId = <AccountIdGoesHere>,
    DeveloperToken = "<DeveloperTokenGoesHere>"
};
static AuthorizationData authorizationData = new AuthorizationData();
authorizationData.setAuthentication(<AuthenticationGoesHere>);
authorizationData.setCustomerId("<CustomerIdGoesHere>");
authorizationData.setAccountId("<AccountIdGoesHere>");
authorizationData.setDeveloperToken("<DeveloperTokenGoesHere>");
$authorizationData = (new AuthorizationData())
    ->withAuthentication($AuthenticationGoesHere)
    ->withCustomerId($CustomerIdGoesHere)
    ->withAccountId($AccountIdGoesHere)
    ->withDeveloperToken($DeveloperTokenGoesHere);
authorization_data = AuthorizationData(
    authentication = <AuthenticationGoesHere>,
    customer_id = <CustomerIdGoesHere>,
    account_id = <AccountIdGoesHere>,
    developer_token = '<DeveloperTokenGoesHere>'
)

Authentication 屬性必須設定為驗證衍生類別,例如 OAuthWebAuthCodeGrantOAuthDesktopMobileAuthCodeGrantOAuthDesktopMobileImplicitGrant

某些客戶管理等服務不接受 CustomerIdCustomerAccountId 標頭,因此如果您在 AuthorizationData 物件中指定它們,則會忽略它們。

使用服務用戶端

您可以使用 ServiceClient 類別的實例來呼叫其中一個 Microsoft Advertising Web 服務的任何方法。 ServiceClient 類別會為您處理一般要求標頭字段,允許為每個服務指定 AuthorizationData 物件中的 AuthenticationCustomerIdAccountIdDeveloperToken 屬性一次。

提示

如果您使用大量或 Reporting 服務,請使用大量 Service Manager報告 Service Manager,而不是 ServiceClient。 例如,大量 Service Manager 會將您的下載要求提交至大量服務、輪詢服務直到完成,然後將檔案下載到您在要求中指定的本機目錄。 您將節省更多時間,因為您不需要寫入或剖析上傳或結果檔案。

// The primary method of the ServiceClient class is CallAsync. The method parameter is the delegate 
// for the service operation that you want to call. The request parameter of this method must be a 
// request message corresponding to the name of the service operation specified by the first request parameter. 
// The request message must match the service operation that is specified as the delegate in the first request.

public async Task<TResponse> CallAsync<TRequest, TResponse>(
    Func<TService, TRequest, Task<TResponse>> method, TRequest request)

// In the following sample, the method delegate is (s, r) => s.GetUserAsync(r) which takes a GetUserRequest 
// message as the request parameter (TRequest) and returns a GetUserResponse message (TResponse).

private async Task<User> GetUserAsync(long? userId)
{
    var request = new GetUserRequest
    {
        UserId = userId
    };

    return (await _customerService.CallAsync((s, r) => s.GetUserAsync(r), request)).User;
}
// You can use the Customer Management service to get the current authenticated user.

ServiceClient<ICustomerManagementService> CustomerService = new ServiceClient<ICustomerManagementService>(
		authorizationData, 
		ICustomerManagementService.class);

java.lang.Long userId = null;
final GetUserRequest getUserRequest = new GetUserRequest();
getUserRequest.setUserId(userId);

// If you updated the authorization data such as account ID or you want to call a new operation, 
// you must call getService to set the latest request headers. 
// As a best practice you should use getService when calling any service operation.
User user = CustomerService.getService().getUser(getUserRequest).getUser();
// You can use a single instance of the ServiceClient class to call any methods in the service, 
// for example you can set the CustomerManagementVersion13 service client type as follows.

$customerProxy = new ServiceClient(ServiceClientType::CustomerManagementVersion13, $authorizationData, ApiEnvironment::Sandbox);
)
# You can use the Customer Management service to get the current authenticated user.

customer_service = ServiceClient(
    'CustomerManagementService', 
    version = 13,
    authorization_data=authorization_data, 
    environment = ENVIRONMENT,
)

user = customer_service.GetUser(UserId = None).User

重要事項

如果您在要求參數中設定 AuthenticationTokenCustomerIdAccountIdDeveloperToken 標頭元素,例如 GetUserRequest,則會忽略它們。 Service Client 一律會使用其初始化所提供的 AuthorizationData

另請參閱

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