Exemple de code utilisateur d’invitation
Cet exemple montre comment inviter un utilisateur à gérer des comptes Microsoft Advertising.
Conseil
Utilisez le sélecteur de langage dans l’en-tête de la documentation pour choisir C#, Java, Php ou Python.
Pour obtenir des jetons d’accès et d’actualisation pour votre utilisateur Microsoft Advertising et effectuer votre premier appel de service à l’aide de l’API Bing Ads, consultez le guide de démarrage rapide . Vous pouvez consulter le guide de prise en main et les procédures pas à pas pour votre langage préféré, par exemple, C#, Java, Php et Python.
Les fichiers de prise en charge pour les exemples C#, Java, Php et Python sont disponibles sur GitHub. Vous pouvez cloner chaque dépôt ou réaffecter des extraits de code en fonction des besoins.
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
namespace Microsoft\BingAds\Samples\V13;
// For more information about installing and using the Bing Ads PHP SDK,
// see https://go.microsoft.com/fwlink/?linkid=838593.
require_once __DIR__ . "/../vendor/autoload.php";
require_once __DIR__ . "/CustomerManagementExampleHelper.php";
include __DIR__ . "/AuthHelper.php";
use SoapVar;
use SoapFault;
use Exception;
// Specify the Microsoft\BingAds\V13\CustomerManagement classes that will be used.
use Microsoft\BingAds\V13\CustomerManagement\LCID;
use Microsoft\BingAds\V13\CustomerManagement\Predicate;
use Microsoft\BingAds\V13\CustomerManagement\PredicateOperator;
use Microsoft\BingAds\V13\CustomerManagement\UserInvitation;
// Specify the Microsoft\BingAds\Auth classes that will be used.
use Microsoft\BingAds\Auth\ServiceClient;
use Microsoft\BingAds\Auth\ServiceClientType;
// Specify the Microsoft\BingAds\Samples classes that will be used.
use Microsoft\BingAds\Samples\V13\AuthHelper;
use Microsoft\BingAds\Samples\V13\CustomerManagementExampleHelper;
// Specify the email address where the invitation should be sent.
// It is important to note that the recipient can accept the invitation
// and sign into Bing Ads with a Microsoft account different than the invitation email address.
$userInviteRecipientEmail = "UserInviteRecipientEmailGoesHere";
try
{
print("You must edit this example to provide the email address (userInviteRecipientEmail) for the user invitation.\r\n");
print("You must use Super Admin credentials to send a user invitation.\r\n");
// Authenticate user credentials and set the account ID for the sample.
AuthHelper::Authenticate();
$customerId = $GLOBALS['AuthorizationData']->CustomerId;
// Prepare to invite a new user
$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->CustomerId = $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->AccountIds = 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->RoleId = 16;
// The email address where the invitation should be sent. This element can contain a maximum of 100 characters.
$userInvitation->Email = $userInviteRecipientEmail;
// The first name of the user. This element can contain a maximum of 40 characters.
$userInvitation->FirstName = "FirstNameGoesHere";
// The last name of the user. This element can contain a maximum of 40 characters.
$userInvitation->LastName = "LastNameGoesHere";
// The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS.
$userInvitation->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 Bing Ads web application.
print("-----\r\nSendUserInvitation:\r\n");
$userInvitationId = CustomerManagementExampleHelper::SendUserInvitation(
$userInvitation
)->UserInvitationId;
printf("Sent new user invitation to %s.\r\n", $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.
$predicates = array();
$predicate = new Predicate();
$predicate->Field = "CustomerId";
$predicate->Operator = PredicateOperator::In;
$predicate->Value = $customerId;
$predicates[] = $predicate;
print("-----\r\nSearchUserInvitations:\r\n");
$userInvitations = CustomerManagementExampleHelper::SearchUserInvitations(
$predicates
)->UserInvitations;
print("UserInvitations:\r\n");
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.
print("-----\r\nGetUsersInfo:\r\n");
$usersInfo = CustomerManagementExampleHelper::GetUsersInfo(
$customerId,
null
)->UsersInfo;
print("UsersInfo:\r\n");
CustomerManagementExampleHelper::OutputArrayOfUserInfo($usersInfo);
foreach ($usersInfo->UserInfo as $userInfo)
{
print("-----\r\nGetUser:\r\n");
$getUserResponse = CustomerManagementExampleHelper::GetUser(
$userInfo->Id,
true
);
$user = $getUserResponse->User;
print("User:\r\n");
CustomerManagementExampleHelper::OutputUser($user);
print("CustomerRoles:\r\n");
CustomerManagementExampleHelper::OutputArrayOfCustomerRole($getUserResponse->CustomerRoles);
}
}
catch (SoapFault $e)
{
printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
var_dump($e->detail);
print "-----\r\nLast SOAP request/response:\r\n";
print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
// Ignore fault exceptions that we already caught.
if ($e->getPrevious())
{ ; }
else
{
print $e->getCode()." ".$e->getMessage()."\r\n";
print $e->getTraceAsString()."\r\n";
}
}
from datetime import datetime, timedelta
from auth_helper import *
from customermanagement_example_helper import *
# You must provide credentials in auth_helper.py.
# 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.
INVITE_EMAIL_TO = "UserInviteRecipientEmailGoesHere"
def main(authorization_data):
try:
output_status_message("You must edit this example to provide the email address (e.g. {0}) for " \
"the user invitation.".format(INVITE_EMAIL_TO))
output_status_message("Login as a Super Admin user to send a user invitation.")
# Prepare to invite a new user
user_invitation = customer_service.factory.create('ns5:UserInvitation')
# The identifier of the customer this user is invited to manage.
# The AccountIds element determines which customer accounts the user can manage.
user_invitation.CustomerId = authorization_data.customer_id
# 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.
user_invitation.AccountIds=None
#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.
user_invitation.RoleId = 16
# The email address where the invitation should be sent.
user_invitation.Email = INVITE_EMAIL_TO
# The first name of the user.
user_invitation.FirstName = "FirstNameGoesHere"
# The last name of the user.
user_invitation.LastName = "LastNameGoesHere"
# The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS.
user_invitation.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 Bing Ads web application.
output_status_message("-----\nSendUserInvitation:")
user_invitation_id=customer_service.SendUserInvitation(
UserInvitation=user_invitation)
output_status_message("Sent new user invitation to {0}.".format(INVITE_EMAIL_TO))
output_status_message("UserInvitationId: {0}".format(user_invitation_id))
# 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.
predicates = {
'Predicate': [
{
'Field': 'CustomerId',
'Operator': 'In',
'Value': authorization_data.customer_id,
},
]
}
output_status_message("-----\nSearchUserInvitations:")
user_invitations = customer_service.SearchUserInvitations(
Predicates = predicates
)
output_status_message("UserInvitations:")
output_array_of_userinvitation(user_invitations)
# 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.
output_status_message("-----\nGetUsersInfo:")
users_info = customer_service.GetUsersInfo(
CustomerId=authorization_data.customer_id,
StatusFilter=None)
output_status_message("UsersInfo:")
output_array_of_userinfo(users_info)
for info in users_info['UserInfo']:
output_status_message("-----\nGetUser:")
get_user_response=customer_service.GetUser(
UserId=info.Id)
user = get_user_response.User
customer_roles=get_user_response.CustomerRoles
output_status_message("User:")
output_user(user)
output_status_message("CustomerRoles:")
output_array_of_customerrole(customer_roles)
except WebFault as ex:
output_webfault_errors(ex)
except Exception as ex:
output_status_message(ex)
# Main execution
if __name__ == '__main__':
print("Loading the web service client proxies...")
authorization_data=AuthorizationData(
account_id=None,
customer_id=None,
developer_token=DEVELOPER_TOKEN,
authentication=None,
)
customer_service=ServiceClient(
service='CustomerManagementService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
authenticate(authorization_data)
main(authorization_data)