本指南旨在協助您運用專為轉換 API 用戶設計的 Meta 商業 SDK 進階功能。非同步要求、並行批次處理和 HTTP 服務介面可用於 PHP、NodeJS、Java、Python 和 Ruby SDK。若要瞭解基本的轉換 API 用法,請參閱主要轉換 API 說明文件。
Meta 商業 SDK 可讓您存取我們的商業 API 套件,以建置專屬和客製化的解決方案,為您的企業和客戶提供服務。轉換 API 就是可供 SDK 用戶使用的 API 之一。
您必須先安裝 Meta 商業 SDK,才能使用下列任一功能。請參閱 Meta 商業 SDK 新手指南,或按照下列 README
指示操作:
facebook-nodejs-business-sdk
facebook-python-business-sdk
使用這些功能所需的最低語言版本:
如果您不想阻擋程式執行以等待要求完成,可以使用此功能。此方法可讓您發出要求,並在要求完成後取得伺服器傳回的訊號。等待回應時,程式可以繼續執行。
非同步要求可讓您更有效運用資源,進而縮短伺服器回應時間。此外,您也能進一步控制程式如何處理伺服器傳回的錯誤,並可輕鬆將 SDK 整合至已非同步執行的程式碼中。
若要實作非同步要求,請參閱下列語言的程式碼範例:
use FacebookAds\Api;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\EventRequestAsync;
use FacebookAds\Object\ServerSide\UserData;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise;
$pixel_id = getenv('PIXEL_ID');
$access_token = getenv('ACCESS_TOKEN');
if (empty($pixel_id) || empty($access_token)) {
throw new Exception('Missing required test config. Got pixel_id: "' . $pixel_id . '", access_token: "' . $access_token . '"');
}
Api::init(null, null, $access_token, false);
function create_events($num) {
$user_data = (new UserData())
->setEmail('joe' . $num . '@eg.com')
->setClientIpAddress($_SERVER['REMOTE_ADDR'])
->setClientUserAgent($_SERVER['HTTP_USER_AGENT']);
$custom_data = (new CustomData())
->setCurrency('usd')
->setValue(123.45);
$event = (new Event())
->setEventName('Purchase')
->setEventTime(time())
->setEventSourceUrl('http://jaspers-market.com/product/123')
->setUserData($user_data)
->setCustomData($custom_data)
->setActionSource(ActionSource::WEBSITE);
return array($event);
}
function create_async_request($pixel_id, $num) {
$async_request = (new EventRequestAsync($pixel_id))
->setEvents(create_events($num));
return $async_request->execute()
->then(
null,
function (RequestException $e) {
print(
"Error!!!\n" .
$e->getMessage() . "\n" .
$e->getRequest()->getMethod() . "\n"
);
}
);
}
// Async request:
$promise = create_async_request($pixel_id, 2);
print("Request 1 state: " . $promise->getState() . "\n");
print("Async request - OK.\n");
// Async request with wait:
$promise = create_async_request($pixel_id, 3);
$response2 = $promise->wait();
print("Request 2: " . $response2->getBody() . "\n");
print("Async request with wait - OK.\n");
// Multiple async requests:
$promises = [
"Request 3" => create_async_request($pixel_id, 4),
"Request 4" => create_async_request($pixel_id, 5),
];
$response3 = Promise\unwrap($promises);
foreach ($response3 as $request_name => $response) {
print($request_name . ": " . $response->getBody()."\n");
}
print("Async - Multiple async requests OK.\n");
並行批次處理運用非同步要求,能夠更有效地利用資源,進而提高傳輸量。您可以建立批次要求來支援事件要求工作者、cron job(排程工作)等使用案例。
您有下列 BatchProcessor
方法可以選擇:
方法 | 使用時機 |
---|---|
| 此方法可用來處理具有相同最上層 |
| 這是 此方法也可以用來處理具有相同最上層 |
| 當您想要為每個要求指定不同的 |
| 這是 當您想要為每個要求指定不同的 |
使用並行批次處理時,應盡可能即時傳送事件。如需詳細資訊,請參閱分享頻率。
如果您使用 PHP、Python 或 Ruby SDK,則上述方法需要 EventRequestAsync 物件,而不是 EventRequest。
若要實作並行批次處理,請參閱下列語言的程式碼範例:
use FacebookAds\Api;
use FacebookAds\Object\ServerSide\BatchProcessor;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequestAsync;
use FacebookAds\Object\ServerSide\UserData;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise;
$pixel_id = getenv('PIXEL_ID');
$access_token = getenv('ACCESS_TOKEN');
if (empty($pixel_id) || empty($access_token)) {
throw new Exception('Missing required test config. Got pixel_id: "' . $pixel_id . '", access_token: "' . $access_token . '"');
}
$api = Api::init(null, null, $access_token, false);
function create_event($i) {
$user_data = (new UserData())
->setEmail('joe' . $i . '@eg.com')
->setClientIpAddress($_SERVER['REMOTE_ADDR'])
->setClientUserAgent($_SERVER['HTTP_USER_AGENT']);
$custom_data = (new CustomData())
->setCurrency('usd')
->setValue(123.45);
return (new Event())
->setEventName('Purchase')
->setEventTime(time())
->setEventSourceUrl('http://jaspers-market.com/product/' . $i)
->setUserData($user_data)
->setCustomData($custom_data)
->setActionSource(ActionSource::WEBSITE);
}
function create_events($num) {
$events = [];
for ($i = 0; $i < $num; $i++) {
$events[] = create_event($i);
}
return $events;
}
function create_async_requests($pixel_id, $num) {
$requests = [];
for ($i = 0; $i < $num; $i++) {
$requests[] = (new EventRequestAsync($pixel_id))
->setUploadTag('test-tag-2')
->setEvents([create_event($i)]);
}
return $requests;
}
function run($pixel_id) {
print("Started CONVERSIONS_API_EVENT_CREATE_BATCH...\n");
$batch_processor = new BatchProcessor($pixel_id, 2, 2);
// processEvents
$events = create_events(11);
$batch_processor->processEvents(array('upload_tag' => 'test-tag-1'), $events);
// processEventRequests
$requests = create_async_requests($pixel_id, 5);
$batch_processor->processEventRequests($requests);
// processEventsGenerator
$process_events_generator = $batch_processor->processEventsGenerator(array('upload_tag' => 'test-tag-1'), $events);
foreach ($process_events_generator as $promises) {
try {
Promise\unwrap($promises);
} catch (RequestException $e) {
print('RequestException: ' . $e->getResponse()->getBody()->getContents() . "\n");
throw $e;
} catch (\Exception $e) {
print("Exception:\n");
print_r($e);
throw $e;
}
}
// processEventRequestsGenerator
$requests = create_async_requests($pixel_id, 5);
$process_event_requests_generator = $batch_processor->processEventRequestsGenerator($requests);
foreach ($process_event_requests_generator as $promises) {
try {
Promise\unwrap($promises);
} catch (RequestException $e) {
print('RequestException: ' . $e->getResponse()->getBody()->getContents() . "\n");
throw $e;
} catch (\Exception $e) {
print("Exception:\n");
print_r($e);
throw $e;
}
}
print("Finished CONVERSIONS_API_EVENT_CREATE_BATCH with no errors.\n");
}
run($pixel_id);
如果您對 HTTP 服務階層有一組特定需求,請使用 HTTP 服務介面。此功能可讓您覆寫商業 SDK 的預設 HTTP 服務,並使用您偏好的方法或程式庫來實作自己的自訂服務。
若要實作自己的 HTTP 服務介面,請參閱下列語言的程式碼範例:
require __DIR__ . '/../vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\EventRequestAsync;
use FacebookAds\Object\ServerSide\HttpServiceClientConfig;
use FacebookAds\Object\ServerSide\UserData;
// Imports used by the TestHttpClient class
use FacebookAds\Object\ServerSide\HttpServiceInterface;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
$pixel_id = getenv('PIXEL_ID');
$access_token = getenv('ACCESS_TOKEN');
if (empty($pixel_id) || empty($access_token)) {
throw new Exception('Missing required test config. Got pixel_id: "' . $pixel_id . '", access_token: "' . $access_token . '"');
}
function run($access_token, $pixel_id) {
Api::init(null, null, $access_token, false);
$request1 = getEventRequest($pixel_id, 1);
$request1->setHttpClient(new TestHttpClient());
$response1 = $request1->execute();
print("Response: " . $response1->getBody() . "\n");
print("Custom HTTP Service Request 1 - OK.\n");
// Alternatively, you can set the access_token and the HTTP Client on the HttpServiceClientConfig
Api::init(null, null, null, false);
HttpServiceClientConfig::getInstance()->setClient(new TestHttpClient());
HttpServiceClientConfig::getInstance()->setAccessToken($access_token);
$request2 = getEventRequest($pixel_id, 2);
$response2 = $request2->execute();
print("Response: " . $response2->getBody() . "\n");
print("Custom HTTP Service Request 2 - OK.\n");
}
function getEventRequest($pixel_id, $num) {
$user_data = (new UserData())
->setEmail('joe' . $num . '@eg.com')
->setClientIpAddress($_SERVER['REMOTE_ADDR'])
->setClientUserAgent($_SERVER['HTTP_USER_AGENT']);
$custom_data = (new CustomData())
->setCurrency('usd')
->setValue(123.45);
$event = (new Event())
->setEventName('Purchase')
->setEventTime(time())
->setEventSourceUrl('http://jaspers-market.com/product/123')
->setUserData($user_data)
->setCustomData($custom_data)
->setActionSource(ActionSource::WEBSITE);
return (new EventRequest($pixel_id))
->setEvents(array($event));
}
class TestHttpClient implements HttpServiceInterface {
public function executeRequest($url, $method, array $curl_options, array $headers, array $params) {
$multipart_contents = [];
foreach ($params as $key => $value) {
if ($key === 'data') {
$multipart_contents[] = [
'name' => $key,
'contents' => \GuzzleHttp\json_encode($value),
'headers' => array('Content-Type' => 'multipart/form-data'),
];
} else {
$multipart_contents[] = [
'name' => $key,
'contents' => $value,
'headers' => array('Content-Type' => 'multipart/form-data'),
];
}
}
$body = new MultipartStream($multipart_contents);
$request = new Request($method, $url, $headers, $body);
$handler_stack = HandlerStack::create(
new CurlHandler(['options' => $curl_options])
);
$client = new Client(['handler' => $handler_stack]);
return $client->send($request);
}
}
run($access_token, $pixel_id);
您可以使用 test_event_code
參數來測試您的事件要求。在事件管理工具中,前往資料來源 > 您的像素 > 測試事件頁籤下的「測試事件」工具,找到該測試程式碼。
注意:您必須將下面程式碼中的範例值(即 TEST12345
)替換為您從測試事件頁籤中取得的測試程式碼。
...
$request = (new EventRequest($pixel_id))
->setTestEventCode('TEST12345')
->setEvents($events);
$response = $request->execute();
我們目前不支援在發出並行批次要求或非同步要求時設定自訂 HTTP 服務介面。