ภาษา
หมายเหตุ
การเข้าถึงหน้านี้ต้องได้รับการอนุญาต คุณสามารถลอง ลงชื่อเข้าใช้หรือเปลี่ยนไดเรกทอรีได้
การเข้าถึงหน้านี้ต้องได้รับการอนุญาต คุณสามารถลองเปลี่ยนไดเรกทอรีได้
ตัวอย่างนี้แสดงวิธีใช้ข้อมูลประจําตัวของหน่วยงานเพื่อเชิญลูกค้า และการใช้ข้อมูลประจําตัวของลูกค้าเพื่อยอมรับคําเชิญ เรียกใช้ตัวอย่างนี้หลายๆ ครั้ง สลับไปมาระหว่างข้อมูลประจําตัวของตัวแทนและไคลเอ็นต์เพื่ออัปเดตและสังเกตการเปลี่ยนแปลงสถานะ ตัวอย่างเช่น จาก LinkPending เป็น LinkAccepted เป็น Active
เคล็ดลับ
ใช้ตัวเลือกภาษาในส่วนหัวของเอกสารประกอบเพื่อเลือก C#, Java, PHP หรือ Python
เมื่อต้องการรับการเข้าถึงและรีเฟรชโทเค็นสําหรับผู้ใช้ Microsoft Advertising ของคุณ และทําการเรียกใช้บริการครั้งแรกของคุณโดยใช้ Bing Ads API ให้ดูคู่มือเริ่มต้นใช้งานด่วน คุณจะต้องตรวจสอบคู่มือเริ่มต้นใช้งานและคําแนะนําสําหรับภาษาที่คุณต้องการ เช่น C#, Java, PHP และ Python
ไฟล์ที่สนับสนุนสําหรับตัวอย่าง C#, Java, PHP และ Python มีอยู่ที่ GitHub คุณสามารถโคลนแต่ละที่เก็บหรือนําส่วนย่อยไปใช้ใหม่ได้ตามต้องการ
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CustomerManagement;
using Microsoft.BingAds;
namespace BingAdsExamplesLibrary.V13
{
/// <summary>
/// How to use agency credentials to invite a client, and use client credentials to accept the invitation.
/// Run this sample multiple times alternating between agency and client credentials
/// to update and observe the status change, for example from LinkPending to LinkAccepted to Active.
/// </summary>
public class ClientLinks : ExampleBase
{
// REQUIRED: The Client Account Id that you want to access.
private long ClientAccountId = 0;
public override string Description
{
get { return "Manage Client | Customer Management V13"; }
}
public async override Task RunAsync(AuthorizationData authorizationData)
{
try
{
OutputStatusMessage("You must edit this example to provide the ClientAccountId for the client link." +
"When adding a client link, the client link's ManagingCustomerId is set to the CustomerId " +
"of the current authenticated user, who must be a Super Admin of the agency." +
"Login as an agency Super Admin user to send a client link invitation, or unlink an existing client link." +
"Login as a client Super Admin user to accept a client link invitation.");
ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;
CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(
OutputStatusMessageDefault: this.OutputStatusMessage);
CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient<ICustomerManagementService>(
authorizationData: authorizationData,
environment: environment);
UpdateClientLinksResponse updateClientLinksResponse = null;
// Set the client link search criteria.
var pageInfo = new Paging
{
Index = 0, // The first page
Size = 100 // The first 100 client links for this page of results
};
var ordering = new OrderBy
{
Field = OrderByField.Number,
Order = SortOrder.Ascending
};
var predicate = new Predicate
{
Field = "ClientAccountId",
Operator = PredicateOperator.In,
Value = ClientAccountId.ToString(CultureInfo.InvariantCulture)
};
// Search for client links that match the criteria.
OutputStatusMessage("-----\nSearchClientLinks:");
var searchClientLinksResponse = (await CustomerManagementExampleHelper.SearchClientLinksAsync(
predicates: new[] { predicate },
ordering: new[] { ordering },
pageInfo: pageInfo));
var clientLinks = searchClientLinksResponse?.ClientLinks;
OutputStatusMessage("ClientLinks:");
CustomerManagementExampleHelper.OutputArrayOfClientLink(clientLinks);
// Determine whether the agency is already managing the specified client account.
// If a link exists with status either Active, LinkInProgress, LinkPending,
// UnlinkInProgress, or UnlinkPending, the agency may not initiate a duplicate client link.
ClientLink clientLink;
var newLinkRequired = true;
if (clientLinks.Count > 0)
{
clientLink = clientLinks[0];
OutputStatusMessage("Using the first client link as an example.");
OutputStatusMessage(string.Format("Current ClientLink Status: {0}.", clientLink.Status));
switch (clientLink.Status)
{
// The agency may choose to initiate the unlink process,
// which would terminate the existing relationship with the client.
case ClientLinkStatus.Active:
clientLink.Status = ClientLinkStatus.UnlinkRequested;
OutputStatusMessage("-----\nUpdateClientLinks:");
updateClientLinksResponse = await CustomerManagementExampleHelper.UpdateClientLinksAsync(
clientLinks: new[] { clientLink });
OutputStatusMessage("UnlinkRequested");
newLinkRequired = false;
break;
// Waiting on a system status transition or waiting for the StartDate.
case ClientLinkStatus.LinkAccepted:
OutputStatusMessage("The status is transitioning towards LinkInProgress");
newLinkRequired = false;
break;
// Waiting on a system status transition.
case ClientLinkStatus.LinkInProgress:
OutputStatusMessage("The status is transitioning towards Active");
newLinkRequired = false;
break;
// When the status is LinkPending, either the agency or client may update the status.
// The agency may choose to cancel the client link invitation; however, in this example
// the client will accept the invitation.
// If the client does not accept or decline the invitation within 30 days, and if the agency
// does not update the status to LinkCanceled, the system updates the status to LinkExpired.
case ClientLinkStatus.LinkPending:
clientLink.Status = ClientLinkStatus.LinkAccepted;
OutputStatusMessage("-----\nUpdateClientLinks:");
updateClientLinksResponse = await CustomerManagementExampleHelper.UpdateClientLinksAsync(
clientLinks: new[] { clientLink });
OutputStatusMessage("LinkAccepted");
newLinkRequired = false;
break;
// Waiting on a system status transition.
case ClientLinkStatus.UnlinkInProgress:
OutputStatusMessage("The status is transitioning towards Inactive");
newLinkRequired = false;
break;
// Waiting on a system status transition.
case ClientLinkStatus.UnlinkPending:
OutputStatusMessage("The status is transitioning towards Inactive");
newLinkRequired = false;
break;
// The link lifecycle has ended.
default:
OutputStatusMessage("A new client link invitation is required");
break;
}
// Output errors if any occurred when updating the client link.
if (updateClientLinksResponse != null)
{
OutputStatusMessage("OperationErrors:");
CustomerManagementExampleHelper.OutputArrayOfOperationError(updateClientLinksResponse.OperationErrors);
OutputStatusMessage("PartialErrors:");
foreach (List<OperationError> operationErrors in updateClientLinksResponse.PartialErrors)
{
CustomerManagementExampleHelper.OutputArrayOfOperationError(operationErrors);
}
}
}
// If no links exist between the agency and specified client account, or a link exists with status
// either Inactive, LinkCanceled, LinkDeclined, LinkExpired, or LinkFailed, then the agency must
// initiate a new client link.
if (newLinkRequired)
{
clientLink = new ClientLink
{
ClientEntityId = ClientAccountId,
ManagingCustomerId = authorizationData.CustomerId,
IsBillToClient = true,
Name = "My Client Link",
StartDate = null,
SuppressNotification = true
};
OutputStatusMessage("-----\nAddClientLinks:");
var addClientLinksResponse = await CustomerManagementExampleHelper.AddClientLinksAsync(
clientLinks: new[] { clientLink });
OutputStatusMessage("OperationErrors:");
CustomerManagementExampleHelper.OutputArrayOfOperationError(addClientLinksResponse.OperationErrors);
OutputStatusMessage("PartialErrors:");
foreach (List<OperationError> operationErrors in addClientLinksResponse.PartialErrors)
{
CustomerManagementExampleHelper.OutputArrayOfOperationError(operationErrors);
}
}
// Output the client links after any status updates above.
OutputStatusMessage("-----\nSearchClientLinks:");
searchClientLinksResponse = (await CustomerManagementExampleHelper.SearchClientLinksAsync(
predicates: new[] { predicate },
ordering: new[] { ordering },
pageInfo: pageInfo));
clientLinks = searchClientLinksResponse?.ClientLinks;
OutputStatusMessage("ClientLinks:");
CustomerManagementExampleHelper.OutputArrayOfClientLink(clientLinks);
}
// 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.*;
// How to use agency credentials to invite a client,
// and use client credentials to accept the invitation.
// Run this sample multiple times alternating between agency and client credentials
// to update and observe the status change, for example from LinkPending to LinkAccepted to Active.
public class ClientLinks extends ExampleBase {
static AuthorizationData authorizationData;
// REQUIRED: The Client Account Id that you want to access.
private static long ClientAccountId = 0;
public static void main(java.lang.String[] args) {
try
{
authorizationData = getAuthorizationData();
CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient<ICustomerManagementService>(
authorizationData,
API_ENVIRONMENT,
ICustomerManagementService.class);
outputStatusMessage("You must edit this example to provide the ClientAccountId for the client link." +
"When adding a client link, the client link's ManagingCustomerId is set to the CustomerId " +
"of the current authenticated user, who must be a Super Admin of the agency." +
"Login as an agency Super Admin user to send a client link invitation, or unlink an existing client link." +
"Login as a client Super Admin user to accept a client link invitation.");
UpdateClientLinksResponse updateClientLinksResponse = null;
// Set the client link search criteria.
Paging pageInfo = new Paging();
pageInfo.setIndex(0); // The first page
pageInfo.setSize(100); // The first 100 client links for this page of results
ArrayOfOrderBy ordering = new ArrayOfOrderBy();
OrderBy orderBy = new OrderBy();
orderBy.setField(OrderByField.NUMBER);
orderBy.setOrder(SortOrder.ASCENDING);
ordering.getOrderBies().add(orderBy);
ArrayOfPredicate predicates = new ArrayOfPredicate();
Predicate predicate = new Predicate();
predicate.setField("ClientAccountId");
predicate.setOperator(PredicateOperator.IN);
predicate.setValue("" + ClientAccountId);
predicates.getPredicates().add(predicate);
// Search for client links that match the criteria.
outputStatusMessage("-----\nSearchClientLinks:");
ArrayOfClientLink clientLinks = CustomerManagementExampleHelper.searchClientLinks(
predicates,
ordering,
pageInfo).getClientLinks();
outputStatusMessage("ClientLinks:");
CustomerManagementExampleHelper.outputArrayOfClientLink(clientLinks);
// Determine whether the agency is already managing the specified client account.
// If a link exists with status either Active, LinkInProgress, LinkPending,
// UnlinkInProgress, or UnlinkPending, the agency may not initiate a duplicate client link.
ClientLink clientLink;
boolean newLinkRequired = true;
if (clientLinks.getClientLinks().size() > 0)
{
clientLink = clientLinks.getClientLinks().get(0);
outputStatusMessage("Using the first client link as an example.");
outputStatusMessage(String.format("Current ClientLink Status: %s.", clientLink.getStatus()));
ArrayOfClientLink updateClientLinks = new ArrayOfClientLink();
switch (clientLink.getStatus())
{
// The agency may choose to initiate the unlink process,
// which would terminate the existing relationship with the client.
case ACTIVE:
clientLink.setStatus(ClientLinkStatus.UNLINK_REQUESTED);
updateClientLinks.getClientLinks().add(clientLink);
outputStatusMessage("-----\nUpdateClientLinks:");
updateClientLinksResponse = CustomerManagementExampleHelper.updateClientLinks(
updateClientLinks);
outputStatusMessage("UpdateClientLinks : UnlinkRequested.");
newLinkRequired = false;
break;
// Waiting on a system status transition or waiting for the StartDate.
case LINK_ACCEPTED:
outputStatusMessage("The status is transitioning towards LinkInProgress.");
newLinkRequired = false;
break;
// Waiting on a system status transition.
case LINK_IN_PROGRESS:
outputStatusMessage("The status is transitioning towards Active.");
newLinkRequired = false;
break;
// When the status is LinkPending, either the agency or client may update the status.
// The agency may choose to cancel the client link invitation; however, in this example
// the client will accept the invitation.
// If the client does not accept or decline the invitation within 30 days, and if the agency
// does not update the status to LinkCanceled, the system updates the status to LinkExpired.
case LINK_PENDING:
clientLink.setStatus(ClientLinkStatus.LINK_ACCEPTED);
updateClientLinks.getClientLinks().add(clientLink);
outputStatusMessage("-----\nUpdateClientLinks:");
updateClientLinksResponse = CustomerManagementExampleHelper.updateClientLinks(
updateClientLinks);
outputStatusMessage("UpdateClientLinks: LinkAccepted.");
newLinkRequired = false;
break;
// Waiting on a system status transition.
case UNLINK_IN_PROGRESS:
outputStatusMessage("The status is transitioning towards Inactive.");
newLinkRequired = false;
break;
// Waiting on a system status transition.
case UNLINK_PENDING:
outputStatusMessage("The status is transitioning towards Inactive.");
newLinkRequired = false;
break;
// The link lifecycle has ended.
default:
outputStatusMessage("A new client link invitation is required.");
break;
}
// Print errors if any occurred when updating the client link.
if (updateClientLinksResponse != null)
{
outputStatusMessage("OperationErrors:");
CustomerManagementExampleHelper.outputArrayOfOperationError(updateClientLinksResponse.getOperationErrors());
outputStatusMessage("PartialErrors:");
for(ArrayOfOperationError operationErrors: updateClientLinksResponse.getPartialErrors().getArrayOfOperationErrors())
{
CustomerManagementExampleHelper.outputArrayOfOperationError(operationErrors);
}
}
}
// If no links exist between the agency and specified client account, or a link exists with status
// either Inactive, LinkCanceled, LinkDeclined, LinkExpired, or LinkFailed, then the agency must
// initiate a new client link.
if(newLinkRequired)
{
clientLink = new ClientLink();
clientLink.setClientEntityId(ClientAccountId);
clientLink.setManagingCustomerId(authorizationData.getCustomerId());
clientLink.setIsBillToClient(true);
clientLink.setName("My Client Link");
clientLink.setStartDate(null);
clientLink.setSuppressNotification(true);
ArrayOfClientLink addClientLinks = new ArrayOfClientLink();
addClientLinks.getClientLinks().add(clientLink);
outputStatusMessage("-----\nAddClientLinks:");
AddClientLinksResponse addClientLinksResponse = CustomerManagementExampleHelper.addClientLinks(
addClientLinks);
outputStatusMessage("OperationErrors:");
CustomerManagementExampleHelper.outputArrayOfOperationError(addClientLinksResponse.getOperationErrors());
outputStatusMessage("PartialErrors:");
for(ArrayOfOperationError operationErrors: addClientLinksResponse.getPartialErrors().getArrayOfOperationErrors())
{
CustomerManagementExampleHelper.outputArrayOfOperationError(operationErrors);
}
}
// Output the client links after any status updates above.
outputStatusMessage("-----\nSearchClientLinks:");
clientLinks = CustomerManagementExampleHelper.searchClientLinks(
predicates,
ordering,
pageInfo).getClientLinks();
outputStatusMessage("ClientLinks:");
CustomerManagementExampleHelper.outputArrayOfClientLink(clientLinks);
}
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\ClientLink;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\ClientLinkStatus;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\AddClientLinksRequest;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\UpdateClientLinksRequest;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\SearchClientLinksRequest;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\Paging;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\Predicate;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\PredicateOperator;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\OrderBy;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\OrderByField;
use Microsoft\MsAds\Rest\Model\CustomerManagementService\SortOrder;
use Microsoft\MsAds\Rest\Test\RestApiTestBase;
class ClientLinksTest extends RestApiTestBase
{
// You must edit this example to provide the ClientAccountId for the client link.
// When adding a client link, the client link's ManagingCustomerId is set to the CustomerId
// of the current authenticated user, who must be a Super Admin of the agency.
// Login as an agency Super Admin user to send a client link invitation, or unlink an existing client link.
// Login as a client Super Admin user to accept a client link invitation.
protected int $clientAccountId = 0; // Set this to a valid client account ID
/**
* @throws ApiException
*/
public function testSearchClientLinks()
{
print("-----\r\nSearchClientLinks:\r\n");
$paging = new Paging();
$paging->setIndex(0);
$paging->setSize(100);
$predicate = new Predicate();
$predicate->setField("ClientAccountId");
$predicate->setOperator(PredicateOperator::IN);
$predicate->setValue((string)$this->clientAccountId);
$orderBy = new OrderBy();
$orderBy->setField(OrderByField::NUMBER);
$orderBy->setOrder(SortOrder::ASCENDING);
$request = new SearchClientLinksRequest([
'Predicates' => [$predicate],
'Ordering' => [$orderBy],
'PageInfo' => $paging
]);
$response = self::$customerManagementServiceApi->searchClientLinks($request);
$clientLinks = $response->getClientLinks();
print("ClientLinks:\r\n");
print_r($clientLinks);
self::assertIsArray($clientLinks);
return $clientLinks;
}
/**
* @depends testSearchClientLinks
* @throws ApiException
*/
public function testAddClientLink($clientLinks)
{
$newLinkRequired = true;
$existingLink = null;
if (!empty($clientLinks)) {
$existingLink = $clientLinks[0];
if (in_array($existingLink->getStatus(), [
ClientLinkStatus::ACTIVE,
ClientLinkStatus::LINK_IN_PROGRESS,
ClientLinkStatus::LINK_PENDING,
ClientLinkStatus::UNLINK_IN_PROGRESS,
ClientLinkStatus::UNLINK_PENDING,
ClientLinkStatus::LINK_ACCEPTED
])) {
$newLinkRequired = false;
}
}
if ($newLinkRequired) {
$clientLink = new ClientLink();
$clientLink->setClientEntityId($this->clientAccountId);
$clientLink->setManagingCustomerId(self::CUSTOMER_ID);
$clientLink->setIsBillToClient(true);
$clientLink->setName("My Client Link" . self::generateRandomAlphaNumeric());
$clientLink->setStartDate(null);
$clientLink->setSuppressNotification(false);
print("-----\r\nAddClientLinks:\r\n");
$request = new AddClientLinksRequest([
'ClientLinks' => [$clientLink]
]);
$response = self::$customerManagementServiceApi->addClientLinks($request);
print("OperationErrors:\r\n");
print_r($response->getOperationErrors());
print("PartialErrors:\r\n");
print_r($response->getPartialErrors());
self::assertEmpty($response->getOperationErrors());
} else {
print("A new client link is not required.\r\n");
}
}
/**
* @depends testSearchClientLinks
* @throws ApiException
*/
public function testUpdateClientLink($clientLinks)
{
if (empty($clientLinks)) {
self::markTestSkipped('No client links to update.');
}
$clientLink = $clientLinks[0];
$status = $clientLink->getStatus();
$update = false;
if ($status === ClientLinkStatus::ACTIVE) {
$clientLink->setStatus(ClientLinkStatus::UNLINK_REQUESTED);
$update = true;
} elseif ($status === ClientLinkStatus::LINK_PENDING) {
$clientLink->setStatus(ClientLinkStatus::LINK_ACCEPTED);
$update = true;
}
if ($update) {
print("-----\r\nUpdateClientLinks:\r\n");
$request = new UpdateClientLinksRequest([
'ClientLinks' => [$clientLink]
]);
$response = self::$customerManagementServiceApi->updateClientLinks($request);
print("OperationErrors:\r\n");
print_r($response->getOperationErrors());
print("PartialErrors:\r\n");
print_r($response->getPartialErrors());
self::assertEmpty($response->getOperationErrors());
} else {
print("No update required for client link status: $status\r\n");
}
}
}
from auth_helper import *
from openapi_client.models.customer import *
import uuid
def main(authorization_data):
try:
# Add client links
client_link = ClientLink(
client_entity_id=authorization_data.account_id,
managing_customer_id=authorization_data.customer_id,
is_bill_to_client=True,
name="Test client link" + str(uuid.uuid4()),
start_date=None,
suppress_notification=False
)
add_request = AddClientLinksRequest(client_links=[client_link])
add_response = customer_service.add_client_links(add_client_links_request=add_request)
assert isinstance(add_response,
AddClientLinksResponse), "add_response is not an instance of AddInsertionOrderResponse"
# Search client links
paging = Paging(index=0, size=100)
predicate = Predicate(
field='ClientAccountId',
operator=PredicateOperator.IN,
value=authorization_data.account_id
)
order_by = OrderBy(field=OrderByField.NUMBER, order=SortOrder.ASCENDING)
request = SearchClientLinksRequest(
predicates=[predicate],
ordering=[order_by],
page_info=paging
)
response = customer_service.search_client_links(search_client_links_request=request)
client_links = response.client_links
assert (len(client_links) > 0)
except Exception as ex:
print(f"Error occurred: {str(ex)}")
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)