I cannot find any documentation on this.
Here is my code:
I'm using Laravel 5.5 and Facbook graph. Im posting to a page but I got this error fb_exchange_token parameter not specified but I have successfully logged in.
Due to shoddy documentation I cannot find anything on fb_exchange_token on the Facebook's website nor elsewhere.
Can anyone help?
{
$facebook = Facebooks::findOrFail($id);
$fb = new Facebook([
'app_id' => 'my_id', // Replace {app-id} with your app id
'app_secret' => 'my_secret',
'default_graph_version' => 'v3.3',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages', 'publish_pages']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach($pages as $key){
if($key['name'] == 'CloudGuest Test'){
if(isset($_POST['facebook_status'])){
$text1 = $_POST['facebook_status'];
$post = $fb->post('/' . $key['id'] . '/feed', array('message' =>$text1),$key['access_token']);
$post = $post->getGraphNode()->asArray();
print_r($post);
}
}
}
}
Related
Hi guys i need your help, i installed facebook sdk with composer on my application, y created a login system, on facebook developer i added my dev domain on localhost https://devlocalhost.io and my domain from production, so in localhost the loging is working fine, but on production i get this error
Argument 3 passed to GuzzleHttp\Client::request() must be of the type array, string given, called in /home/user/src/app/vendor/guzzlehttp/guzzle/src/Client.php on line 89
here is part of my code,
on my SecurityController
public function facebookCallback(Request $request,UserPasswordEncoderInterface $encoder)
{
$fb = $this->facebook();
$helper = $this->fHelper($fb);
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name,email,link,picture', $accessToken->getValue());
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user_info = $response->getGraphUser();
//here i create the user on my app or check if the user exist
}
So, here are my private method to the Facebook object and helper
private function facebook()
{
$fb = new Facebook([
'app_id' => 'myapp-id', // Replace {app-id} with your app id
'app_secret' => 'my-secret',
'default_graph_version' => 'v3.1',
]);
return $fb;
}
private function fHelper($fb)
{
$helper = $fb->getRedirectLoginHelper();
return $helper;
}
private function furlLogin()
{
$fb = $this->facebook();
$helper = $this->fHelper($fb);
$permissions = ['email']; // Optional permissions
//$loginUrl = $helper->getLoginUrl('https://devlocalhost.io/es/fb-callback/', $permissions);
$loginUrl = $helper->getLoginUrl('https://my_domain.com/es/fb-callback/', $permissions);
return $loginUrl;
}
so, on local host ys working fine but when i did the deploy os the branch i installed the dependency on server etc, is giving me this error
any idea?
I'm trying to get the list of pages a user manages.
The FB documentation for v2.12 says that I should use GetGraphNode().
try {
// Returns a `FacebookFacebookResponse` object
$response = $fb->get(
'/{user-id}/accounts',
'{access-token}'
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
When I try this, I get an exception : "Unable to convert response from Graph to a GraphNode because the response looks like a GraphEdge. Try using GraphNodeFactory::makeGraphEdge() instead."
I tried $pages=$response->makeGraphEddge(); but this doesn't work.
Any idea ?
Thank you.
I'm working with Laravel 5.2 and I'm using SammyK/laravel-facebook-sdk Package i Tried the code in the following link enter link description here
I keep on having this error : "Cross-site request forgery validation failed. The "state" param from the URL and session do not match."
this is my controller code :
public function callbackfbsdk(Facebook $fb){
$helper = $fb::getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(['email']);
var_dump($loginUrl);
try {
$token = $fb::getAccessTokenFromRedirect();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
if (! $token) {
// Get the redirect helper
$helper = $fb::getRedirectLoginHelper();
if (! $helper->getError()) {
abort(403, 'Unauthorized action.');
}
// User denied the request
dd(
$helper->getError(),
$helper->getErrorCode(),
$helper->getErrorReason(),
$helper->getErrorDescription()
);
}
if (! $token->isLongLived()) {
$oauth_client = $fb::getOAuth2Client();
try {
$token = $oauth_client->getLongLivedAccessToken($token);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
}
$fb::setDefaultAccessToken($token);
Session::put('fb_user_access_token', (string) $token);
try {
$response = $fb::get('/me?fields=id,name,email');
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
$facebook_user = $response->getGraphUser();
$user = App\User::createOrUpdateGraphNode($facebook_user);
// Log the user into Laravel
Auth::login($user);
return redirect('/')->with('message', 'Successfully logged in with Facebook');
}
Any Ideas about how can I solve this error??
why you are putting these line in callback
$helper = $fb::getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(['email']);
it will try to generate link again after redirect.seperate it, will solve the problem
I am using symfony. I have to create programme for facebook login. I created on class and in that create two function first is for generating link and other is callback function.
In controller created one action name is indexAction, in that object of class present. But when we run programme using link as http://localhost/symfony-demo-project/web/app_dev.php/login on browser it gives Error like:
The autoloader expected class "Btit\Bundle\CommonBundle\facebook\facebookLogin" to be defined in file "/var/www/html/symfony-demo-project/src/Btit/Bundle/CommonBundle/facebook/facebookLogin.php". The file was found but the class was not in it, the class name or namespace probably has a typo.
<?php
namespace Btit\Bundle\CommomBundle\facebook;
use Facebook\Facebook;
$fb = new Facebook/Facebook([
'app_id' => '1622871987981966',
'app_secret' => '6a15b7ae9e4409b6d33553ed3ed61f95',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://localhost/symfony-demo-project/app-dev.php/login/', $permissions);
echo 'Log in with Facebook!';
}
function Callback()
{
$fb = new Facebook/Facebook([
'app_id' => '1622871987981966',
'app_secret' => '6a15b7ae9e4409b6d33553ed3ed61f95',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');
}
}
?>
Controller is like that
<?php
namespace Btit\Bundle\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Btit\Bundle\CommonBundle\facebook\facebookLogin;
class LoginController extends Controller
{
/**
* #Route("/login")
* #Template()
*/
public function indexAction()
{
$l = new facebookLogin;
$l->LoginLink();
$l->Callback();
//return array();
}
}
?>
Give me solution for this error...
I am using php api's in my website (to make a profile page)
I am using the below code:
$action = $_REQUEST["action"];
switch($action){
case "fblogin":
include 'facebook.php';
$appid = "**********";
$appsecret = "*************************";
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => TRUE,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
$user_profile = $facebook->api('/me');
}
catch (Exception $e) {
echo $e->getMessage();
exit();
}
$user_fbid = $fbuser;
$user_email = $user_profile["email"];
$user_fnmae = $user_profile["first_name"];
$user_image = "https://graph.facebook.com/".$user_fbid."/picture?type=large";
$check_select = mysql_num_rows(mysql_query("SELECT * FROM `fblogin` WHERE email = '$user_email'"));
if($check_select > 0){
mysql_query("INSERT INTO `fblogin` (fb_id, name, email, image, postdate) VALUES ('$user_fbid', '$user_fnmae', '$user_email', '$user_image', '$now')");
}
}
break;
}
It gives an error saying : Undefined index: action
I am using wamp server as localhost. Please provide a solution