create events on my Application's page - facebook-graph-api

I am in a process of writing an app which works this way
1. Asks a user permission for events_create, publish_stream
2. Gets the access_token for the same
3. takes input of Title, date, time, location( ie all inputs) from a form and then calls graph api like
/$app_id/events along with access token and post date
I want this to create an event within my APPLICATION's events and hence I use $app_id instead of ..../me/events
But it creates an event on USER's wall ???
I want users to be able to create an event on my wall. It should be an event whose owner is the application and the user should get invited along with his contacts( if he chooses so) ...
Basically, I think POST to /$app_id/events and /me/events work the same, I think it should not ... Am I missing something?
Thanks in advance ..
AC
HiShakyeb,
Same result ... It just creates an event in my account rather than the application's.
Here is the code I am using ..
$url = "https://graph.facebook.com/$app/events?" . $access_token;
$params = array();
// Prepare Event fields
foreach($_POST as $key=>$value)
if(strlen($value))
$params[$key] = $value;
$params['name']=mysql_real_escape_string($params['name']);
$params['description']=mysql_real_escape_string($params['description']);
$params['location']=mysql_real_escape_string($params['location']);
$params['end_time']=date('Y-m-d H:i:s', mktime(0, 0, 0, date("m") , date("d")+1, date("Y")));
$params['privacy_type']="SECRET";
// 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);
I also tried just app/events? instead of $app/events?
Thanks a lot ...

Use a Page Admin access token to take an action on behalf of that application's page. To do this, get /me/accounts with the manage_pages permission. That will give you the pages you have access to (including the app's profile page), along with an access token to use for acting as that page/application. If you use that access token, then events will be created as the application page and not the user. See the Graph API documentation for the Page object for more details.

With PHP-SDK I uses the api call for automatic POSTING an Event in App page after filling a form.
Here the automatic process after the user (You) have an valid APP access_token and manage app/page permissions. The token to use is your APP token you receive with your FBapp connection.
Starting creating php-sdk object
$connectparam = array();
$connectparam['appId'] = 'YOURAPPID';
$connectparam['secret'] = 'YOURAPPSECRET';
$connectparam['fileUpload'] = 'true';
$connectparam['cookie'] = 'true';
$facebook = new Facebook($this->connectparam);
Building the event informations
$FBcreateAnTestEvent = array();
$nowtime = date('Y-m-d H:i:s');
$FBcreateAnTestEvent['name'] = 'Test Event in myApp from me';
$FBcreateAnTestEvent['start_time'] = $nowtime;
$FBcreateAnTestEvent['privacy_type'] = 'SECRET';
$FBcreateAnTestEvent['description'] = 'This Event is created from my WebFBApp and is a testing Event creating by Qtronik from myWebApp';
Automaticly create event
$resp = '<a href="'.$facebook->api('/me/events','POST',$FBcreateAnTestEvent).'">
Create a test event</a>';
echo $resp;
When is echoing the php-sdk create immediately the Event so it's better to put it in a ajax or in action linked page in a form
For FanPage use FQL link
If You parse the FBuser admin_pages and filter by APPLICATION field and/or filter by your FBpage id you can get this user FBpages admin access_token's. Of Course you need the manage_pages permissions. Then you need admin_events permission to publish to FBfanPage's. I create an FanPageEvent with GraphApi link like this:
$pageAccessToken = $facebook->api('/' . $YOURPAGEID . '/?fields=access_token');
$resp = '<a href="https://graph.facebook.com/'.$pageAccessToken['id'].'/events
?access_token=' . $pageAccessToken['access_token'] . '
&method=POST
&name='.$FBcreateAnTestEvent['name'].'
&start_time='.$FBcreateAnTestEvent['start_time'].'
&location='.$FBcreateAnTestEvent['location'].')">
Create a test event</a>';
Then voila I have allot of other things to do with this for handle it with Ajax but this is the two way of adding an Event's to Facebook from a website administrating way... All this it's not very intended for personal profile event create so it's more difficult to spam FBpages and or FBapp/FBwebapp.
I'm French speaking so excuse my poor English... ;)

Related

Facebook PHP SDK 4.0 - Cannot re-ask read permissions once denied

I'm currently asking users for two read permissions i.e. email and user_location and one write permssion i.e. publish_actions. Following is the code snippet I'm using to verify if the user has granted all requested permissions:
$facebook = new Facebook(APP_ID, APP_SECRET, REDIRECT_URI);
if ( $facebook->IsAuthenticated() ) {
// Verify if all of the scopes have been granted
if ( !$facebook->verifyScopes( unserialize(SCOPES) ) ) {
header( "Location: " . $facebook->getLoginURL( $facebook->denied_scopes) );
exit;
}
...
}
Facebook is a class I've customly built to wrap the login flow used by various classes in the SDK. IsAuthenticated() makes the use of code get variable to check if the user is authorized. verifyScopes() checks granted permissions against SCOPES and assings an array of denied scopes to denied_scopes property. getLoginURL()` builds a login-dialog URL based on permissions passed as an an array as a only paramter.
Now, the problem is when the user doesn't grant write permissions, publish_actions in this case, write permission dialog is shown until user grants the write permission. But if the user chooses to deny of the read permissions, say email, the read login dialog isn't show. Instead Facebook redirects to the callback URL (that is REDIRECT_URI) creating a redirect loop.
The application I'm builiding requires email to be compulsorily provided but apparently the above approach (which seems to be the only) is failing. So, is there a workaround or a alternative way to achieve this? Or Facebook doesn't allow to ask for read permissions once denied?
As of July 15, 2014, an update has been made to the Facebook PHP SDK 4.x that allows user to re-ask the declined permissions. The function prototype of getLoginUrl() now looks like this.
public function getLoginUrl($redirectUrl, $scope = array(), $rerequest = false, $version = null)
So, to re-ask declined permissions we'd do something like this:
<?php
// ...
$helper = new FacebookRedirectLoginHelper();
if ($PermissionIsDeclined) {
header("Location: " . $helper->getLoginUrl( $redirect_uri, $scopes, true );
exit;
}
// ....
?>
For the time being you can append &auth_type=rerequest to the getLoginUrl return value to enable a rerequest, kind of lame but it works.
$helper = new FacebookRedirectLoginHelper($app_url, $app_id, $app_secret);
$login = $helper->getLoginUrl(array('scope'=>'user_likes', 'user_location'));
print $login."&auth_type=rerequest";
what about getReRequestUrl(); ?
That works just fine.
Read more at https://developers.facebook.com/docs/php/FacebookRedirectLoginHelper/5.0.0

How can I get my facebook personal profile posts using getAccessToken()?

What I am actually trying to do is to retrieve my posts/statuses from my personal facebook profile page (this is not a fan page) and display them in my website. Also please note that every user that will visit my website should be able to view my statuses by means it does not have to do with authenticating them or something like that. This is something that needs to be generated server-side.
I am aware that you can retrieve a JSON string from a URL like this https://graph.facebook.com/MY_PROFILE_ID/feed?access_token=ACCESS_TOKEN because I tried it from the facebook developers (Graph API Explorer) page and it is exactly what I need.
The thing is that when I generate the access token from the Graph API Explorer I can select permissions and it generates the token respectively according to permissions chosen, such as user_status, status_update, etc.
Now I want to accomplish this by using PHP-SDK but I have no idea how to generate an access token the same as the one I generate in the Graph API Explorer.
The basic way to do this is by calling getAccessToken() as shown here. The thing is that when I use the token generated from this simple method the JSON string returned will only show me my basic information.
$config = array(
'appId' => 'MY_APP_ID',
'secret' => 'MY_APP_SECRET',
);
$facebook = new Facebook($config);
$ACCESS_TOKEN = $facebook->getAccessToken();
How can I add permissions for instance? Should I assign parameters somewhere? I spent quite a lot of time reading the facebook API documentation and some other forums but I did not find the answer that I need.
Finally if I get the right access token than I would simply retrieve the JSON string and parse it with what I need.
Thanks.
you need for add permissions in your code for login using the fb js sdk add in the scope this like this example:
$("#login").on('click',function(){
FB.login(function(response){
console.log(response);
},{scope: 'email,manage_pages,read_insights'});
});
or in php fb sdk the next form:
<?php
require 'server/fb-php-sdk/facebook.php';
$app_id = 'APP_ID';
$app_secret = 'APP_SECRET';
$app_namespace = 'APP_NAMESPACE';
$app_url = 'https://apps.facebook.com/' . $app_namespace . '/';
$scope = 'email,publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Login Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
?>
the most important for add permission is this part :
$scope = 'email,publish_actions';
you can find all about the extended permissions in this link
https://developers.facebook.com/docs/reference/login/extended-permissions

having trouble sending facebook notification via ajax call to php

In my javascript I have a click event that triggers an ajax call to the php page where I send my notification from. I chose to do it this way because the documentation advises against using your app secret in any client side code, and the notifications parameters requires an access token that you can only get using the app secret.
The problem I'm having is that even though I'm logged in, $facebook->getUser() is returning 0 in php, so the api call I make afterwards to send the notification wont work. My user is already logged in via the client side code, so how do I get the message to the php that they're logged in so the notification can be sent.
//JS
$.ajax({
url : "http://xxxxxo/bn/notification.php",
type : 'POST',
data: {notify: notify },
success : function (result) {
console.log(result);
},
error : function () {
alert("error sending notification");
}
});//closes ajax
//PHP
<?php
require_once(dirname(__FILE__).'/php-sdk/facebook.php') ;
$APPLICATION_ID = '1402xxxxx7';
$APPLICATION_SECRET = 'ce71d6bbxxxxx5f55a';
$fb_app_url = "http://apps.facebook.com/myAPP";
$config = array();
$config['appId'] = $APP_ID;
$config['secret'] = $APP_SECRET;
$config['cookie'] = true;
$facebook = new Facebook($config) or die('Error is here!');
$facebook = new Facebook(array(
'appId' => $APP_ID,
'secret' => $APP_SECRET,
'fileUpload' => true
));
$notify = $_REQUEST['notify'];
$userid = $facebook->getUser();
/*IF WE HAVE A LOGGED IN USER AND THE 'NOTIFY' REQUEST VALUE, THEN SEND THE NOTIFICATION.
BUT MY USER ID IS 0. HOW DO I GET PHP TO RECOGNIZE ME AS LOGGED IN WITHOUT HAVING TO FORCE MY USER TO LOG IN VIA PHP AFTER THEY'VE ALREADY LOGGED IN CLIENT SIDE?*/
if($userid && $notify){
$token_url ="https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $APP_ID .
"&client_secret=" . $APP_SECRET .
"&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
$app_token = str_replace("access_token=", "", $app_token);
$data = array(
'href'=> 'https://apps.facebook.com/thebringernetwork/',
'access_token'=> $app_token,
'template'=> 'test'
);
$sendnotification = $facebook->api('/1622649653/notifications', 'post', $data);
}else{
//handle error
}
?>
The first thing I noticed is that you define your app id as $APPLICATION_ID but use it as $APP_ID (and the same goes for your app secret). But since you didn't mention any errors and $facebook->getUser(); executes I'm guessing this is just a bad copy-paste.
Now for the sake of answering this question I'm going to presume that you are using the latest versions of both JS and PHP SDKs. These use oauth 2.0 and change the way you pass the login information from JS to PHP.
According to Facebook Developer Blog removing $config['cookie'] = true; and setting oauth to true in your JS configuration should work. Just make sure to refresh the site after the login.
The solution I've found in my own project is to disable cookies altogether and simply pass the access token to my PHP script.
In your JS call your PHP script like this (make sure to call this after the JS login!):
$.ajax({
url : "http://xxxxxo/bn/notification.php",
type : 'POST',
data: {
notify: notify,
token: FB.getAuthResponse()['accessToken'] // add your access token
},
success : function (result) {
console.log(result);
},
error : function () {
alert("error sending notification");
}
});
And in your PHP script add this after creating the FB object.
$facebook->setAccessToken($_POST['token']); // set the users access token
Doing things this way will also get rid of any need to refresh the website after the login.
Yes, this is a common problem when using the PHP SDK in combination with AJAX:
When you make an AJAX request, the PHP SDK deletes the cookies where the authorization information are stored, and then the next call to getUser will just return 0, because this method tries to find the current user id in those cookies – apparently there is something in the OAuth 2.0 spec that demands this behavior to prevent some sort of click-jacking attack.
But the info will still be stored in the session, so you can read the user id (and the user access token, should you need it) from there:
$user_id = $_SESSION['fb_YourAppIdHere_user_id'];
$user_access_token = $_SESSION['fb_YourAppIdHere_access_token'];
Replace YourAppIdHere with your app id (so it becomes fb_1234567890_user_id resp. fb_1234567890_access_token) to get the correct names of those session keys.

Facebook API - App using Oauth to update status of page

I have built an app using the PHP Facebook SDK. It allows users to authenticate my app with facebook OAth so that they can update their status' via my App. This works great, however a lot of my users have business pages and they want to update the status on their business page not their main personal feed. How is this possible? Below is what I have so far.
if ($status != ''){
try {
$parameters = array(
'message' => "$status"/*,
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']*/
);
//add the access token to it
$parameters['access_token'] = $access_token;
//build and call our Graph API request
$newpost = $facebook->api(
'/me/feed',
'POST',
$parameters
);
$success['status'] = "$xml->status";
$xml2 = new XMLGenerator($success, 'facebook','status');
$returnData = $xml2->output;
$returnData = APIResponse::successResponse('200', "$xml->status");
} catch (Exception $e) {
$returnData = APIResponse::errorResponse('400', 'Facebook Error: '.$e);
}
I assume I would have to change '/me/feed'? but to what? What is they have multiple pages how would my app know which page to post to?
Any help with this would be much appreciated.
You can substitute me with the PAGE_ID to post to a page e.g., /013857894/feed. Make sure that you have completed the OAuth process with the manage_pages and publish_stream permissions. You can learn more at the link below:
https://developers.facebook.com/docs/reference/api/page/#statuses
If the user has multiple Pages then you will first need to give them some way of selecting which page they want to post to. You can find out which Facebook Pages a given user is the administrator of by calling /me/accounts for that user. You can find out more about this approach in the Connections section of this page:
https://developers.facebook.com/docs/reference/api/user/

Send data from drupal form to Web service Client (REST)

I create a simple form. When I put data in all fields of the form and press a submit button, then all data that were completed on the form should be sent to a Web service client (rest).
My question is, how to send all data from my form to web service? Is there a module for that or I have to draw on an API?
Thanks :D
UPDATE:
I created my form that contains 2 fields: "Name" and "Phone" and a submit button. (All in my own module)
Then I show my code that I just did. However, when I see the web service. The shipping data, not shown. I did a debug and uh I realized that when running: "curl_exec ($ch)" returns me FALSE.
function mymodule_form_submit($form, &$form_state){
$name = $form_state['values']['name'];
$phone = $form_state['values']['phone'];
$data = array(
'name' => $name,
'phone' => $phone
);
$url = 'http://[IP]/event/management/attendee';
$headers = array('Content-Type: multipart/form-data');
$userpasswd = 'user:pass';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
curl_close($ch);
}
The params,in the web service, are: attendee['name'], attendee['phone']. What is my error?
Sure man try the service module 3 . It's one of drupal great module as usual .
here's the link ( http://drupal.org/node/736522 ) , you can also authenticate user before getting the fields by using two techniques either session authentication or aouth authentication .. you can call your drupal from client application by one of those approach "json,xml-rpc, rest".
1- first the session authentication takes a user name and password and authenticates. Then it takes the user permissions from drupal so you need to authenticate in each step to go through your application that communicate with your drupal. Anonymous users can get what they want according to your permission in drupal.
2- While in Aouth authentication you create a user and add token to him and only the user who had the token communicate with the application according to the permission rule you set to him . In case of anonymous users they can't retrieve or get anything. The communication between drupal and the client within the created used with a certain token.
Feel free to contact me for more support.
sorry for miss-understanding .
there's two implementation method to do this :
1- You may do a custom module which hooks on the node_api and on submit form get posted data and send it to webservice by this method
$json = drupal_http_request('http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false');
$decode = json_decode($json->data, TRUE);
or by using this module web service client module ( http://drupal.org/project/wsclient ) this is only for drupal 7
2- and this is a guide about this module http://drupal.org/node/1114308 .