Partilhar via


Exemplo de Código de Inscrição do Cliente

Este exemplo demonstra como um agregador pode chamar SignupCustomer para criar um novo cliente e conta.

Sugestão

Utilize o seletor de idiomas no cabeçalho da documentação para escolher C#, Java, Php ou Python.

Para obter tokens de acesso e atualização para o seu utilizador do Microsoft Advertising e fazer a sua primeira chamada de serviço com a API de Anúncios do Bing, veja o Guia de Introdução . Vai querer rever o guia de Introdução e instruções para o seu idioma preferido, por exemplo, C#, Java, Php e Python.

Os ficheiros de suporte para exemplos de C#, Java, Php e Python estão disponíveis no GitHub. Pode clonar cada repositório ou reutilizar fragmentos conforme necessário.

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 customermanagement_example_helper import *

# You must provide credentials in auth_helper.py.

def main(authorization_data):

    try:
        output_status_message("-----\nGetUser:")
        get_user_response=customer_service.GetUser(
            UserId=None
        )
        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)

        # 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.

        role_ids=[]
        for customer_role in customer_roles['CustomerRole']:
            role_ids.append(customer_role.RoleId)
        if(not 33 in role_ids):
            output_status_message("Only a user with the aggregator role (33) can sign up new customers.")
            exit(0)
        
        customer = customer_service.factory.create('ns5:Customer')

        # The primary business segment of the customer, for example, automotive, food, or entertainment.
        customer.Industry = 'Other'

        # The primary country where the customer operates. 
        customer.MarketCountry = 'US'

        # The primary language that the customer uses. 
        customer.MarketLanguage = 'English'

        # The name of the customer. 
        customer.Name = "Child Customer " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

        # SUDS requires that you set unused value sets to None
        customer.CustomerFinancialStatus=None
        customer.ServiceLevel=None
        customer.CustomerLifeCycleStatus=None
        
        account=customer_service.factory.create('ns5:AdvertiserAccount')
        
        # The location where your business is legally registered. 
        # The business address is used to determine your tax requirements.
        business_address = customer_service.factory.create('ns5:Address')
        business_address.City = "Redmond"
        business_address.Line1 = "One Microsoft Way"
        business_address.CountryCode = "US"
        business_address.PostalCode = "98052"
        business_address.StateOrProvince = "WA"
        account.BusinessAddress = business_address

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

        # The name of the account. 
        account.Name = "Child Account " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

        # The identifier of the customer that owns the account. 
        account.ParentCustomerId = user.CustomerId

        # The TaxInformation (e.g. VAT number) is optional. If specified, The VAT number 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.TaxInformation = None

        # The default time-zone for campaigns in this account.
        account.TimeZone = 'PacificTimeUSCanadaTijuana'

        # SUDS requires that you set unused value sets to None
        account.AccountFinancialStatus=None
        account.AccountLifeCycleStatus=None
        account.AutoTagType=None
        account.Language=None
        account.PaymentMethodType=None

        # Signup a new customer and account for the reseller. 
        output_status_message("-----\nSignupCustomer:")
        signup_customer_response=customer_service.SignupCustomer(
            Customer=customer,
            Account=account,
            ParentCustomerId=user.CustomerId
        )

        output_status_message("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.
        output_status_message("\tCustomerId: {0}".format(signup_customer_response.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.
        output_status_message("\tCustomerNumber: {0}".format(signup_customer_response.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.
        output_status_message("\tAccountId: {0}".format(signup_customer_response.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.
        output_status_message("\tAccountNumber: {0}".format(signup_customer_response.AccountNumber))
    
    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)

See Also

Introdução à API de Anúncios do Bing