Facebook PHP SDK get access token using php - php

I am using the following code to post to Facebook:
require('facebook.php');
$fb = new Facebook(array('appId' => 'MY APP ID','secret' => 'MY APP SECRET','cookie' => true));
$result = false;
$feed_dir = '/401868882779/feed/'; //to the UID you want to send to
$acToken = "MY ACCESS TOKEN";
$url = 'URL';
$link = $url . 'event.php?id=' . $id;
if (isset($picture))
{
$picture = $url . 'uploads/' . $picture;
}
else
{
$picture = $url . 'images/blank100x70.png';
}
$msg_body = array('access_token' => $acToken,'name' => $noe_unsecured,'message' => $link,'link' => $link,'description' => $description_unsecured,'picture' => $picture);
try
{
$result = $fb->api($feed_dir, 'post', $msg_body);
}
catch (Exception $e)
{
$err_str = $e->getMessage();
}
but I need to update the access token manually every time it changes. I am sure there's solution but I cant find it.. I tried lots of scripts and nothing worked.

It is possible.
Check: http://developers.facebook.com/docs/reference/php/facebook-setAccessToken/

Depending on when you perform the wall post, you might need to request the offline_access permission. This will convert your access_token into a format that does not expire so there would be no need to refresh the token.

A simple solution...remove the access_token!
You simply don't need it as long as you got the publish_stream permission!

I believe there are multiple methods to do this:
- you can use the method already provided in the PHP SDK getAccessToken which returns the current access token being used by the sdk instance, more info at this url.
- However you need not use an access token to call the api() method, once you ask the user for the publish_stream permission, as already mentioned by #ifaour. Hence you can do something like this example, scroll to the subheading Post a link to a User's wall using the Graph API.
- Then, you have another three options
i) either get a new access token using the method here, if you are posting when the user is currently using your app, otherwise you can try the next 2 options
ii) get offline access
iii) i'm not sure of this, but you might want to try with an app access token which can be obtained this way.

Related

Facebook API Real Time updates for Page/Feed no response

I have a problem with Facebook Real-time subscription from my facebook page.
When I POST a subscription, i get the message from facebook about it to my call back url.
Code:
$session = new FacebookSession('<APP ACCESS TOKEN>');
$request = new FacebookRequest(
$session,
'POST',
'/<APP ID>/subscriptions',
array(
'object' => 'page',
'callback_url' => 'http://*************/facebook/callback.php',
'fields' => 'conversation', // a try 'feed' to
'verify_token' => '<VERIFY TOKEN>',
)
);
$response = $request->execute();
BUT when someone add a post/conversation to my fb page, facebook don't send me any data.
callback.php code:
<?php
// Insert the path where you unpacked log4php
include('log4php/Logger.php');
// Tell log4php to use our configuration file.
Logger::configure('config.xml');
// Fetch a logger, it will inherit settings from the root logger
$log = Logger::getLogger('myLogger');
// Start logging
$log->warn($_REQUEST); // Logged because WARN >= WARN
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\Authentication\AccessToken;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
//define('VERIFY_TOKEN', '*******');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == '<VERIFY TOKEN>') {
echo $_GET['hub_challenge'];
$log->warn($_GET);
$log->warn($_POST);
} else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
// Here you can do whatever you want with the JSON object that you receive from FaceBook.
// Before you decide what to do with the notification object you might aswell just check if
// you are actually getting one. You can do this by choosing to output the object to a textfile.
// It can be done by simply adding the following line:
// file_put_contents('/filepath/updates.txt',$updates, FILE_APPEND);
$log->warn($updates);
$log->warn($_GET);
$log->warn($_POST);
error_log('updates = ' . print_r($obj, true));
}
Thank you for your help !
There is currently an open bug with Facebook support:
https://developers.facebook.com/bugs/709097499224897/
So it's possible that this is a temporary issue...
What's the output of /{your-app-id}/subscriptions?
According to your code you subscribed to /conversations which requires read_page_mailboxes permissions. You probably want to try a simple page feed subscription first to see if this works.
RTU updates seem to be back to normal since yesterday, but deleting your subscriptions and re-subscribing might be worth a try, too, since you probably subscribed to a black hole when RTU had issues yesterday.
I find answer with a big help from facebook developers forum friends :)
My code to make subscription and callback code is good. But to get conversations or feed it is not enough. I have to add my app to my page as a subscribed_app using request in graph api:
POST
{page-id}/subscribed_apps
the docs for this operation is on:
https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps/

Facebook TokenResponseException with Laravel 4.1 and oauth-4-laravel

I'm getting a TokenResponseException from Laravel when I try to login to my web site with Facebook using oauth-4-laravel.
OAuth \ Common \ Http \ Exception \ TokenResponseException
Failed to request resource.
Using Facebook's JavaScript API works like its supposed to, so I'm pretty sure my application is configured correctly.
Are there any known issues that might cause this problem? Am I doing something wrong, or is this a bug in the library?
With the exception of a redirect line that works around another bug, my code is identical to the example code at the GitHub page. I think the exception is thrown when I try to get the token from the Facebook Service object.
Here's the code:
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from google, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
// ref: https://github.com/artdarek/oauth-4-laravel/issues/27
//return Response::make()->header( 'Location', (string)$url );
return Redirect::to((string)$url);
}
}
And a screenshot:
I had this exact same problem. It turns out that my issue was that my return_uri was missing a trailing slash, which through off the entire process. Make sure that when you're calling it you've added it.
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to/');
NOT
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to');
first try to load file_get_contents("https://www.facebook.com");
if allow_url_fopen=0 was set in the php.ini it will not work so you need to change it to allow_url_fopen=1
The weirdest thing i have your problem with google not with facebook, so here is my code maby it helps you fix your fb problem
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
Since my previous answer was deleted.. Let's try again..
--
After some debugging I think I got it. Commenting out the error_reporting part visible in your code snippet will already tell you a lot. The file_get_contents call got a 401 Unauthorized because the tokens were no longer valid.
After changing code, start your auth process from the beginning and don't refresh your url half-way, that wil cause the error.
The problem should be here $token = $fb->requestAccessToken( $code );
When I tried var_dump it, I get this.
object(OAuth\OAuth2\Token\StdOAuth2Token)[279]
protected 'accessToken' => string 'your-accessToken' (length=180)
protected 'refreshToken' => null
protected 'endOfLife' => int 1404625939
protected 'extraParams' =>
array (size=0)
empty
Try this and check what you've get as accessToken. Anyway, your function loginWithFacebook working fine with me.
I had the same problem. I was trying to access facebook graph. It wasn't that it could not access the URL, it was that Facebook was returning a 400 error because I wasn't passing parameters through. Try connecting to HTTPS on a site that will have a working HTTPS connection. E.g. Try this:
file_get_contents("https://www.namhost.com");
If that works, you must see why the HTTPs connection you are connecting to is failing, because the problem isn't that you can't connect to HTTPs, but rather that what you are connecting to isn't liking the request.

Writing a twitter API using php that is username specific

I've written a twitter api application using the following tutorial:
http://www.youtube.com/watch?v=GQaPt-gQVRI
How can I modify the script to generate a timeline stream that is specific to a user so that the application when run will show user's timeline stream and not mine (since i wrote the app and therefore it has my twitter credentials)
Thanks
the php application validates my twitter credentials using the following:
<?php
require 'tmhOAuth.php'; // Get it from: https://github.com/themattharris/tmhOAuth
// Use the data from http://dev.twitter.com/apps to fill out this info
// notice the slight name difference in the last two items)
$connection = new tmhOAuth(array(
'consumer_key' => 'my key',
'consumer_secret' => 'my secret',
'user_token' => 'my token', //access token
'user_secret' => 'my user secret' //access token secret
));
// set up parameters to pass
$parameters = array();
if ($_GET['count']) {
$parameters['count'] = strip_tags($_GET['count']);
}
if ($_GET['screen_name']) {
$parameters['screen_name'] = strip_tags($_GET['screen_name']);
}
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else {
$twitter_path = '1.1/statuses/user_timeline.json';
}
$http_code = $connection->request('GET', $connection->url($twitter_path), $parameters );
if ($http_code === 200) { // if everything's good
$response = strip_tags($connection->response['response']);
if ($_GET['callback']) { // if we ask for a jsonp callback function
echo $_GET['callback'],'(', $response,');';
} else {
echo $response;
}
} else {
echo "Error ID: ",$http_code, "<br>\n";
echo "Error: ",$connection->response['error'], "<br>\n";
So without having to pass a new username in the api call, how can i add a snippet to require the user to log in? and if i add that snippet for the user to log in, will the api automatically populate the authentication strings with the user's?
You can send a get request to the following url to get a users timeline.
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2
You can replace the parameters screen_name with the username you want to access, and you can replace count with the number of tweets you would like to get, count is optional and doesn't have to be included.
You can read more about statuses/user_timeline on the office twitter API site: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
If you wish to get a user to sign in then your best bet would be to use the twitteroauth library by abraham
Download and include in your project, then include the library and start a session.
require("twitteroauth/twitteroauth.php");
session_start();
Then create a new instance and authenticate with your app details. You can set a url to redirect to when the user authenticates. You also need to cache your tokens.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET');
$request_token = $twitteroauth->getRequestToken('http://example.com/loggedin.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
Redirect the user to twitter to authenticate
header('Location: '.$twitteroauth->getAuthorizeURL($request_token['oauth_token']));
In the file that you set twitter to redirect to you need to re-authenticate using the tokens created. Twitter will also add a parameter to your url which you use to create a access token for that user. Now when you send GET requests to twitter, it does it on behalf of the user logged in.
require("twitteroauth/twitteroauth.php");
session_start();
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$user_info = $twitteroauth->get('account/verify_credentials');
print_r($user_info);
You can get additional details from $user_info which you can cache or store in a database, which will allow you to remember users that have already authenticated. You will need to use oauth_token and oauth_secret, something like this.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', 'OAUTH_TOKEN', 'OAUTH_SECRET');

facebook php sdk - catch if user didnt give permissions (authentication failed)

Documentation says:
"redirect_uri - (optional) The URL to redirect the user to once the login/authorization process is complete. The user will be redirected to the URL on both login success and failure, so you must check the error parameters in the URL as described in the authentication documentation. If this property is not specified, the user will be redirected to the current URL (i.e. the URL of the page where this method was called, typically the current URL in the user's browser)."
So there is a method to catch if user refused autnentication/permissions, but link to corresponding documentation doesnt exist anymore (https://developers.facebook.com/docs/authentication/).
For the simplicity, redirect_uri is same address as a starting php file, and the php code is as simple as:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'X',
'secret' => 'Y',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user) {
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'http://myapp.com/app'
);
$loginUrl = $facebook->getLoginUrl($params);
}
Anybody knows how to catch that information?
You can do following to check the permissions:
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
// Do the related task
$post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
} else {
// We don't have the permission
// Alert the user or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
It should be noted that in the newest PHP facebook SDK, there is no method ->api. There also seems to be an issue using this check (sometimes) to get permissions. When using the older SDK, sometimes (randomly by user it seemed) some users were getting "OAuthException: (#412) User has not installed the application" even though a check on the FB access token debugger showed proper permissions. After I updated to new SDK, and figured out the new way to get a simple data list of permissions, everything worked again.
It took me a lot of digging in the FB website to find this solution, so I paste it here to hopefully save somebody else a few hours. They real life saver was my discovery of the getDecodedBody method (a very hard to find trick in FB docs). My example just checks for publish_actions.
$fb = new Facebook\Facebook([
'app_id' => your_app_id,
'app_secret' => your_secret,
'default_graph_version' => 'v2.2',
]);
$badperms=true; //start by assume bad permissions
try {
$response = $fb->get('/me/permissions', $at);
$perms = $response->getDecodedBody();
if($badperms){
foreach($perms['data'] AS $perm){
if($perm['permission']=='publish_actions' && $perm['status']=='granted') $badperms=false;
}
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
log("MSG-received facebook Response exception!! ".$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
log("MSG-received facebook SDK exception!! ".$e->getMessage());
}
if($badperms) {
//do something like reflow auth
}
I just had the same issue, I didn't know how to treat the cancel action (both in facebook php api and google oauth2).
The solution is much easier than expected.
The response in case of permission not accepted (at all) comes with at least one parameter/variable: error in the URL.
In facebook that response looks like:
error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied
for google you only get the
error=access_denied
but it should be enough.
I'm just checking if error is set and if it's set I am redirecting the response to my login page.
I hope it will help someone because it's really not documented this step.
By the way:
version of facebook API: v5
version of google API oAuth2: 2.0 (i think - google doc is really a mess when it comes to finding the latest versions)

Auth problems with OAuth (Facebook App), session is not available?

I want to read all birthdays of the friends from current user. I use the new Graph API of facebook. I request the authorization of the permissions (read_friendslist and friends_birthday) based on Facebooks insights example and php-sdk example. For reading the friendslist and the user details I used the Graph API with Facebook PHP SDK.
The upcoming code snippets are a short self contained correct example of my approach. If I try to use my app it requests login, then asks for permissions and then fails in printing all my friends due to the fact that no session is available. What's wrong here?
First is the birthday.php which is used by the following index.php, I removed some boilerplate code or code I think it's not causing this problem (identified by [...]). You can find the complete code on the end of this question.
<?php
function get_birthday_of_friends() {
$fbconfig['appid' ] = "MY_APP_ID";
$fbconfig['secret'] = "MY_APP_SECRET";
try{
include_once "facebook/src/facebook.php";
}
catch(Exception $o){
// [...] log error
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
// [...] return birthdays
} else {
echo "No session found";
}
}
?>
The required lib.php is identically with the insights example.
<?php
// [...] Include and define app-id etc.
function get_access_token($base_url) {
if (isset($_REQUEST['access_token'])) {
return $_REQUEST['access_token'];
}
$params = array();
$params['client_id'] = APP_ID;
$params['redirect_uri'] = $base_url;
if (!isset($_REQUEST['code'])) {
$params['scope'] = 'read_friendlists, friends_birthday';
$url = FacebookMethods::getGraphApiUrl('oauth/authorize', $params);
throw new RedirectionException($url);
} else {
$params['client_secret'] = APP_SECRET;
$params['code'] = $_REQUEST['code'];
$url = FacebookMethods::getGraphApiUrl('oauth/access_token');
$response = FacebookMethods::fetchUrl($url, $params);
$response = strstr($response, 'access_token=');
$result = substr($response, 13);
$pos = strpos($result, '&');
if ($pos !== false) {
$result = substr($result, 0, $pos);
}
return $result;
}
}
// [...] Call get_access_token() and get_birthday_of_friends()!
?>
Can you help me with that? I added the whole source code on pastebin.com if this helps you to identify my problem. Source code on pastebin.com for "index.php" and "birthday.php".
Thank you in advance!
I am not sure if the method that you are using is deprecated or not, but I know it's the old way and you should try with the new one in order to get the auth token.
Take a look at this link:
http://developers.facebook.com/docs/authentication/signed_request/
In a glance, you have to:
Get the signed_request parameter from $_REQUEST.
Use the sample function provided in
the link to decode it Once you decode
it, you will have an array in which
there is a parameter called
oauth_token.
With this parameter, you can start
making calls to the Graph by
appending it to the URL e.g.
*https://graph.facebook.com/PROFILE_ID/pictures/?access_token=OAUTH_TOKEN*
Make sure that you have Oauth 2.0 for Canvas enabled into the Configuration settings of your app (Advanced tab).
I think in some browsers there's a prblem with third party cookies. Are you testing in Safari? And also, try to add permissions to the loginUrl - it's a bit more simple than adding and requesting the permissions with oauth.
If no session is available, I had to redirect to the login page and require the extended permissions with the parameters. This did the trick to me, thanks to manuelpedrera for helping me out.
$facebook->getLoginUrl(array('req_perms' => 'read_friendlists, [...]'));

Categories