How to login with OFFLINE_ACCESS using the new Facebook PHP SDK 3.0.0?

后端 未结 3 948
小鲜肉
小鲜肉 2021-01-31 06:35

with the old (2.x) SDK I used this to log someone with offline_access:

$session = array
(
    \'uid\' => $userdata[\'fb_uid\'],
    \'sig\' => $userdata[\'         


        
相关标签:
3条回答
  • 2021-01-31 06:56

    Quentin's answer is pretty nice but incomplete, I think. It works nice, but I for example getUser() isn't working in that time because userId (which is getUser() returning) is cached.

    I have created a new method to clear all caches and save it persistently.

    public function setPersistentAccessToken($access_token) {
      $this->setAccessToken($access_token);
      $this->user = $this->getUserFromAccessToken();
      $this->setPersistentData('user_id', $this->user);
      $this->setPersistentData('access_token', $access_token);
      return $this;
    }
    
    0 讨论(0)
  • 2021-01-31 07:01

    With the Facebook PHP SDK v3 (see on github), it is pretty simple. To log someone with the offline_access permission, you ask it when your generate the login URL. Here is how you do that.

    Get the offline access token

    First you check if the user is logged in or not :

    require "facebook.php";
    $facebook = new Facebook(array(
        'appId'  => YOUR_APP_ID,
        'secret' => YOUR_APP_SECRET,
    ));
    
    $user = $facebook->getUser();
    
    if ($user) {
      try {
        $user_profile = $facebook->api('/me');
      } catch (FacebookApiException $e) {
        // The access token we have is not valid
        $user = null;
      }
    }
    

    If he is not, you generate the "Login with Facebook" URL asking for the offline_access permission :

    if (!$user) {
        $args['scope'] = 'offline_access';
        $loginUrl = $facebook->getLoginUrl($args);
    }
    

    And then display the link in your template :

    <?php if (!$user): ?>
        <a href="<?php echo $loginUrl ?>">Login with Facebook</a>
    <?php endif ?>
    

    Then you can retrieve the offline access token and store it. To get it, call :

    $facebook->getAccessToken()
    

    Use the offline access token

    To use the offline access token when the user is not logged in :

    require "facebook.php";
    $facebook = new Facebook(array(
        'appId'  => YOUR_APP_ID,
        'secret' => YOUR_APP_SECRET,
    ));
    
    $facebook->setAccessToken("...");
    

    And now you can make API calls for this user :

    $user_profile = $facebook->api('/me');
    

    Hope that helps !

    0 讨论(0)
  • 2021-01-31 07:20

    With PHP SDK 2.0 (I guess), I just use it like

    $data = $facebook->api( '/me', 'GET', array( 'access_token' => $userdata['fb_access_token'] ) );
    

    This should work with the newer one to as it seems to be more of a clean approach than rather setting up sessions by ourself. Can you try?

    0 讨论(0)
提交回复
热议问题