PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label facebook-access-token. Show all posts
Showing posts with label facebook-access-token. Show all posts

Wednesday, November 2, 2022

[FIXED] How to publish an image to a Facebook Page's albums via CURL along with getting new Page Access Tokens?

 November 02, 2022     curl, facebook, facebook-access-token, facebook-graph-api, php     No comments   

Issue

Currently, I have a website that allows users to upload images and at the same time I would like all these uploaded images to be published automatically to a Facebook page's albums. I used this CURL code below:

    $args = array(
       'message' => $imageDescription,
        'access_token'=>$accesstoken,
        'url' => $img
    );

    $ch = curl_init();
    $url = 'https://graph.facebook.com/' . $albumid . '/photos';
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    $data = curl_exec($ch);

    $response = json_decode($data,true);

From my test, this code works, but only for an hour, because I use the access token generated from the Graph API. This expiration is mentioned in https://developers.facebook.com/docs/pages/access-tokens#expire .

I have been looking around on Stack Overflow, and majority of the questions and answers mentioned the use of app ID and app secret to generate a new token, but this is a page and not an app. There is no app ID and app secret, so I am stuck.

So in this case, what can I do? Or is it not possible to use CURL in this case?


Solution

An app in this case doesn't refer to something like a game, it is referring to an API app. This is common for APIs that use OAuth to authenticate users. You create an app for your account and it allows you to access the Facebook API using your user account as the user accessing it.

The following post explains the entire thing and even has info about how the facebook API works https://stormpath.com/blog/what-the-heck-is-oauth



Answered By - Dan Hastings
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 16, 2022

[FIXED] How to detect logout event with the Facebook Android API v4?

 July 16, 2022     android, facebook, facebook-access-token, facebook-android-sdk, facebook-login     No comments   

Issue

I post here because I've got a problem. I'm working on a new android application , and I want to know how I can detect when a user is disconnecting (facebook logout button), because I want to refresh my UI at this moment.

I have been watched the official documentation, but I found nothing.


Solution

You can try this also

 if(AccessToken.getCurrentAccessToken()!=null)
 {
   Log.v("User is login","YES");

 }
else
{
         Log.v("User is not login","OK");
      LoginManager.getInstance().logInWithReadPermissions(WelcomeActivity1.this, (Arrays.asList("public_profile", "user_friends","user_birthday","user_about_me","email")));
 }


Answered By - Anny
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, March 13, 2022

[FIXED] How do I get the App Access Token via the Facebook PHP SDK?

 March 13, 2022     facebook, facebook-access-token, facebook-graph-api, facebook-php-sdk, php     No comments   

Issue

I'm trying to retrieve the app access token of my app in order to post notifications, but for some reason, it doesn't work. Here's the code:

$AppParams = array(
    'client_id'     => 'myclientid',
    '&client_secret' => 'myclientsecret',
    '&grant_type'    =>'client_credentials'
    );
$AppToken = $facebook->api('oauth/access_token?', 'GET', $AppParams);

I also replaced the first part with the full oauth/accesstoken link, but then it returns me general information about oauth and their facebook page, which I do not want. I did nearly the same thing in C# and there it works.


Solution

You don't really have to request an application access token. You can simply assemble one yourself.

An application access token is formatted like this:

app_id|app_secret

That's the application's id, a pipe character | and the application secret.

Make sure that this app token is not accessible to your users! Only use and reference it on the serverside - never pass this to the client. For more info, check out the last few sentences in the relevant documentation.



Answered By - Lix
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, March 6, 2022

[FIXED] Get Access Token from Facebook PHP SDK is not working properly

 March 06, 2022     codeigniter, facebook, facebook-access-token, facebook-php-sdk     No comments   

Issue

I'm trying to retrieve an Access Token from Facebook using PHP SDK 3.2.2, being the code below what I placed in the redirect url after a sucessfull user login in Facebook. My problem is that $this->facebook->getAccessToken() is not giving back the user access token after the user gives access to the APP, just a string with the form: 'AppId|AppSecret', and I have to include code to manually get the User Access Token. This work, but I don't know WHY when I use getAccessToken is not giving back the right Token. I would also like to know how if there is any better way to retrieve User Access Token than with $code, because I don't feel this is a good way of doing it.

NOTE: I use $this->facebook because I load it as a Codeigniter library.

  $access_token  = $this->facebook->getAccessToken();

  //-------------------------------------------------------------------------
  //echo '<br/>Access Token: ' . $access_token;
  // Generare Token if not created:
  $code = $_REQUEST["code"];

  if ( isset($code) ) {
     //echo '<br/>Code Enviado: ' . $code;
     //exit();
     $appId     = $this->facebook->getAppId();
     $appSecret = $this->facebook->getAppSecret();

     $redirectTo = base_url('asociar/acc_facebook/step2/');

     $token_url="https://graph.facebook.com/oauth/access_token?client_id="
        . $appId . "&redirect_uri=" . urlencode($redirectTo)
        . "&client_secret=" . $appSecret
        . "&code=" . $code . "&display=popup";
     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $access_token = $params['access_token'];

     //echo '<br/>Repitiendo el Token';

     $this->facebook->setAccessToken($access_token);
     //echo '<br/>Second Access Token Fijado: ' . $access_token;
  }
  //-----------------------------------------------------------------------

UPDATE:

This issue is due to I used CI with PHP SDK (check my own answer for that), but the answer is valid to anyone that have this issue with Facebook PHP SDK (Check @Imbru answer)


Solution

The response is little late, but may be it will help for other users.

I have got the same issue today.

My access_token was not correctly store in $_SESSION. Apparently, client side send juste one time the access_token. You have to store it in memory (SESSION) and reused it.

In normal time, Facebook PHP SDK do it...

EDIT : See @Chococroc response for more explanations



Answered By - Kevin ABRIOUX
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 5, 2022

[FIXED] Getting warning while creating a page access token with 'manage_pages' permission

 March 05, 2022     facebook, facebook-access-token, facebook-graph-api, facebook-php-sdk, php     No comments   

Issue

When I try to get a page_access token with 'manage_pages' permission, i get following warning

The following permissions have not been approved for use: manage_pages. If you make your app public, they will not be shown to people using your app. Submit them for review or learn more.

I am the admin of this facebook page.

Trying to retrieve My Fanpage's reviews in my website, through php sdk v4.


Solution

From v2.0 onwards, the permissions other than public_profile, email and the user_friends need to the submitted for review before you can make your app live; else you wont be able to use them. Only the testers/admin/developers of the app will be able to test with those permissions until the permissions are reviewed.

If you want to skip the review process, you can keep your app in the dev mode and use the page access token that will never expire. To generate such token , see the steps mentioned here.



Answered By - Sahil Mittal
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 26, 2022

[FIXED] Login with Facebook using Facebook SDK for PHP

 February 26, 2022     facebook-access-token, facebook-graph-api, facebook-login, facebook-php-sdk, php     No comments   

Issue

I have problems with making login to my site with Facebook.

I have created login using Facebook SDK by following the tutorial at developers.facebook.com , but it does not work for me.

I have wrote a simple test page to find out, what goes wrong. This is the code:

<!DOCTYPE html>
<html>
<head></head>
<body>
<pre>
<?php

$app_id         = '446458238729594';
$app_secret     = '********';
$redirect_uri   = 'http://mysite.localhost/';

try {

    echo( 'Including "facebook.php"...' );
    require './src/facebook.php';
    echo( "done.\n\n" );

    echo( 'Starting session...' );
    $result = session_start();
    if( $result ) {
        echo( "done.\n\n" );
        echo( "\n=====>>>>> Session array:\n" . var_export( $_SESSION, true )
                . "\n\n" );
    } else {
        echo( "fail.\n\n" );
        echo( "\n=====>>>>> Session array:\n" . var_export( $_SESSION, true )
                . "\n\n" );
    }

    echo( "Trying to get counter from the session...\n");
    if( isset( $_SESSION['counter'] ) ) {
        echo( 'Value: ' . $_SESSION['counter'] . "\n" );
        echo( "Increasing to one...\n");
        $_SESSION['counter']++;
        echo( "done.\n" );
        echo( 'Value: ' . $_SESSION['counter'] . "\n\n" );
    } else {
        echo( "fail.\n" );
        echo( "Trying to add a counter and set it's value to 0...\n");
        $_SESSION['counter'] = 0;
        echo( 'Value: ' . $_SESSION['counter'] . "\n" );
        echo( "done.\n\n" );
    }

    echo( 'Creating an instance of Facebook class...' );
    $facebook = new Facebook(
        array(
            'appId'     => $app_id,
            'secret'    => $app_secret,
        )
    );
    echo( "done.\n\n" );
    echo( "The instance of Facebook class:\n" . str_replace( $app_secret,
            '>>>APP_SECRET<<<', var_export( $facebook, true ) ) . "\n\n" );

    echo( "\n=====>>>>> Session array:\n" . var_export( $_SESSION, true )
            . "\n\n" );

    echo( 'Trying to get user ID...' );
    $user_id = $facebook->getUser();
    echo( "done.\n\n" );
    echo( "User ID:\n" . var_export( $user_id, true ) . "\n\n" );

    echo( "\n=====>>>>> Session array:\n" . var_export( $_SESSION, true )
            . "\n\n" );

    echo( 'Trying to get user profile info...' );
    try {
        $user_profile = $facebook->api( '/me' );
        echo( "done.\n\n" );
        echo( "User profile info:\n" . var_export( $user_profile, true )
                . "\n\n" );
    } catch( Exception $exception ) {
        echo( "fail. Probably user is not logged in.\n\n" );
        echo( "Exception:\n--------\n" . str_replace( $app_secret,
                '>>>APP_SECRET<<<', var_export( $exception, true ) )
                . "\n--------\n\n" );
        $user_id = null;
        echo( "User ID is now NULL.\n\n" );
    }

    echo( "\n=====>>>>> Session array:\n" . var_export( $_SESSION, true )
            . "\n\n" );

    if( $user ) {
        echo( 'Seems like user is logged in. Getting logout url...' );
        $url = $facebook->getLogoutUrl();
        echo( "done.\n\n" );
    } else {
        echo( 'Seems like user is NOT logged in. Getting login url...' );
        $url = $facebook->getLoginUrl(
            array(
                'scope'         => 'read_stream, publish_stream, user_birthday,'
                        . ' user_location, user_work_history, user_hometown,'
                        . ' user_photos',
                'redirect_uri'  => $redirect_uri,
            )
        );
        echo( "done.\n\n" );
    }
    echo( 'URL:<br></pre><a href=' . $url .">Login / Logout</a><pre>\n\n" );

    echo( "\n=====>>>>> Session array:\n"
            . var_export( $_SESSION, true ) . "\n\n" );

    if( $user ) {
        echo( 'Seems like user is still logged in. Trying to get some profile'
                . ' info...' );
        echo( "\nCreating request...\n" );
        $queries = array(
            array(
                'method'        => 'GET',
                'relative_url'  => '/' . $user,
            ),
            array(
                'method'        => 'GET',
                'relative_url'  => '/' . $user . '/home?limit=50',
            ),
            array(
                'method'        => 'GET',
                'relative_url'  => '/' . $user . '/friends',
            ),
            array(
                'method'        => 'GET',
                'relative_url'  => '/' . $user . '/photos?limit=6',
            ),
        );
        echo( "Request:\n\n" . var_export( $queries, true ) . "\n\n" );
        echo( "\nEncoding request using JSON format...\n" );
        $queries_encoded = json_encode( $queries );
        echo( "Encoded request:\n\n" . var_export( $queries_encoded, true )
                . "\n\n" );
        try {
            echo( "\nTrying to get response...\n" );
            $response = $facebook->api( '?batch=' . $queries_encoded, 'POST' );
            echo( "Response:\n\n" . var_export( $response, true ) . "\n\n" );
            echo( "\nTrying to decode response...\n" );
            echo( "\n" . json_decode( $response[0]['body'], true ) . "\n" );
            echo( "\n" . json_decode( $response[1]['body'], true ) . "\n" );
            echo( "\n" . json_decode( $response[2]['body'], true ) . "\n" );
            echo( "\n" . json_decode( $response[3]['body'], true ) . "\n" );
            echo( "\n\ndone.\n\n" );
        } catch( Exception $exception ) {
            echo( "fail.\n\n" );
            echo( "Exception:\n--------\n\n" . str_replace( $app_secret,
                    '>>>APP_SECRET<<<', var_export( $exception, true ) )
                    . "\n--------\n\n" );
        }
    } else {
        echo( 'Seems like user is still NOT logged in. At now we can\'t do'
                . ' anything. Try to login using the URL above.' );
    }

    echo( "\n\n========\n\nSession array:\n" . var_export( $_SESSION, true )
            . "\n\n" );

} catch( Exception $exception ) {
    echo( "\n\n\nAn exception have been trown:\n--------\n\n" . str_replace(
            $app_secret, '>>>APP_SECRET<<<', var_export( $exception, true ) )
            . "\n--------\n\n" );
    echo( "\n\n========\n\nSession array:\n" . var_export( $_SESSION, true )
            . "\n\n" );
}

?>
</pre>
</body>
</html>

After the first visit of this page (I am not logged in at Facebook), I get this output:

Including "facebook.php"...done.

Starting session...done.


=====>>>>> Session array:
array (
)

Trying to get counter from the session...
fail.
Trying to add a counter and set it's value to 0...
Value: 0
done.

Creating an instance of Facebook class...done.

The instance of Facebook class:
Facebook::__set_state(array(
   'sharedSessionID' => NULL,
   'appId' => '446458238729594',
   'appSecret' => '>>>APP_SECRET<<<',
   'user' => NULL,
   'signedRequest' => NULL,
   'state' => NULL,
   'accessToken' => NULL,
   'fileUploadSupport' => false,
   'trustForwarded' => false,
))


=====>>>>> Session array:
array (
  'counter' => 0,
)

Trying to get user ID...done.

User ID:
0


=====>>>>> Session array:
array (
  'counter' => 0,
)

Trying to get user profile info...fail. Probably user is not logged in.

Exception:
--------
FacebookApiException::__set_state(array(
   'result' => 
  array (
    'error_code' => 7,
    'error' => 
    array (
      'message' => 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
      'type' => 'CurlException',
    ),
  ),
   'message' => 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
   'string' => '',
   'code' => 7,
   'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
   'line' => 967,
   'trace' => 
  array (
    0 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
      'line' => 899,
      'function' => 'makeRequest',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => 'https://graph.facebook.com/me',
        1 => 
        array (
          'method' => 'GET',
          'access_token' => '446458238729594|>>>APP_SECRET<<<',
        ),
      ),
    ),
    1 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
      'line' => 866,
      'function' => '_oauthRequest',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => 'https://graph.facebook.com/me',
        1 => 
        array (
          'method' => 'GET',
        ),
      ),
    ),
    2 => 
    array (
      'function' => '_graph',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => '/me',
      ),
    ),
    3 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
      'line' => 644,
      'function' => 'call_user_func_array',
      'args' => 
      array (
        0 => 
        array (
          0 => 
          Facebook::__set_state(array(
             'sharedSessionID' => NULL,
             'appId' => '446458238729594',
             'appSecret' => '>>>APP_SECRET<<<',
             'user' => 0,
             'signedRequest' => NULL,
             'state' => NULL,
             'accessToken' => '446458238729594|>>>APP_SECRET<<<',
             'fileUploadSupport' => false,
             'trustForwarded' => false,
          )),
          1 => '_graph',
        ),
        1 => 
        array (
          0 => '/me',
        ),
      ),
    ),
    4 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/index.php',
      'line' => 69,
      'function' => 'api',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => '/me',
      ),
    ),
  ),
   'previous' => NULL,
))
--------

User ID is now NULL.


=====>>>>> Session array:
array (
  'counter' => 0,
)

Seems like user is NOT logged in. Getting login url...done.

URL:
Login / Logout


=====>>>>> Session array:
array (
  'counter' => 0,
  'fb_446458238729594_state' => '84260edcd60940884d261812496a488c',
)

Seems like user is still NOT logged in. At now we can't do anything. Try to login using the URL above.

========

Session array:
array (
  'counter' => 0,
  'fb_446458238729594_state' => '84260edcd60940884d261812496a488c',
)

Then I try to login using the given URL. It leads me to my Facebook app authorization page. After confirming the requested permissions, it redirects me to this URL:

http://mysite.localhost/?state=84260edcd60940884d261812496a488c&code=AQDkHPlXXweEiTjXg-sUXwwQAy0_xRYc89Opfz6AF9dlGOomCSG7fjf0440ctHuADKMEG4P7CheeNx9PnwUta-jkfpm03MjDCKyieOZpIPG-evlKYm64mRxD2Q5f_-HJROIC9I_-lHswr5RT3huSQySA55pD28b07Ouv87NqihZ1brGfU-_0LyhcdldtNikb-2xn6NRpa17xEmU37pBqDV1r#_=_

After that I expect that I am logged in and my page retrieves and shows me some info from my Facebook profile, but it doesn't. I get this output:

Including "facebook.php"...done.

Starting session...done.


=====>>>>> Session array:
array (
  'counter' => 0,
  'fb_446458238729594_state' => '84260edcd60940884d261812496a488c',
)

Trying to get counter from the session...
Value: 0
Increasing to one...
done.
Value: 1

Creating an instance of Facebook class...done.

The instance of Facebook class:
Facebook::__set_state(array(
   'sharedSessionID' => NULL,
   'appId' => '446458238729594',
   'appSecret' => '>>>APP_SECRET<<<',
   'user' => NULL,
   'signedRequest' => NULL,
   'state' => '84260edcd60940884d261812496a488c',
   'accessToken' => NULL,
   'fileUploadSupport' => false,
   'trustForwarded' => false,
))


=====>>>>> Session array:
array (
  'counter' => 1,
  'fb_446458238729594_state' => '84260edcd60940884d261812496a488c',
)

Trying to get user ID...done.

User ID:
0


=====>>>>> Session array:
array (
  'counter' => 1,
)

Trying to get user profile info...fail. Probably user is not logged in.

Exception:
--------
FacebookApiException::__set_state(array(
   'result' => 
  array (
    'error_code' => 7,
    'error' => 
    array (
      'message' => 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
      'type' => 'CurlException',
    ),
  ),
   'message' => 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
   'string' => '',
   'code' => 7,
   'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
   'line' => 967,
   'trace' => 
  array (
    0 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
      'line' => 899,
      'function' => 'makeRequest',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => 'https://graph.facebook.com/me',
        1 => 
        array (
          'method' => 'GET',
          'access_token' => '446458238729594|>>>APP_SECRET<<<',
        ),
      ),
    ),
    1 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
      'line' => 866,
      'function' => '_oauthRequest',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => 'https://graph.facebook.com/me',
        1 => 
        array (
          'method' => 'GET',
        ),
      ),
    ),
    2 => 
    array (
      'function' => '_graph',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => '/me',
      ),
    ),
    3 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/src/base_facebook.php',
      'line' => 644,
      'function' => 'call_user_func_array',
      'args' => 
      array (
        0 => 
        array (
          0 => 
          Facebook::__set_state(array(
             'sharedSessionID' => NULL,
             'appId' => '446458238729594',
             'appSecret' => '>>>APP_SECRET<<<',
             'user' => 0,
             'signedRequest' => NULL,
             'state' => NULL,
             'accessToken' => '446458238729594|>>>APP_SECRET<<<',
             'fileUploadSupport' => false,
             'trustForwarded' => false,
          )),
          1 => '_graph',
        ),
        1 => 
        array (
          0 => '/me',
        ),
      ),
    ),
    4 => 
    array (
      'file' => '/srv/www/htdocs/mysite/web/index.php',
      'line' => 69,
      'function' => 'api',
      'class' => 'BaseFacebook',
      'type' => '->',
      'args' => 
      array (
        0 => '/me',
      ),
    ),
  ),
   'previous' => NULL,
))
--------

User ID is now NULL.


=====>>>>> Session array:
array (
  'counter' => 1,
)

Seems like user is NOT logged in. Getting login url...done.

URL:
Login / Logout


=====>>>>> Session array:
array (
  'counter' => 1,
  'fb_446458238729594_state' => '6ae5ea9e5f7199fb6d19793905dcdd65',
)

Seems like user is still NOT logged in. At now we can't do anything. Try to login using the URL above.

========

Session array:
array (
  'counter' => 1,
  'fb_446458238729594_state' => '6ae5ea9e5f7199fb6d19793905dcdd65',
)

Please, help me figure out, why login does not work? Why the instance of Facebook class does not retrieve the access token? And why the method Facebook::getUser() always returns 0? How can I fix it?


Solution

Going to take a stab here - so patience please:

Possible cause 1: Your FB code looks good - but your error states:

"Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable" which points to a cURL issue.

Can you confirm your cURL is installed/working on your webserver? A simple phpinfo(); will tell you.

Possible Cause 2: Check that your app URL is set to the location you are running the tests from. Your redirect URI is "http://mysite.localhost/" - so make sure in your app setup page that it corresponds.

Lastly,

simply start with the basics, and then start adding all your extra code in. This works for me:

<?php

require 'src/facebook.php';

$facebook = new Facebook(array(
  'appId'  => 'xxxxxxxxxxxxxxxxxxx',
  'secret' => 'xxxxxxxxxxxxxxxxxxx',
));

// See if there is a user from a cookie
$user = $facebook->getUser();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
$logoutUrl = $facebook->getLogoutUrl();
  } catch (FacebookApiException $e) {
    echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
    $user = null;
$loginUrl = $facebook->getLoginUrl($params);
  }
}

?>

<?php if ($user) { ?>
    Your user profile is
    <?php print htmlspecialchars(print_r($user_profile, true)) ?>
    <a href="<?php echo $logoutUrl; ?>">Logout</a>
<?php } else { ?>
    <a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
<?php } ?>'


Answered By - DavidP
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 13, 2022

[FIXED] Getting an access token for a local Facebook script

 February 13, 2022     facebook, facebook-access-token, facebook-graph-api, facebook-php-sdk, php     No comments   

Issue

I will start this question by mentioning that this is my first experience with Facebook's API.

I have a script on my own PC, which is executed with WAMP. It fetches data from Facebook's Graph API, when given manually an access token from Graph API Explorer, getting a specific group's feed.

I would like my script to ask for an access token, and then just use file_get_contents to ask for the json string. I need the access token to have all the permissions available.

What should I do to make the next steps work?

  1. Open my PHP file. (already exists)
  2. The script will ask for an access token.
  3. It will print the content of https://graph.facebook.com/GROUP_ID/feed?=access_token=ACCESS_TOKEN

Solution

  1. If you are developing a facebook app, you don't need to login to facebook again. (Code snippets for both PHP and Javascript, use that is required to you.)

    [PHP]

    You can get the access_token by performing Http GET request on -

    https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials
    

    For more details: login as app

    [Javascript]

    FB.getLoginStatus(function(response) 
    {
      if (response.status === 'connected') 
      {
          var uid = response.authResponse.userID;
          var accessToken = response.authResponse.accessToken;
      } 
      else if (response.status === 'not_authorized') 
      {
         // the user is logged in to Facebook, 
         // but has not authenticated your app
      } 
      else 
      {
         // the user isn't logged in to Facebook.
      }
    });
    

    For more details: getLoginStatus

  2. If you are integrating fb with your website, you need to login first and in the response you can obtain the access token.

    Read this: Login Architecture

    [PHP] (Difficulty: High)

    Read this: server-side-login

    [Javascript] (Dfifficulty: Low)

    FB.login(function(response) 
    {
        if (response.authResponse)
        {
            console.log('Welcome!  Fetching your information.... ');
            var access_token = response.authResponse.accessToken;
        } 
        else 
        {
            console.log('User cancelled login or did not fully authorize.');
        }
     }); 
    

    More details: FB.Login



Answered By - Sahil Mittal
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, December 28, 2021

[FIXED] "The request is invalid because the app secret is the same as the client token" error when trying to get an access token

 December 28, 2021     app-secret, facebook-access-token, facebook-authentication, facebook-oauth, facebook-php-sdk     No comments   

Issue

I was using facebook php sdk without any problem to provide facebook login on my website. Since a few days, I'm unable to log in anymore. I follow the steps described on https://developers.facebook.com/docs/howtos/login/server-side-login/ but at step 6 it fails with the following response :

{
  error: {
    message: "The request is invalid because the app secret is the same as the client token",
    type: "OAuthException",
    code: 1
  }
}

I don't understand why it stopped working. Have you ever had the same problem ?

Thanks


Solution

I just encountered this problem and I fixed it by resetting my client token (Advanced > Security on the Facebook App settings page) and changing my app type from Native / Desktop to Web app.



Answered By - isyi
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing