Freigeben über


Exemplarische Vorgehensweise: Bing Ads-API-Webanwendung in PHP

Diese PHP-Beispielwebanwendung fordert über die von Ihnen angegebenen Anmeldeinformationen zur Benutzereinwilligung auf und ruft dann die Konten ab, auf die der authentifizierte Benutzer zugreifen kann.

Sie müssen zunächst eine Anwendung registrieren und sich die Client-ID (registrierte Anwendungs-ID), den geheimen Clientschlüssel (registriertes Kennwort) und den Umleitungs-URI notieren. Weitere Informationen zum Registrieren einer Anwendung und zum Autorisierungscodegenehmigungsflow finden Sie unter Authentifizierung mit OAuth.

Sie benötigen auch Ihr Entwicklertoken für die Produktion. Sie können das Beispiel wie unten beschrieben Schritt für Schritt erstellen oder weitere Beispiele von GitHub herunterladen.

Beispiel für die Webanwendungsauthentifizierung Walk-Through

  1. Erstellen Sie eine neue Datei namens Index.php, und fügen Sie den Code wie im folgenden Beispiel gezeigt hinzu.

    <?php
    namespace Microsoft\BingAds\Samples;
    
    require_once "./vendor/autoload.php";
    
    include "WebAuthHelper.php";
    
    // Specify the Microsoft\BingAds\Samples classes that will be used.
    use Microsoft\BingAds\Samples\WebAuthHelper;
    
    ?>
    
    <!-- 
    Display a small form with a login button. In your application, you would implement code to allow
    the user to either log into your service or create a new account. 
    -->
    <h2>Microsoft Advertising OAuth Demo</h2>
    
    <p>This application would like to manage your Microsoft Advertising data. Click below to login and authorize this application.</p>
    
    <p>When you click OK below, you'll be redirected to the following URI:</p>
    <p><?php echo WebAuthHelper::RedirectUri ?></p>
    
    <!-- 
    When the user presses this button, they will be redirected to fully formed URL to request an authorization token. 
    From here, the user will be redirected to the RedirectUri where the authorization token can be extracted. 
    -->
    <input type="button" onClick="return window.location='<?php echo WebAuthHelper::RedirectUri;?>';" value="OK" />
    
  2. Erstellen Sie eine neue Datei mit dem Namen OAuth2Callback.php, und fügen Sie den Code wie im folgenden Beispiel gezeigt hinzu.

    <?php
    namespace Microsoft\BingAds\Samples;
    
    require_once "./vendor/autoload.php";
    
    include "WebAuthHelper.php";
    
    // Specify the Microsoft\BingAds\Auth classes that will be used.
    use Microsoft\BingAds\Auth\AuthorizationData;
    use Microsoft\BingAds\Auth\OAuthTokenRequestException;
    use Microsoft\BingAds\Auth\OAuthWebAuthCodeGrant;
    
    // Specify the Microsoft\BingAds\Samples classes that will be used.
    use Microsoft\BingAds\Samples\WebAuthHelper;
    
    use Exception;
    
    try 
    {
        session_start();
    
        if(!isset($_SESSION['AuthorizationData']) || !isset($_SESSION['AuthorizationData']->Authentication))
        {
            // 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(WebAuthHelper::ClientId)
                ->withClientSecret(WebAuthHelper::ClientSecret)
                ->withRedirectUri('https://' . $_SERVER['HTTP_HOST'] . WebAuthHelper::RedirectUri)
                ->withState(rand(0,999999999)); 
    
            // Assign this authentication instance to the global authorization_data. 
    
            $_SESSION['AuthorizationData'] = (new AuthorizationData())
                ->withAuthentication($authentication)
                ->withDeveloperToken(WebAuthHelper::DeveloperToken);
    
            $_SESSION['state'] = $_SESSION['AuthorizationData']->Authentication->State;
    
            // The user needs to provide consent for the application to access their Microsoft Advertising accounts.
            header('Location: '. $_SESSION['AuthorizationData']->Authentication->GetAuthorizationEndpoint());
        }
    
        // If the current HTTP request is a callback from the Microsoft Account authorization server,
        // use the current request url containing authorization code to request new access and refresh tokens
        if(isset($_GET['code']))
        {   
            // Verify whether the 'state' value is the same random value we created
            // when the authorization request was initiated.
            if ($_GET['state'] != $_SESSION['state'])
            {
                throw new Exception(sprintf(
                    "The OAuth response state (%s) does not match the client request state (%s)", 
                    $_GET['state'], 
                    $_SESSION['state']));
            }   
    
            $_SESSION['AuthorizationData']->Authentication->RequestOAuthTokensByResponseUri(
                $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    
            header('Location: '. '/CallBingAdsServices.php');
        }
    }
    catch(OAuthTokenRequestException $e)
    {
        // The user could not be authenticated or the grant is expired. 
        // The user must first sign in and if needed grant the client application access to the requested scope.
        print $e;
    }
    catch(Exception $e)
    {
        print $e;
    }    
    
  3. Erstellen Sie eine neue Datei mit dem Namen CallBingAdsServices.php, und fügen Sie den Code wie im folgenden Beispiel gezeigt hinzu.

    <?php
    namespace Microsoft\BingAds\Samples;
    
    require_once "./vendor/autoload.php";
    
    include "WebAuthHelper.php";
    
    // Specify the Microsoft\BingAds\Auth classes that will be used.
    use Microsoft\BingAds\Auth\AuthorizationData;
    use Microsoft\BingAds\Auth\ServiceClient;
    use Microsoft\BingAds\Auth\ServiceClientType;
    
    // Specify the Microsoft\BingAds\V13\CustomerManagement classes that will be used.
    use Microsoft\BingAds\V13\CustomerManagement\GetUserRequest;
    use Microsoft\BingAds\V13\CustomerManagement\SearchAccountsRequest;
    use Microsoft\BingAds\V13\CustomerManagement\Paging;
    use Microsoft\BingAds\V13\CustomerManagement\Predicate;
    use Microsoft\BingAds\V13\CustomerManagement\PredicateOperator;
    
    // Specify the Microsoft\BingAds\Samples classes that will be used.
    use Microsoft\BingAds\Samples\WebAuthHelper;
    
    use Exception;
    
    session_start();
    
    // If there is no user authenticated, go back to the site index.
    
    if(!isset($_SESSION['AuthorizationData']) || 
    !isset($_SESSION['AuthorizationData']->Authentication) || 
    !isset($_SESSION['AuthorizationData']->Authentication->OAuthTokens)
    )
    {
        header('Location: '. 'https://' . $_SERVER['HTTP_HOST']);
    }
    else {
        // If a refresh token is already present, use it to request new access and refresh tokens.
        // You should store refresh tokens securely i.e. not in session as shown in this demo.
    
        $refreshToken = $_SESSION['AuthorizationData']->Authentication->OAuthTokens->RefreshToken;
        if($refreshToken != null)
        {
            $_SESSION['AuthorizationData']->Authentication->RequestOAuthTokensByRefreshToken($refreshToken);
        }
    
        printf("Access token: %s<br/>", $_SESSION['AuthorizationData']->Authentication->OAuthTokens->AccessToken);
        printf("Refresh token: %s<br/>", $_SESSION['AuthorizationData']->Authentication->OAuthTokens->RefreshToken);
    
        $GLOBALS['CustomerManagementProxy'] = new ServiceClient(
            ServiceClientType::CustomerManagementVersion13, 
            $_SESSION['AuthorizationData'], 
            WebAuthHelper::GetApiEnvironment());
    
        // Set the GetUser request parameter to an empty user identifier to get the current 
        // authenticated Microsoft Advertising user, and then search for all accounts the user may access.
    
        $getUserRequest = new GetUserRequest();
        $getUserRequest->UserId = null;
    
        $user = $GLOBALS['CustomerManagementProxy']->GetService()->GetUser($getUserRequest)->User;
    
        // Search for the Microsoft Advertising accounts that the user can access.
    
        $pageInfo = new Paging();
        $pageInfo->Index = 0;    // The first page
        $pageInfo->Size = 1000;   // The first 1,000 accounts for this page of results    
        $predicate = new Predicate();
        $predicate->Field = "UserId";
        $predicate->Operator = PredicateOperator::Equals;
        $predicate->Value = $user->Id; 
    
        $searchAccountsRequest = new SearchAccountsRequest();
        $searchAccountsRequest->Predicates = array($predicate);
        $searchAccountsRequest->Ordering = null;
        $searchAccountsRequest->PageInfo = $pageInfo;
    
        $accounts = $GLOBALS['CustomerManagementProxy']->GetService()->SearchAccounts($searchAccountsRequest)->Accounts;
    
        print "-----<br/>Accounts the user can access:<br/>";
        foreach ($accounts->AdvertiserAccount as $account)
        {
            printf("Account Name: %s<br/>", $account->Name);
        }
    }
    
    session_unset();
    
    ?>
    
  4. Erstellen Sie eine neue Datei mit dem Namen WebAuthHelper.php, und fügen Sie den Code wie im folgenden Beispiel gezeigt hinzu. Sie müssen das folgende Beispiel mit clientID, ClientSecret und RedirectionUri bearbeiten, die bei der Registrierung Ihrer Anwendung bereitgestellt wurden. Außerdem müssen Sie das Beispiel mit Ihrem Produktionsentwicklertoken bearbeiten.

    <?php
    
    namespace Microsoft\BingAds\Samples;
    
    require_once "./vendor/autoload.php";
    
    // Specify the Microsoft\BingAds\Auth classes that will be used.
    use Microsoft\BingAds\Auth\ApiEnvironment;
    
    /** 
    * Defines global settings that you can use for testing your application.
    * Your production implementation may vary, and you should always store sensitive information securely.
    */
    final class WebAuthHelper {
    
        const DeveloperToken = 'DeveloperTokenGoesHere';
        const ApiEnvironment = ApiEnvironment::Production;
        const ClientId = 'ClientIdGoesHere'; 
        const ClientSecret = 'ClientSecretGoesHere'; 
        const RedirectUri = '/OAuth2Callback.php'; 
    
        static function GetApiEnvironment() 
        {
            return WebAuthHelper::ApiEnvironment;
        }
    }
    
  5. Die Anwendung kann auf einem Server mit den installierten PHP-Clientbibliotheken bereitgestellt werden. Sie können beispielsweise eine Web-App mit dem Azure App Service veröffentlichen. Weitere Informationen finden Sie unter Konfigurieren von PHP in Azure App Service Web-Apps.

Siehe auch

Codebeispiele für die Bing Ads-API
Adressen des Bing Ads-API-Webdiensts