Edit

Customer Signup Code Example

This example demonstrates how an aggregator can call SignupCustomer to create a new customer and account.

Tip

Use the language selector in the documentation header to choose C#, Java, Php, or Python.

To get access and refresh tokens for your Microsoft Advertising user and make your first service call using the Bing Ads API, see the Quick Start guide. You'll want to review the Get Started guide and walkthroughs for your preferred language e.g., C#, Java, Php, and Python.

Supporting files for C#, Java, Php, and Python examples are available at GitHub. You can clone each repository or repurpose snippets as needed.

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

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How a reseller can call SignupCustomer to create a new customer and account.
    /// </summary>
    public class CustomerSignup : ExampleBase
    {
        public override string Description
        {
            get { return "Create new customer for reseller | Customer Management V13"; }
        }

        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

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

                OutputStatusMessage("-----\nGetUser:");
                var getUserResponse = await CustomerManagementExampleHelper.GetUserAsync(
                    userId: null);
                var user = getUserResponse.User;
                OutputStatusMessage("User:");
                CustomerManagementExampleHelper.OutputUser(user);
                OutputStatusMessage("CustomerRoles:");
                CustomerManagementExampleHelper.OutputArrayOfCustomerRole(getUserResponse.CustomerRoles);

                // Only a user with the aggregator role (33) can sign up new customers. 
                // If the user does not have the aggregator role, then do not continue.    
                
                if (!getUserResponse.CustomerRoles.Select(role => role.RoleId).Contains(33))
                {
                    OutputStatusMessage("Only a user with the aggregator role (33) can sign up new customers.");
                    return;
                }
                
                var customer = new Customer
                {
                    // The primary business segment of the customer, for example, automotive, food, or entertainment.
                    Industry = Industry.Other,

                    // The primary country where the customer operates. 
                    MarketCountry = "US",

                    // The primary language that the customer uses. 
                    MarketLanguage = LanguageType.English,

                    // The name of the customer. 
                    Name = "Child Customer " + DateTime.UtcNow,
                };
                
                var account = new AdvertiserAccount
                {
                    // The location where your business is legally registered. 
                    // The business address is used to determine your tax requirements.
                    BusinessAddress = new Address
                    {
                        BusinessName = "Contoso",
                        City = "Redmond",
                        Line1 = "One Microsoft Way",
                        CountryCode = "US",
                        PostalCode = "98052",
                        StateOrProvince = "WA",                        
                    },

                    // The type of currency that is used to settle the account. 
                    // The service uses the currency information for billing purposes.
                    CurrencyCode = CurrencyCode.USD,

                    // The name of the account. 
                    Name = "Child Account " + DateTime.UtcNow,

                    // The identifier of the customer that owns the account. 
                    ParentCustomerId = (long)user.CustomerId,

                    // The TaxId (VAT identifier) is optional. If specified, The VAT identifier must be valid 
                    // in the country that you specified in the BusinessAddress element. Without a VAT registration 
                    // number or exemption certificate, taxes might apply based on your business location.
                    TaxInformation = null,

                    // The default time-zone for campaigns in this account.
                    TimeZone = TimeZoneType.PacificTimeUSCanadaTijuana,
                };

                // Signup a new customer and account for the reseller. 
                OutputStatusMessage("-----\nSignupCustomer:");
                var signupCustomerResponse = await CustomerManagementExampleHelper.SignupCustomerAsync(
                    customer: customer,
                    account: account,
                    parentCustomerId: user.CustomerId,
                    userInvitation: null,
                    userId: null);

                OutputStatusMessage("New Customer and Account:");

                // This is the identifier that you will use to set the CustomerId 
                // element in most of the Bing Ads API service operations.
                OutputStatusMessage(string.Format("\tCustomerId: {0}", signupCustomerResponse.CustomerId));

                // The read-only system-generated customer number that is used in the Microsoft Advertising web application. 
                // The customer number is of the form, Cnnnnnnn, where nnnnnnn is a series of digits.
                OutputStatusMessage(string.Format("\tCustomerNumber: {0}", signupCustomerResponse.CustomerNumber));

                // This is the identifier that you will use to set the AccountId and CustomerAccountId 
                // elements in most of the Bing Ads API service operations.
                OutputStatusMessage(string.Format("\tAccountId: {0}", signupCustomerResponse.AccountId));

                // The read-only system generated account number that is used to identify the account in the Microsoft Advertising web application. 
                // The account number has the form xxxxxxxx, where xxxxxxxx is a series of any eight alphanumeric characters.
                OutputStatusMessage(string.Format("\tAccountNumber: {0}", signupCustomerResponse.AccountNumber));
            }
            // 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 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 (FaultException<Microsoft.BingAds.V13.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
    }
}
package com.microsoft.bingads.examples.v13;

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

public class CustomerSignup extends ExampleBase {
        
    public static void main(java.lang.String[] args) {
     
        try
        {
            authorizationData = getAuthorizationData();
                         
            CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient<ICustomerManagementService>(
                    authorizationData, 
                    API_ENVIRONMENT,
                    ICustomerManagementService.class);
            
            outputStatusMessage("-----\nGetUser:");
            GetUserResponse getUserResponse = CustomerManagementExampleHelper.getUser(
                    null);
            User user = getUserResponse.getUser();
            outputStatusMessage("User:");
            CustomerManagementExampleHelper.outputUser(user);
            outputStatusMessage("CustomerRoles:");
            CustomerManagementExampleHelper.outputArrayOfCustomerRole(getUserResponse.getCustomerRoles());
                            
            // Only a user with the aggregator role (33) can sign up new customers. 
            // If the user does not have the aggregator role, then do not continue.
            
            ArrayOfint roleIds = new ArrayOfint();
            for(CustomerRole customerRole : getUserResponse.getCustomerRoles().getCustomerRoles()){
                roleIds.getInts().add(customerRole.getRoleId());
            }
            if(!roleIds.getInts().contains(33))
            {
                outputStatusMessage("Only a user with the aggregator role (33) can sign up new customers.");
                return;
            }

            Customer customer = new Customer();

            // The primary business segment of the customer, for example, automotive, food, or entertainment.
            customer.setIndustry(Industry.OTHER);

            // The primary country where the customer operates. 
            customer.setMarketCountry("US");

            // The primary language that the customer uses. 
            customer.setMarketLanguage(LanguageType.ENGLISH);

            // The name of the customer.
            customer.setName("Child Customer " + System.currentTimeMillis());
                        
            AdvertiserAccount account = new AdvertiserAccount();

            // The location where your business is legally registered. 
            // The business address is used to determine your tax requirements.
            Address businessAddress = new Address();
            businessAddress.setBusinessName("Contoso");
            businessAddress.setCity("Redmond");
            businessAddress.setLine1("One Microsoft Way");
            businessAddress.setPostalCode("98052");
            businessAddress.setStateOrProvince("WA");
            account.setBusinessAddress(businessAddress);

            // The type of currency that is used to settle the account. 
            // The service uses the currency information for billing purposes.
            account.setCurrencyCode(CurrencyCode.USD);

            // The name of the account. 
            account.setName("Child Account " + System.currentTimeMillis());

            // The identifier of the customer that owns the account. 
            account.setParentCustomerId((long)user.getCustomerId());

            // The TaxInformation (VAT identifier) is optional. If specified, The VAT identifier must be valid 
            // in the country that you specified in the BusinessAddress element. Without a VAT registration 
            // number or exemption certificate, taxes might apply based on your business location.
            account.setTaxInformation(null);

            // The default time-zone for campaigns in this account.
            account.setTimeZone(TimeZoneType.PACIFIC_TIME_US_CANADA_TIJUANA);
            
            // Signup a new customer and account for the reseller. 
            outputStatusMessage("-----\nSignupCustomer:");
            SignupCustomerResponse signupCustomerResponse = CustomerManagementExampleHelper.signupCustomer(
                customer,
                account,
                user.getCustomerId(),
                null,
                null);

            outputStatusMessage("New Customer and Account:");

            // This is the identifier that you will use to set the CustomerId 
            // element in most of the Bing Ads API service operations.
            outputStatusMessage(String.format("\tCustomerId: %s", signupCustomerResponse.getCustomerId()));

            // The read-only system-generated customer number that is used in the Bing Ads web application. 
            // The customer number is of the form, Cnnnnnnn, where nnnnnnn is a series of digits.
            outputStatusMessage(String.format("\tCustomerNumber: %s", signupCustomerResponse.getCustomerNumber()));

            // This is the identifier that you will use to set the AccountId and CustomerAccountId 
            // elements in most of the Bing Ads API service operations.
            outputStatusMessage(String.format("\tAccountId: %s", signupCustomerResponse.getAccountId()));

            // The read-only system generated account number that is used to identify the account in the Bing Ads web application. 
            // The account number has the form xxxxxxxx, where xxxxxxxx is a series of any eight alphanumeric characters.
            outputStatusMessage(String.format("\tAccountNumber: %s\n", signupCustomerResponse.getAccountNumber()));        
        } 
        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\Address;
use Microsoft\BingAds\V13\CustomerManagement\Customer;
use Microsoft\BingAds\V13\CustomerManagement\AdvertiserAccount;
use Microsoft\BingAds\V13\CustomerManagement\User;
use Microsoft\BingAds\V13\CustomerManagement\AutoTagType;
use Microsoft\BingAds\V13\CustomerManagement\CurrencyCode;
use Microsoft\BingAds\V13\CustomerManagement\Industry;
use Microsoft\BingAds\V13\CustomerManagement\LanguageType;
use Microsoft\BingAds\V13\CustomerManagement\TimeZoneType;

// 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;

try
{
    // Authenticate user credentials and set the account ID for the sample.  
    AuthHelper::Authenticate();

    print("-----\r\nGetUser:\r\n");
    $getUserResponse = CustomerManagementExampleHelper::GetUser(
        null, 
        true
    );
    $user = $getUserResponse->User;
    print("User:");
    CustomerManagementExampleHelper::OutputUser($user);
    print("CustomerRoles:");
    CustomerManagementExampleHelper::OutputArrayOfCustomerRole($getUserResponse->CustomerRoles);
    
    // Only a user with the aggregator role (33) can sign up new customers. 
    // If the user does not have the aggregator role, then do not continue.    
    $roleIds = array();
    foreach ($getUserResponse->CustomerRoles->CustomerRole as $customerRole)
    {
        $roleIds[] = $customerRole->RoleId;
    }
    if (!(in_array(33, $roleIds))){
        print "Only a user with the aggregator role (33) can sign up new customers.";
        return;
    }
    
    $customer = new Customer();

    // The primary business segment of the customer, for example, automotive, food, or entertainment.
    $customer->Industry = Industry::Other;

    // The primary country where the customer operates. 
    $customer->MarketCountry = "US";

    // The primary language that the customer uses. 
    $customer->MarketLanguage = LanguageType::English;

    // The name of the customer. 
    $customer->Name = "Child Customer " . $_SERVER['REQUEST_TIME'];
    
    $account = new AdvertiserAccount();

    // The location where your business is legally registered. 
    // The business address is used to determine your tax requirements.   
    $businessAddress = new Address();
    $businessAddress->City = "Redmond";
    $businessAddress->Line1 = "One Microsoft Way";
    $businessAddress->CountryCode = "US";
    $businessAddress->PostalCode = "98052";
    $businessAddress->StateOrProvince = "WA"; 
    $account->BusinessAddress = $businessAddress;

    // The type of currency that is used to settle the account. 
    // The service uses the currency information for billing purposes.
    $account->CurrencyCode = CurrencyCode::USD;

    // The name of the account. 
    $account->Name = "Child Account " . $_SERVER['REQUEST_TIME'];

    // The identifier of the customer that owns the account. 
    $account->ParentCustomerId = $user->CustomerId;

    // The TaxInformation is optional. If specified, The tax information must be valid 
    // in the country that you specified in the BusinessAddress element. Without tax information 
    // or exemption certificate, taxes might apply based on your business location.
    $account->TaxInformation = null;

    // The default time-zone for campaigns in this account.
    $account->TimeZone = TimeZoneType::PacificTimeUSCanadaTijuana;
    
    // Signup a new customer and account for the reseller. 
    print("-----\r\nSignupCustomer:\r\n");
    $signupCustomerResponse = CustomerManagementExampleHelper::SignupCustomer(
        $customer,
        $account,
        $user->CustomerId,
        null,
        null
    );

    print "New Customer and Account:\r\n";

    // This is the identifier that you will use to set the CustomerId 
    // element in most of the Bing Ads API service operations.
    printf("CustomerId: %s\r\n", $signupCustomerResponse->CustomerId);

    // The read-only system-generated customer number that is used in the Bing Ads web application. 
    // The customer number is of the form, Cnnnnnnn, where nnnnnnn is a series of digits.
    printf("CustomerNumber: %s\r\n", $signupCustomerResponse->CustomerNumber);

    // This is the identifier that you will use to set the AccountId and CustomerAccountId 
    // elements in most of the Bing Ads API service operations.
    printf("AccountId: %s\r\n", $signupCustomerResponse->AccountId);

    // The read-only system generated account number that is used to identify the account in the Bing Ads web application. 
    // The account number has the form xxxxxxxx, where xxxxxxxx is a series of any eight alphanumeric characters.
    printf("AccountNumber: %s\n\n", $signupCustomerResponse->AccountNumber);
}
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()."\n\n";
        print $e->getTraceAsString()."\n\n";
    }
}
from auth_helper import *
from openapi_client.models.customer import *


def main(authorization_data):
    try:
        # 1. Get user and verify aggregator role
        print("-----\nGetUser:")
        get_user_request = GetUserRequest(
            UserId=None
        )
        
        user_response = customer_service.get_user(get_user_request)
        user = user_response.User
        
        print("GetUserResponse:")
        print(f"User: {user}")
        assert user is not None
        assert user.CustomerId is not None
        
        print("Checking if user has aggregator role...")
        role_ids = [role.RoleId for role in user_response.CustomerRoles]
        print(f"User Roles: {', '.join(map(str, role_ids))}")
        
        if 33 not in role_ids:
            raise Exception("Only a user with the aggregator role (33) can sign up new customers.")
        
        print("User has aggregator role, proceeding with signup...")
        
        # 2. Sign up a new customer
        print("\n-----\nSignupCustomer:")
        
        # Create customer
        customer = Customer(
            Name=f'Child Customer {str(uuid.uuid4())[:8]}',
            Industry='Other',
            MarketCountry='US',
            MarketLanguage='English'
        )
        
        # Create account with business address
        business_address = Address(
            City='Redmond',
            CountryCode='US',
            PostalCode='98052',
            StateOrProvince='WA',
            Line1='One Microsoft Way'
        )
        
        account = AdvertiserAccount(
            BusinessAddress=business_address,
            CurrencyCode='USDollar',
            Name=f'Child Account {str(uuid.uuid4())[:8]}',
            ParentCustomerId=user.CustomerId,
            TaxInformation=None,
            TimeZone='PacificTimeUSCanadaTijuana'
        )
        
        signup_request = SignupCustomerRequest(
            Customer=customer,
            Account=account,
            ParentCustomerId=user.CustomerId
        )
        
        signup_response = customer_service.signup_customer(signup_request)
        
        print("SignupCustomerResponse:")
        print(f"Customer ID: {signup_response.CustomerId}")
        print(f"Account ID: {signup_response.AccountId}")
        print(f"Customer Number: {signup_response.CustomerNumber}")
        print(f"Account Number: {signup_response.AccountNumber}")
        
        assert signup_response.CustomerId is not None
        assert signup_response.AccountId is not None
        assert signup_response.AccountNumber is not None
        assert signup_response.CustomerNumber is not None
        
        print(f"\nNew Customer ID: {signup_response.CustomerId}")
        print(f"New Account ID: {signup_response.AccountId}")
        print(f"New Customer Number: {signup_response.CustomerNumber}")
        print(f"New Account Number: {signup_response.AccountNumber}")
        
    except Exception as ex:
        print(f"Error occurred: {str(ex)}")
        import traceback
        traceback.print_exc()


if __name__ == '__main__':
    import uuid
    
    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)

See Also

Get Started with the Bing Ads API