Posting an Event to Page Wall with PHP - php

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/

Related

failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request 5

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"

Searching Local Venues With Foursquare API

I am searching foursquare for venues around my area. I cannot get the search function to work.
This is the documentation on it,
I believe my problem is in the http request but I don't get why =the result is always null or how to troubleshoot it from here.
Click Here
This is my search form,
<div class="row">
<div class="col-sm-6 text-center">
<div class="signup-form">
<form class="clearfix" action="actions/fsSearch.php" method="post">
<div class="form-group">
<h3>sup bro</h3>
<input type="text" class="form-control" name="query" placeholder="do iT">
</div>
</div>
<button type="submit" name="submit" value="post" class="btn btn-huge btn-info">Search For Places!</button>
</form>
</div>
</div>
This is my search foursquare script,
<?php
$client_id = "foo";
$secret = "foo";
$redirect = "http://www.example.com/sandbox";
$query = $_POST['query'];
$fsSearch = file_get_contents("https://api.foursquare.com/v2/venues/search
?client_id=" . $client_id . "
&client_secret=" . $secret . "
&v=20140623
&ll=40.7,-74
&query=".$query);
$searchResults = json_decode($fsSearch,true);
header("Location: http://www.example.com/sandbox");
?>
Then when I var_dump($searchResults);
I get a null result.
I dont see what I am doing wrong here...
This is my try with Curl
<?php
$client_id = "foo";
$secret = "foo";
$redirect = "http://www.example.com/sandbox";
$query = $_POST['query'];
echo $query;
$ch = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "https://api.foursquare.com/v2/venues/search?client_id={$client_id}&client_secret={$secret}&v=20140623&ll=40.7,-74&query={$query}",
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>
I know this is epically late, but i just got this to work by removing the line feeds in your API request and wanted to submit this encase anyone arrived here via google (like i did!)
Change this:
$fsSearch = file_get_contents("https://api.foursquare.com/v2/venues/search
?client_id=" . $client_id . "
&client_secret=" . $secret . "
&v=20140623
&ll=40.7,-74
&query=".$query);
To this:
$fsSearch = file_get_contents("https://api.foursquare.com/v2/venues/search?client_id=" . $client_id . "&client_secret=" . $secret . "&v=20140623&ll=40.7,-74&query=".$query);

php facebook event rsvp

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.

How do I parse data returned from the Graph Api

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.

Posting an Event to Page Wall with PHP - The Proper Page?

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;

Categories