我只是想对 Facebook Graph API 进行最基本的测试。我正在使用 PHP 和 cURL。我直接从 Facebook Payload Helper 复制数据字符串。一切看起来都正确,但我收到消息:
string(135) "{"error":{"message":"(#100) 参数数据为必填","type":"OAuthException","code":100,"fbtrace_id":"Age1fgb47kngho3guOkcAcj"} }“
该消息告诉我“data”参数未设置,但您可以看到它已设置在数据字符串中。请参阅下面的我的代码。任何调试方面的帮助将不胜感激。
<?php
$url = "https://graph.facebook.com/v10.0/<PIXEL ID>/events?access_token=<TOKEN>";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"content-type: multipart/form-data",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = '{
"data": [
{
"event_name": "Purchase",
"event_time": '.time().',
"action_source": "website",
"event_id": '.rand(100000, 500000).',
"user_data": {
"em": "6b583232e99af45c3b436798f32800a4dd6f3524624ba6507ed8269b53ce82a3",
"ph": null
},
"custom_data": {
"currency": "USD",
"value": "37"
}
}
],
"test_event_code":"TEST9031"
}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
?>
如果有帮助的话,我做了一个包含此方法的类来将数据发送到 Facebook 的 API:
/** @var string url to accede to Facebook API */
private $apiUrl = "https://graph.facebook.com/v12.0";
/** @var int id of pixel used with Facebook API */
private $pixelId = 0000000000000;
/** @var string token to accede to Facebook API */
private $token = "QWERTY...";
/** @var string|null code to specify test to Facebook API */
private $testEventCode = "TEST00000";
/** Send datas to Facebook's API
*
* @param array datas to send like ['event_name' => 'ViewContent', ... ]
*
* @return string|bool
*/
public function sendData(array $data)
{
$fields = [
'access_token' => $this->token,
'test_event_code' => $this->testEventCode,
'data' => [$data],
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "{$this->apiUrl}/{$this->pixelId}/events",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($fields),
CURLOPT_HTTPHEADER => [
"cache-control: no-cache",
"accept: application/json",
"content-type: application/json",
],
]);
return curl_exec($ch);
}