Beispiel für den Einladungscode

In diesem Beispiel wird veranschaulicht, wie Sie einen Benutzer zum Verwalten von Microsoft Advertising-Konten einladen.

Tipp

Verwenden Sie die Sprachauswahl im Dokumentationsheader, um C#, Java, Php oder Python auszuwählen.

Informationen zum Abrufen von Zugriffs- und Aktualisierungstoken für Ihren Microsoft Advertising-Benutzer und Zum ersten Dienstaufruf mithilfe der Bing Ads-API finden Sie im Schnellstarthandbuch . Sie sollten den Leitfaden für die ersten Schritte und exemplarische Vorgehensweisen für Ihre bevorzugte Sprache lesen, z. B. C#, Java, Php und Python.

Unterstützende Dateien für C#-, Java-, Php- und Python-Beispiele sind auf GitHub verfügbar. Sie können jedes Repository klonen oder Codeausschnitte nach Bedarf erneut verwenden.

using System;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CustomerManagement;
using Microsoft.BingAds;
using System.Globalization;

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How to invite a user to manage your advertising accounts.
    /// </summary>
    public class InviteUser : ExampleBase
    {
        // Specify the email address where the invitation should be sent. 
        // The recipient can accept the invitation and sign up 
        // with credentials that differ from the invitation email address.

        const string UserInviteRecipientEmail = "UserInviteRecipientEmailGoesHere";
        
        public override string Description
        {
            get { return "Invite a User to Manage accounts | Customer Management V13"; }
        }

        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                OutputStatusMessage("You must edit this example to provide the email address (UserInviteRecipientEmail) for " +
                                    "the user invitation.");
                OutputStatusMessage("You must use Super Admin credentials to send a user invitation.");

                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

                CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient<ICustomerManagementService>(
                    authorizationData: authorizationData,
                    environment: environment);

                // Prepare to invite a new user
                var userInvitation = new UserInvitation
                {
                    // The identifier of the customer this user is invited to manage. 
                    // The AccountIds element determines which customer accounts the user can manage.
                    CustomerId = authorizationData.CustomerId,

                    // Users with account level roles such as Advertiser Campaign Manager can be restricted to specific accounts. 
                    // Users with customer level roles such as Super Admin can access all accounts within the user's customer, 
                    // and their access cannot be restricted to specific accounts.
                    AccountIds = null,

                    // The user role, which determines the level of access that the user has to the accounts specified in the AccountIds element.
                    // The identifier for an advertiser campaign manager is 16.
                    RoleId = 16,

                    // The email address where the invitation should be sent. 
                    Email = UserInviteRecipientEmail,

                    // The first name of the user. 
                    FirstName = "FirstNameGoesHere",

                    // The last name of the user. 
                    LastName = "LastNameGoesHere",

                    // The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS.
                    Lcid = LCID.EnglishUS,
                };

                // Once you send a user invitation, there is no option to rescind the invitation using the API.
                // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Microsoft Advertising web application. 

                OutputStatusMessage("-----\nSendUserInvitation:");
                var userInvitationId = (await CustomerManagementExampleHelper.SendUserInvitationAsync(
                    userInvitation: userInvitation))?.UserInvitationId;
                OutputStatusMessage(string.Format("Sent new user invitation to {0}.", UserInviteRecipientEmail));

                // It is possible to have multiple pending invitations sent to the same email address, 
                // which have not yet expired. It is also possible for those invitations to have specified 
                // different user roles, for example if you sent an invitation with an incorrect user role 
                // and then sent a second invitation with the correct user role. The recipient can accept 
                // any of the invitations. The Bing Ads API does not support any operations to delete 
                // pending user invitations. After you invite a user, the only way to cancel the invitation 
                // is through the Microsoft Advertising web application. You can find both pending and accepted invitations 
                // in the Users section of Accounts & Billing.

                // Since a recipient can accept the invitation with credentials that differ from 
                // the invitation email address, you cannot determine with certainty the mapping from UserInvitation 
                // to accepted User. You can only determine whether the invitation has been accepted or has expired. 
                // The SearchUserInvitations operation returns all pending invitations, whether or not they have expired. 
                // Accepted invitations are not included in the SearchUserInvitations response.  

                var predicate = new Predicate
                {
                    Field = "CustomerId",
                    Operator = PredicateOperator.In,
                    Value = authorizationData.CustomerId.ToString(CultureInfo.InvariantCulture)
                };

                OutputStatusMessage("-----\nSearchUserInvitations:");
                var userInvitations = (await CustomerManagementExampleHelper.SearchUserInvitationsAsync(
                    predicates: new[] { predicate }))?.UserInvitations;
                OutputStatusMessage("UserInvitations:");
                CustomerManagementExampleHelper.OutputArrayOfUserInvitation(userInvitations);

                // After the invitation has been accepted, you can call GetUsersInfo and GetUser to access the Microsoft Advertising user details. 
                // Once again though, since a recipient can accept the invitation with credentials that differ from 
                // the invitation email address, you cannot determine with certainty the mapping from UserInvitation 
                // to accepted User. 

                OutputStatusMessage("-----\nGetUsersInfo:");
                var usersInfo = (await CustomerManagementExampleHelper.GetUsersInfoAsync(
                    customerId: authorizationData.CustomerId,
                    statusFilter: null))?.UsersInfo;
                OutputStatusMessage("UsersInfo:");
                CustomerManagementExampleHelper.OutputArrayOfUserInfo(usersInfo);

                foreach (var info in usersInfo)
                {
                    OutputStatusMessage("-----\nGetUser:");
                    var getUserResponse = await CustomerManagementExampleHelper.GetUserAsync(
                        userId: info.Id);
                    var user = getUserResponse.User;
                    OutputStatusMessage("User:");
                    CustomerManagementExampleHelper.OutputUser(user);
                    OutputStatusMessage("CustomerRoles:");
                    CustomerManagementExampleHelper.OutputArrayOfCustomerRole(getUserResponse.CustomerRoles);
                }
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Customer Management AdApiFaultDetail service exceptions
            catch (FaultException<Microsoft.BingAds.V13.CustomerManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            // Catch Customer Management ApiFault service exceptions
            catch (FaultException<Microsoft.BingAds.V13.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            // Catch other .NET framework exceptions
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
    }
}
package com.microsoft.bingads.examples.v13;

import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.customermanagement.*;

public class InviteUser extends ExampleBase {
    
    // Specify the email address where the invitation should be sent. 
    // The recipient can accept the invitation and sign up 
    // with credentials that differ from the invitation email address.
    
    final static java.lang.String UserInviteRecipientEmail = "UserInviteRecipientEmailGoesHere";
        
    public static void main(java.lang.String[] args) {
     
        try
        {
            outputStatusMessage("You must edit this example to provide the email address (UserInviteRecipientEmail) for " +
                "the user invitation.");
            outputStatusMessage("You must use Super Admin credentials to send a user invitation.");
            
            authorizationData = getAuthorizationData(); 
            java.lang.Long customerId = authorizationData.getCustomerId();
                         
            CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient<ICustomerManagementService>(
                    authorizationData, 
                    API_ENVIRONMENT,
                    ICustomerManagementService.class);
            
            // Prepare to invite a new user
            UserInvitation userInvitation = new UserInvitation();
            
            // The identifier of the customer this user is invited to manage. 
            // The AccountIds element determines which customer accounts the user can manage.
            userInvitation.setCustomerId(customerId);

            // Users with account level roles such as Advertiser Campaign Manager can be restricted to specific accounts. 
            // Users with customer level roles such as Super Admin can access all accounts within the user�s customer, 
            // and their access cannot be restricted to specific accounts.
            userInvitation.setAccountIds(null);

            // The user role, which determines the level of access that the user has to the accounts specified in the AccountIds element.
            // For example you can use Role Id 16 for Advertiser Campaign Manager.
            userInvitation.setRoleId(16);

            // The email address where the invitation should be sent. 
            userInvitation.setEmail(UserInviteRecipientEmail);

            // The first name of the user. 
            userInvitation.setFirstName("FirstNameGoesHere");

            // The last name of the user. 
            userInvitation.setLastName("LastNameGoesHere");

            // The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS.
            userInvitation.setLcid(LCID.ENGLISH_US);
                        
            // Once you send a user invitation, there is no option to rescind the invitation using the API.
            // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Bing Ads web application.
            java.lang.Long userInvitationId = CustomerManagementExampleHelper.sendUserInvitation(
                    userInvitation).getUserInvitationId();
            outputStatusMessage(String.format("Sent new user invitation to %s.", UserInviteRecipientEmail));

            // It is possible to have multiple pending invitations sent to the same email address, 
            // which have not yet expired. It is also possible for those invitations to have specified 
            // different user roles, for example if you sent an invitation with an incorrect user role 
            // and then sent a second invitation with the correct user role. The recipient can accept 
            // any of the invitations. The Bing Ads API does not support any operations to delete 
            // pending user invitations. After you invite a user, the only way to cancel the invitation 
            // is through the Bing Ads web application. You can find both pending and accepted invitations 
            // in the Users section of Accounts & Billing.

            // Since a recipient can accept the invitation with credentials that differ from 
            // the invitation email address, you cannot determine with certainty the mapping from UserInvitation 
            // to accepted User. You can only determine whether the invitation has been accepted or has expired. 
            // The SearchUserInvitations operation returns all pending invitations, whether or not they have expired. 
            // Accepted invitations are not included in the SearchUserInvitations response.  

            ArrayOfPredicate predicates = new ArrayOfPredicate();
            Predicate predicate = new Predicate();
            predicate.setField("CustomerId");
            predicate.setOperator(PredicateOperator.IN);
            predicate.setValue(String.valueOf(customerId));
            predicates.getPredicates().add(predicate);
            
            outputStatusMessage("-----\nSearchUserInvitations:");
            ArrayOfUserInvitation userInvitations = CustomerManagementExampleHelper.searchUserInvitations(
                    predicates).getUserInvitations();
            outputStatusMessage("UserInvitations:");
            CustomerManagementExampleHelper.outputArrayOfUserInvitation(userInvitations);

            // After the invitation has been accepted, you can call GetUsersInfo and GetUser to access the Bing Ads user details. 
            // Once again though, since a recipient can accept the invitation with credentials that differ from 
            // the invitation email address, you cannot determine with certainty the mapping from UserInvitation 
            // to accepted User. 

            outputStatusMessage("-----\nGetUsersInfo:");
            ArrayOfUserInfo usersInfo = CustomerManagementExampleHelper.getUsersInfo(
                    customerId, 
                    null).getUsersInfo();
            outputStatusMessage("UsersInfo:");
            CustomerManagementExampleHelper.outputArrayOfUserInfo(usersInfo);
            
            for (UserInfo userInfo : usersInfo.getUserInfos())
            {
                outputStatusMessage("-----\nGetUser:");
                GetUserResponse getUserResponse = CustomerManagementExampleHelper.getUser(
                        userInfo.getId());
                User user = getUserResponse.getUser();
                outputStatusMessage("User:");
                CustomerManagementExampleHelper.outputUser(user);
                outputStatusMessage("CustomerRoles:");
            }
        } 
        catch (Exception ex) {
            String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
            outputStatusMessage(faultXml);
            String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
            outputStatusMessage(message);
        }
    }
}
<?php

use Microsoft\MsAds\Rest\ApiException;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\InviteUserRequest;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\LCID;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\Predicate;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\PredicateOperator;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\SearchUserInvitationsRequest;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\SendUserInvitationRequest;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\UserInvitation;
use Microsoft\MsAds\Rest\Test\RestApiTestBase;

class InviteUserTest extends RestApiTestBase
{
    // You must edit this example to provide the email address of the user you want to invite.
    private string $userInvitationEmail = "jayw.92@gmail.com"; // Set this to a valid email address
    /**
     * @throws ApiException
     */
    public function testInviteUser()
    {
        print("-----\r\nInviteUser:\r\n");
        $invitation = new UserInvitation();
        $invitation->setFirstName("FirstNameGoesHere");
        $invitation->setLastName("LastNameGoesHere");
        $invitation->setEmail($this->userInvitationEmail);
        $invitation->setCustomerId(self::CUSTOMER_ID);
        $invitation->setRoleId(16); // Set a valid role ID if required
        $invitation->setLcid(LCID::ENGLISH_US); // English

        $request = new SendUserInvitationRequest([
            'UserInvitation' => $invitation
        ]);

        $response = self::$customerManagementServiceApi->sendUserInvitation($request);
        print("InviteUserResponse:\r\n");
        print_r($response);
        self::assertNotNull($response);
        self::assertNotNull($response->getUserInvitationId());
        print("User invitation sent successfully to: " . $this->userInvitationEmail . "\r\n");
    }

    /**
     * @throws ApiException
     */
    public function testSearchUserInvitations()
    {
        print("-----\r\nSearchUserInvitations:\r\n");
        $predicates = [];
        $predicate = new Predicate();
        $predicate->setField("CustomerId");
        $predicate->setOperator(PredicateOperator::IN);
        $predicate->setValue(self::CUSTOMER_ID);
        $predicates[] = $predicate;

        $request = new SearchUserInvitationsRequest();
        $request->setPredicates($predicates);

        $response = self::$customerManagementServiceApi->searchUserInvitations($request);
        print("SearchUserInvitationsResponse:\r\n");
        print_r($response);
        self::assertNotNull($response);
        self::assertIsArray($response->getUserInvitations());
        print("Found " . count($response->getUserInvitations()) . " user invitations:\r\n");
        self::assertGreaterThan(0, count($response->getUserInvitations()));

        foreach ($response->getUserInvitations() as $invitation) {
            print("Found User Invitation:\r\n");
            print_r($invitation);
        }

    }
}

from auth_helper import *
from openapi_client.models.customer import *

# You must edit this example to provide the email address of the user you want to invite.
USER_INVITATION_EMAIL = "jayw.92@gmail.com"  # Set this to a valid email address

def main(authorization_data):
    try:
        # 1. Invite a user
        print("-----\nInviteUser:")
        
        invitation = UserInvitation(
            FirstName='FirstNameGoesHere',
            LastName='LastNameGoesHere',
            Email=USER_INVITATION_EMAIL,
            CustomerId=authorization_data.customer_id,
            RoleId=16,  # Set a valid role ID if required
            Lcid='EnglishUS'  # English
        )
        
        invite_request = SendUserInvitationRequest(
            UserInvitation=invitation
        )
        
        invite_response = customer_service.send_user_invitation(invite_request)
        
        print("InviteUserResponse:")
        print(f"User Invitation ID: {invite_response.UserInvitationId}")
        
        assert invite_response is not None
        assert invite_response.UserInvitationId is not None
        
        print(f"User invitation sent successfully to: {USER_INVITATION_EMAIL}")
        
        # 2. Search for user invitations
        print("\n-----\nSearchUserInvitations:")
        
        predicate = Predicate(
            Field='CustomerId',
            Operator='In',
            Value=str(authorization_data.customer_id)
        )
        
        search_request = SearchUserInvitationsRequest(
            Predicates=[predicate]
        )
        
        search_response = customer_service.search_user_invitations(search_request)
        
        print("SearchUserInvitationsResponse:")
        assert search_response is not None
        assert search_response.UserInvitations is not None
        
        print(f"Found {len(search_response.UserInvitations)} user invitations:")
        assert len(search_response.UserInvitations) > 0
        
        for invitation in search_response.UserInvitations:
            print(f"\nFound User Invitation:")
            print(f"  ID: {invitation.Id}")
            print(f"  Email: {invitation.Email}")
            print(f"  FirstName: {invitation.FirstName}")
            print(f"  LastName: {invitation.LastName}")
            print(f"  CustomerId: {invitation.CustomerId}")
            print(f"  RoleId: {invitation.RoleId}")
        
    except Exception as ex:
        print(f"Error occurred: {str(ex)}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    print("Loading the web service client...")
    
    authorization_data = AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )
    
    authenticate(authorization_data)
    
    customer_service = ServiceClient(
        service='CustomerManagementService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT,
    )
    
    main(authorization_data)

Siehe auch

Erste Schritte mit der Bing Ads-API