Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Post an Event to a Facebook Fan Page using the PHP SDK and Graph API?

The following code works, but it creates the event as the currently logged-in page administrator. I need it to post the event to the fan page itself. FYI: My app has been granted the permissions scope: manage_pages

<?php

// Initialize a Facebook instance from the PHP SDK
$config = array(
  'appId' => FACEBOOK_APP_ID,
  'secret' => FACEBOOK_APP_SECRET,
  'cookie' => false,
  'scope' => 'manage_pages,create_event'
);

$facebook = new Facebook($config);

$access_token = $facebook->getAccessToken();

$page_id = 'XXXXXXXXXXXX';

// Now, getting the PAGE Access token, using the user access token

$page_token_url = "https://graph.facebook.com/$page_id?fields=access_token&" . $access_token;
$response = file_get_contents($page_token_url);

// Parse the return value and get the Page access token
$resp_obj = json_decode($response,true);

$page_access_token = $resp_obj['access_token'];

// Declare the variables we'll use to demonstrate
// the new event-management APIs
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = time() + rand(1, 100) * rand(24, 64) * 3600;
$event_privacy = "SECRET"; // We'll make it secret so we don't annoy folks.

// We'll create an event in this example.
// We'll need create_event permission for this.
$params = array(
  'name' => $event_name,
  'start_time' => $event_start,
  'privacy_type' => $event_privacy,
  'access_token' => $page_access_token,
  'page_id' => $page_id //where $page_id is the ID of the page you are managing
);

// Create an event
$ret_obj = $facebook->api("/$page_id/events", 'POST', $params);
if(isset($ret_obj['id'])) {
  // Success
  $event_id = $ret_obj['id'];
  printMsg('Event ID: ' . $event_id);
} else {
  printMsg("Couldn't create event.");
}

// Convenience method to print simple pre-formatted text.
function printMsg($msg) {
   echo "<pre>$msg</pre>";
}

?>
like image 820
lincolnberryiii Avatar asked Nov 14 '22 05:11

lincolnberryiii


1 Answers

Answer is here: Facebook PHP API, Post an Event on a Page

Copied below for convenience:

I think you need the page access_token and here how you get it:

$page_id = "XXXXXXXXX";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
    if($page["id"] == $page_id) {
        $page_access_token = $page["access_token"];
        break;
    }
}

Make sure you grant the manage_pages permission and add the access_token to the $event_info array.

like image 188
Max Avatar answered Jan 05 '23 23:01

Max