I'm getting tantalizingly close to completing this script. The goal is to Post an event to one of my fan page walls. The script is effectively grabbing the correct PAGE Access Token, and is effectively posting the event, but it's on my personal wall, not the page wall I'm trying to get it to.
What am I missing? It seems to be all there, but clearly something is inside out or backwards.
Any and all help is appreciated! Here's the code:
<?php
$app_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "http://xxxxxxxxxxxxxxxxxxxxxx.com/testfiles/fbeventform.php";
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=create_event&scope=manage_pages";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$access_token = #file_get_contents($token_url);
$params = null;
parse_str($access_token, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
echo '<hr />' . $access_token;
//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'];
echo '<hr />' . $page_access_token;
//Post the event--here's the form function
if( !empty($_POST) && (empty($_POST['name']) || empty($_POST['start_time']) || empty($_POST['end_time'])) ) {
$msg = "Please check your inputs!";
} elseif(!empty($_POST)) {
$url = "https://graph.facebook.com/" . $page_id . "/events?" . $access_token;
$params = array();
// Prepare Event fields
foreach($_POST as $key=>$value)
if(strlen($value))
$params[$key] = $value;
// Check if we have an image
if( isset($_FILES) && !empty($_FILES['picture']['name']) ) {
$uploaddir = './upload/';
$uploadfile = $uploaddir . basename($_FILES['picture']['name']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
$params['picture'] = "#" . realpath($uploadfile);
}
}
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if(is_array($decoded) && isset($decoded['id'])) {
// Event created successfully, now we can
// a) save event id to DB AND/OR
// b) show success message AND/OR
// c) optionally, delete image from our server (if any)
$msg = "Event created successfully: {$decoded['id']}";
}
}
?>
<form enctype="multipart/form-data" action="" method="post">
<p><label for="name">Event Name</label><input type="text" name="name" value="a" /></p>
<p><label for="description">Event Description</label><textarea name="description"></textarea></p>
<p><label for="location">Location</label><input type="text" name="location" value="" /></p>
<p><label for="">Start Time</label><input type="text" name="start_time" value="<?php echo date('Y-m-d H:i:s'); ?>" /></p>
<p><label for="end_time">End Time</label><input type="text" name="end_time" value="<?php echo date('Y-m-d H:i:s', mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); ?>" /></p>
<p><label for="picture">Event Picture</label><input type="file" name="picture" /></p>
<p>
<label for="privacy_type">Privacy</label>
<input type="radio" name="privacy_type" value="OPEN" checked='checked'/>Open
<input type="radio" name="privacy_type" value="CLOSED" />Closed
<input type="radio" name="privacy_type" value="SECRET" />Secret
</p>
<p><input type="submit" value="Create Event" /></p>
</form>
</body>
</html>
On your $url = "https://graph.facebook.com/" . $page_id . "/events?" . $access_token; you're missing the query string name for the access token
Try this
$url = "https://graph.facebook.com/" . $page_id . "/events?access_token=" . $access_token;
Related
I'm a beginner to PHP and the Facebook API. I want a upload an image to facebook. I get an error that says: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
Below is a sample of my code:
<?php
error_reporting(E_ALL & ~E_NOTICE); $app_id="xxxxxxxxxxxxx" ; $app_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxx" ; $my_url="`http://localhost/facebook/examples/example.php`" ; $perms_str="publish_stream" ; $code=$ _REQUEST[ "code"]; if(empty($code)) { $auth_url="http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url). "&scope=" . $perms_str; echo( "<script>top.location.href='" . $auth_url . "'</script>"); } $token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url).
"&client_secret=" . $app_secret. "&code=" . $code; $response=f ile_get_contents($token_url); $p=n ull; parse_str($response, $p); $access_token=$ p[ 'access_token']; $graph_url="https://graph.facebook.com/me/photos?" . "access_token=" .$access_token; if (!empty($_FILES))
{ $params=a rray(); if( isset($_POST[ 'message']) ) { $params[ 'message']=t rim($_POST[ 'message']); } $uploaddir='./uploads/' ; // Upload folder $uploadfile=$ uploaddir . basename($_FILES[ 'source'][ 'name']); if (move_uploaded_file($_FILES[ 'source'][
'tmp_name'], $uploadfile)) { $params[ 'source']="#" . realpath($uploadfile); } // Start the Graph API call $ch=c url_init(); curl_setopt($ch, CURLOPT_URL,$graph_url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch,
CURLOPT_POSTFIELDS, $params); $result=c url_exec($ch); $decoded=j son_decode($result, true); curl_close($ch); if(is_array($decoded) && isset($decoded[ 'id'])) { $msg="Image uploaded successfully: {$decoded['id']}" ; } }
?>
<!doctype html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<?php if( isset($msg) ) { ?>
<p id="msg">
<?php echo $msg; ?>
</p>
<?php } ?>
<form enctype="multipart/form-data" action="" method="post">
<p>
<label for="name">Caption</label>
<input type="text" name="message" value="" />
</p>
<p>
<label for="source">Image</label>
<input type="file" name="source" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</form>
</body>
</html>
Remove the extra quotes in $my_url
$my_url="http://localhost/facebook/examples/example.php"
I have an event on facebook I would like to rsvp attending to. I would like to rsvp with a link, all the examples I have found for rsvping were done with forms. I have the rsvp_event permission and an active access_token. The actual problem I am facing is redirecting after a successful http post.
<?php
$redirect_uri = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$access_token = "ACCESS_TOKEN";
$eid = "EVENT_ID";
$rsvp_to_event = "https://graph.facebook.com/$eid/attending?method=post&access_token=$access_token&redirect_uri=$redirect_uri";
?>
Join
Clicking the 'Join' link will rsvp to the event, but leaves me on a page displaying true. Any ideas to get the page to redirect after a successful rsvp?
Thank you.
You have to query that URL using cURL or file_get_contents(), here's an example from my tutorial:
<?php
$app_id = "APP_ID";
$app_secret = "APP_SECRET";
$my_url = "REDIRECT_URI";
$event_id = "EVENT_ID";
$rsvp_status = "";
$code = $_REQUEST["code"];
if(empty($code)) {
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&scope=rsvp_event";
echo("<script>top.location.href='" . $auth_url . "'</script>");
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
if( isset($_POST['rsvp']) ) {
// Form submitted, call the Graph API to RSVP to the event
$event_rsvp = "https://graph.facebook.com/$event_id/{$_POST['rsvp']}?method=post&" . $access_token;
$rsvped = json_decode(file_get_contents($event_rsvp));
if($rsvped) {
$msg = "Your RSVP status is now <strong>{$_POST['rsvp']}</strong>";
$rsvp_status = $_POST['rsvp'];
}
}
if( !$rsvp_status ) {
$query = "SELECT rsvp_status FROM event_member WHERE eid=$event_id AND uid=me()";
$fql_url = "https://api.facebook.com/method/fql.query?"
. "query=" . urlencode($query)
. "&format=json"
. "&" . $access_token;
$fql_resp = json_decode(file_get_contents($fql_url));
$rsvp_status = $fql_resp[0]->rsvp_status;
}
?>
<!doctype html>
<html>
<head>
<title>Create An Event</title>
<style>
label {float: left; width: 100px;}
input[type=text],textarea {width: 210px;}
#msg {border: 1px solid #000; padding: 5px; color: red;}
</style>
</head>
<body>
<?php if( isset($msg) ) { ?>
<p id="msg"><?php echo $msg; ?></p>
<?php } ?>
<form action="" method="post">
<p>
<label for="privacy_type">RSVP:</label>
<input type="radio" name="rsvp" value="attending" <?php if($rsvp_status==="attending") echo "checked='checked'"; ?>/>Attending
<input type="radio" name="rsvp" value="maybe" <?php if($rsvp_status==="maybe" || $rsvp_status==="unsure") echo "checked='checked'"; ?>/>Maybe
<input type="radio" name="rsvp" value="declined" <?php if($rsvp_status==="declined") echo "checked='checked'"; ?>/>Not Attending
</p>
<p><input type="submit" value="RSVP to this event" /></p>
</form>
</body>
</html>
You should be looking at:
if( isset($_POST['rsvp']) ) {
// Form submitted, call the Graph API to RSVP to the event
$event_rsvp = "https://graph.facebook.com/$event_id/{$_POST['rsvp']}?method=post&" . $access_token;
$rsvped = json_decode(file_get_contents($event_rsvp));
if($rsvped) {
$msg = "Your RSVP status is now <strong>{$_POST['rsvp']}</strong>";
$rsvp_status = $_POST['rsvp'];
}
}
The above tutorial consist of HTML form where the user can choose his status.
Most graph api endpoints are not designed to be called directly with your user's browser but to call them from your backend code (authentication related ones could be exception).
Try using the offical php sdk for sending those requests from your php page, or just use the curl extension or file_get_contents on these endpoints from your php script and redirect the user yourself.
I have a PHP form (index.php) that uses the Facebook Graph API to create an event. A form is used to capture user input, and this data is POSTed back to the API to create the event.
This is the same code as explained in this tutorial: http://www.masteringapi.com/tutorials/how-to-create-facebook-events-using-graph-api/49/
The result of this is that, it returns the ID of the event that just got created.
<?php
$app_id = "APP_key";
$app_secret = "APP_secret";
$my_url = "URL";
$code = $_REQUEST["code"];
if(empty($code)) {
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&scope=create_event";
echo("<script>top.location.href='" . $auth_url . "'</script>");
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$event_url = "https://graph.facebook.com/me/events?" . $access_token;
?>
<style>
label {float: left; width: 100px;}
input[type=text],textarea {width: 210px;}
</style>
</head>
<body>
<div id="inputForm">
<form enctype="multipart/form-data" action="<?php echo $event_url; ?>" method="post">
<p><label for="name">Event Name</label><input type="text" name="name" value="" /></p>
<p><label for="description">Event Description</label><textarea name="description"></textarea></p>
<p><label for="location">Location</label><input type="text" name="location" value="" /></p>
<p><label for="">Start Time</label><input type="text" name="start_time" value="<?php echo date('Y-m-d H:i:s'); ?>" /></p>
<p><label for="end_time">End Time</label><input type="text" name="end_time" value="<?php echo date('Y-m-d H:i:s', mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); ?>" /></p>
<p><label for="picture">Event Picture</label><input type="file" name="picture" /></p>
<p>
<label for="privacy_type">Privacy</label>
<input type="radio" name="privacy_type" value="OPEN" checked='checked'/>Open
<input type="radio" name="privacy_type" value="CLOSED" />Closed
<input type="radio" name="privacy_type" value="SECRET" />Secret
</p>
<p><input type="submit" value="Create Event" /></p>
</form>
</div>
<?php
This code works great, but I'm trying to modify this code such that, index.php posts data to $event_url to create the event, but redirects you to a confirmation page that displays a message such as:
"Event successfully created! Click here to access your event", and clicking "here" would redirect you the event on Facebook.
Any thoughts on how this could be done?
Change $event_url to a page like event_submitter.php on your site and add the access_token as a hidden field on your form.
The event_submitter page should take the $_POST data, strip out the access_token (You could eliminate this part if you used the php SDK), reformat the rest of the $_POST data, send this to to the Facebook API via cURL and examine the response.
If you get the correct response, you can then generate the output you want from that.
I've been knocking my head against a wall for two weeks now, poring over the net, poring over stackoverflow, and repeatedly testing and failing to get a script together to post an event to a Fan Page. I've finally gotten a script that effectively creates the event, but it doesn't appear on the page.
After DMCS pointed me along to the PAGE access tokens, I fiddled about to generate them. Now, the problem is that the event appears on my personal wall, not the page wall I'm targeting. Can anyone see what I'm missing?
Here's the script after the latest edits:
<?php
$app_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "http://xxxxxxxxxxxxxxxxxxxxxx.com/testfiles/fbeventform.php";
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=create_event&scope=manage_pages";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$access_token = #file_get_contents($token_url);
$params = null;
parse_str($access_token, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
echo '<hr />' . $access_token;
//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'];
echo '<hr />' . $page_access_token;
//Post the event--here's the form function
if( !empty($_POST) && (empty($_POST['name']) || empty($_POST['start_time']) || empty($_POST['end_time'])) ) {
$msg = "Please check your inputs!";
} elseif(!empty($_POST)) {
$url = "https://graph.facebook.com/" . $page_id . "/events?" . $access_token;
$params = array();
// Prepare Event fields
foreach($_POST as $key=>$value)
if(strlen($value))
$params[$key] = $value;
// Check if we have an image
if( isset($_FILES) && !empty($_FILES['picture']['name']) ) {
$uploaddir = './upload/';
$uploadfile = $uploaddir . basename($_FILES['picture']['name']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
$params['picture'] = "#" . realpath($uploadfile);
}
}
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if(is_array($decoded) && isset($decoded['id'])) {
// Event created successfully, now we can
// a) save event id to DB AND/OR
// b) show success message AND/OR
// c) optionally, delete image from our server (if any)
$msg = "Event created successfully: {$decoded['id']}";
}
}
?>
<form enctype="multipart/form-data" action="" method="post">
<p><label for="name">Event Name</label><input type="text" name="name" value="a" /></p>
<p><label for="description">Event Description</label><textarea name="description"></textarea></p>
<p><label for="location">Location</label><input type="text" name="location" value="" /></p>
<p><label for="">Start Time</label><input type="text" name="start_time" value="<?php echo date('Y-m-d H:i:s'); ?>" /></p>
<p><label for="end_time">End Time</label><input type="text" name="end_time" value="<?php echo date('Y-m-d H:i:s', mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); ?>" /></p>
<p><label for="picture">Event Picture</label><input type="file" name="picture" /></p>
<p>
<label for="privacy_type">Privacy</label>
<input type="radio" name="privacy_type" value="OPEN" checked='checked'/>Open
<input type="radio" name="privacy_type" value="CLOSED" />Closed
<input type="radio" name="privacy_type" value="SECRET" />Secret
</p>
<p><input type="submit" value="Create Event" /></p>
</form>
</body>
</html>
This effectively creates the event, but it doesn't appear on the page wall I'm targetting. I'm really at the end of my rope over this...
Any and all help is appreciated, and I will be happy to post final results for future users!
Debug the access token you're using at https://developers.facebook.com/tools/lint and ensure you have a PAGE access token and not a USER access token.
For getting a page access token, see "Page Login" part of https://developers.facebook.com/docs/authentication/
<?php $prev_path = "./../../."; $dont_redirect = true; require_once "${prev_path}./config.php";
session_start();
function http_digest_parse($txt){
$needed_parts = array("nonce"=>1, "nc"=>1, "cnonce"=>1, "qop"=>1, "username"=>1, "uri"=>1, "response"=>1);
$data = array();
$keys = implode("|", array_keys($needed_parts));
preg_match_all("#(" . $keys . ")=(?:(['\"])([^\\2]+?)\\2|([^\s,]+))#", $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
if($_REQUEST["task"] == "logout") {
unset($_SESSION["KEY"]);
unset($_SESSION["SUCCESS"]);
unset($_SERVER["PHP_AUTH_DIGEST"]);
}
if (!isset($_SESSION["SUCCESS"])){
$_SESSION["KEY"] = $_SESSION["KEY"] ? $_SESSION["KEY"] : uniqid();
$realm = "Restricted area, KEY: " . $_SESSION["KEY"];
$users = array("user" => "pass", "google" => "stackoveflow");
header("HTTP/1.1 401 Unauthorized");
header("WWW-Authenticate: Digest realm=\"" . $realm . "\",qop=\"auth\",nonce=\"" . uniqid() . "\",opaque=\"" . md5($realm) . "\"");
echo "Hello Guest, you are not permitted to view this page..";
if (!($data = http_digest_parse($_SERVER["PHP_AUTH_DIGEST"])) || !isset($users[$data["username"]])) {
unset($_SESSION["SUCCESS"]);
die("Incorrect Username!");
}
$A1 = md5($data["username"] . ":" . $realm . ":" . $users[$data["username"]]);
$A2 = md5($_SERVER["REQUEST_METHOD"].":".$data["uri"]);
$valid_response = md5($A1.":".$data["nonce"].":".$data["nc"].":".$data["cnonce"].":".$data["qop"].":".$A2);
if ($data["response"] != $valid_response) {
unset($_SESSION["SUCCESS"]);
die("Incorect Password!");
}
$_SESSION["SUCCESS"] = true;
} else {
if($_REQUEST["task"]=="newItem") {
sql("INSERT INTO ITEM VALUES('','${_REQUEST["code"]}','${_REQUEST["pic"]}','${_REQUEST["size"]}','${_REQUEST["description"]}','${_REQUEST["retail"]}','','${_REQUEST["instock"]}','1')", 0);
}
?>
<!doctype html>
<html>
<head>
<title></title>
<head>
<body><?print_r($_REQUEST)?>
<fieldset>
<legend>Create one new shop item:</legend>
<form action="./?task=newItem" method="GET">
<table>
<tr><td>Pic:</td><td><input id="pic" /></td></tr>
<tr><td>Code:</td><td><input id="code" /></td></tr>
<tr><td>Description:</td><td><textarea id="description"></textarea></td></tr>
<tr><td>Retail:</td><td><input id="retail" /></td></tr>
<tr><td>In Stock:</td><td><input id="instock" /></td></tr>
<tr><td></td><td><input type="submit" /></td></tr>
</table>
</form>
</feildset>
</body>
</html>
<?}?>
The Login sort-of works but the form never works.. and fixes for both would be nice.
You'll have to include the "name" and "type" attributes in your form fields.
<input name="code" id="code" type="text" />