14. August 2023

Facebook API mit PHP cURL benutzen

Wer die Meta Business SDK nicht in seinem Web-Projekt benutzen möchte, kann die Facebook API auch per PHP cURL verwenden. Hier ein Code-Beispiel:

<?php

// Daten-Array zusammenstellen
$data_array=array(
	"data" => array(
		array(
			"event_name" => $event_name,
			"event_time" => time(),
			"user_data" => array(
				"client_ip_address" => $client_ip_address,
				"client_user_agent" => $client_user_agent,
				"em" => $client_email,
				"ph" => $client_phone,
				"fbc" => $client_fb_click_id,
				"fbp" => $client_fb_browser_id
			),
			"custom_data" => array(
				"currency" => $custom_data_currency,
				"value" => $custom_data_value,
				"contents" => array(
					"id" => $custom_data_contents_id,
					"quantity" => $custom_data_contents_quantity,
					"delivery_category"=> ""
				)
			),
			"action_source" => $action_source,
			"event_source_url"  => $event_source_url,
	   ),
	),
	"access_token" => $access_token
);

// JSON erstellen
$data_json=json_encode($data_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// Test-Ausgabe: Daten
// exit($data_json);

// Facebook-API per cURL aufrufen
$curl=curl_init('https://graph.facebook.com/v17.0/'.$pixel_id.'/events');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);       
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
	'Content-Type: application/json',
	'Content-Length: ' . strlen($data_json))
);

// Facebook-API Antwort als JSON oder Array
$response_json=curl_exec($curl);
$response_array=json_decode($response_json, 1);

// Test-Ausgabe: Antwort
// exit($response_json);

curl_close($curl);