您需要先安装 Meta Business SDK,才能使用以下任何一项功能。请参阅 Meta Business 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 作业等用例。
您可以从以下 BatchProcessor
方法中进行选择:
方法 | 适用情况 |
---|---|
| 使用该方法处理具有相同顶层 |
| 此方法是 也可以使用此方法处理具有相同顶层 |
| 当您想为每个请求指定不同的 |
| 此方法是 当您想为每个请求指定不同的 |
在使用并发批量处理时,应尽量实时发送事件。如需了解更多信息,请参阅分享频次。
如果您使用的是 PHP SDK、Python SDK 或 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 服务接口。通过这项功能,您可以覆盖 Business 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
参数测试事件请求。前往数据来源 > 您的 Pixel 像素代码事件 > 测试事件选项卡中的事件管理工具,找到测试事件工具,从而获取测试代码。
注意:您必须使用从测试事件选项卡获取的测试代码来替换以下代码中的示例值(即 TEST12345
)。
...
$request = (new EventRequest($pixel_id))
->setTestEventCode('TEST12345')
->setEvents($events);
$response = $request->execute();
目前,我们不支持在执行并发批量处理请求或异步请求时设置自定义 HTTP 服务接口。