Facebook、Oauth、PHP 以及在 MySQL 中存储 access_tokens

发布于 2024-12-14 08:09:08 字数 1515 浏览 1 评论 0原文

我已经开始破解一个函数,使用 PHP 通过我的网站提取 FB 数据,但可以在重新身份验证阶段获得一些帮助。

到目前为止,我已经有了它,以便访问者可以通过 FB 进行身份验证并获取他们的数据。我的下一个挑战是尝试在无需重新验证的情况下进行重复访问。

当前计划

为此,我将存储第一次访问时获得的访问令牌(在 MySQL 中)。当访问者返回时,我从数据库检索此访问令牌,并使用 cURL 函数尝试使用类似 ... 的 URL 获取内容,

$graph_url = "https://graph.facebook.com/me/home?date_format=U&limit=40" . "access_token=" . $access_token;

然后检查返回的内容是否有错误。如有必要,我会将访问者浏览器发送回 Facebook,通过这样的 URL 进行身份验证...

$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . $my_url . "&state=" . $_SESSION['state'] ;

(我了解用于原始身份验证的 URL 必须 在第一次访问和任何后续访问中都相同,所以我现在已经在一个脚本中获得了所有开关。)

然后返回代码(或请求令牌)。然后,使用此代码,我可以使用另一个 cURL 函数来尝试使用这个新的请求令牌(使用像这样的 URL)获取新的访问令牌...

$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . $my_url . "&client_secret=" . $app_secret . "&code=" . $code;

然后,新的访问令牌将返回到页面正文中,我可以抓取它,更新本地 MySQL 数据库版本并发出进一步的 FB 图形请求(使用上面的 $graph_url)。

问题

看起来 FB 在每次调用时都向我返回相同的访问令牌。我目前认为我已经编写了代码,并且我误解了 FB/Oauth 流程(但我当然可能是错的!)。

所以我的问题是......

(1)FB 是否有可能/正确地返回相同的访问令牌(也许在一段时间内)?

(2) 我是否应该使用另一个/不同的 URL 或参数来进行上面概述的调用?

(3) 谁能给我指出一个执行此类操作的示例脚本(是否使用 Facebook PHP SDK)?

(4) 还有其他指示、技巧等吗?

我并不自称是这方面的专家,但我已经为此工作了几个星期,并搜索了各种资源以获取示例,但显然在某个地方遗漏了要点。

提前致谢。 皮特.

I've started to hack around a function to pull in FB data via my site using PHP, but could do with some help about the re-authentication stages.

So far I have it so that a visitor can authenticate via FB and get their data. My next challenge is trying to make repeat visits work without having to re-authenticate.

Current Plan

To do this I am storing the access token I get on the first visit (in MySQL). When the visitor returns I retrieve this access token fro mthe db and using a cURL function try to get content using a URL like ...

$graph_url = "https://graph.facebook.com/me/home?date_format=U&limit=40" . "access_token=" . $access_token;

I then check the returned content for errors. If necessary, I send the visitors browser back to Facebook for authentication via a URL like this ...

$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . $my_url . "&state=" . $_SESSION['state'] ;

(I understand the URL used for the original authenticate must be the same in the first visit and any subsequent ones, so I've now got all switches in once script.)

This then returns the code (or request token). Using this code I can then use another cURL function to try and get a new access token using this new request token using a URL like this ...

$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . $my_url . "&client_secret=" . $app_secret . "&code=" . $code;

The new access token is then returned in the body of the page and I can grab this, update the local MySQL db version and make further FB graph requests (using the $graph_url above).

The Problem

It looks like FB is returning the same access token to me on each call. I currently think I have the code write, and that I have misunderstood the FB/Oauth flow (but I of course could be wrong!).

So my questions are ...

(1) is it possible/right for FB to return the same access token (maybe for a set period)?

(2) Should I be using another/different URL or parameters to make the calls I've outlined above?

(3) Can anyone point me to an example script (using the Facebook PHP SDK or not) that does this sort of thing?

(4) Any other pointers, tips, etc?

I don't profess to be an expert with all this, but I have been working on this for a few weeks now and scoured various resources for examples, but obviously missing the point somewhere.

Thanks in advance.
Pete.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮湿 2024-12-21 08:09:08

(1) FB 是否可能/正确地返回相同的访问令牌(也许在设定的时间内)?

是的,如果您为已经有效的用户会话请求访问令牌,您只会得到返回给您的相同令牌。

(2) 我是否应该使用另一个/不同的 URL 或参数来进行上面概述的调用?

你的网址一目了然。最好的计划是使用 Facebook 的 Graph API Explorer 来检查它们。

(3) 谁能给我提供一个执行此类操作的示例脚本(无论是否使用 Facebook PHP SDK)?

我可以提供一些我为最近的应用程序编写的快速助手,该应用程序使用 Facebook 提供的游戏/得分功能。这些可能或多或少对您有帮助:

// SERVER-SIDE
/**
 *  Simplified cURL function for Facebook API
 * 
 *  @param  string  $url    Properly encoded URL to cURL
 *  @param  string  $type   Expected return type
 *     
 *  @return string  $buffer Buffer of returned data (decoded if appropriate)
 *  
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */
function doCurl( $url , $type='JSON' )
{
  $ch = curl_init();
  curl_setopt( $ch , CURLOPT_URL , $url );
  curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT , 10 );
  curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
  $buffer = curl_exec( $ch );
  curl_close( $ch );

  if( strtolower( $type ) == 'json' )
  {
    $buffer = json_decode( $buffer );
  }    

  return $buffer;
}

/**
 *  Grab Data Thru the Graph API
 * 
 *  Structured call to the Graph API using cURL.  To grab general User info, 
 *  leave the $what parameter blank.
 * 
 *  @param  string  $token  User's access token
 *  @param  string  $what   API-specific reference to what data is requested
 *  @param  string  $who    
 * 
 *  @return string  $json   Decoded JSON object containing returned data
 * 
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */
function graphDo( $token , $what='' , $who="me" , $type='JSON' )
{
  return doCurl( 
    "https://graph.facebook.com/{$who}/{$what}?access_token={$token}" , $type 
  );
}



// CLIENT-SIDE 
/** 
 *  Get User's Current Score
 * 
 *  Assumes global-scope definitions for variables:
 *    facebook_user_access_token
 *
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */
facebookGetScore : function( p )
{
  var score_from_fb = '';

  $.ajax(
  {
    url: "https://graph.facebook.com/me/scores" ,
    data: 'access_token=' + facebook_user_access_token ,
    dataType: 'json' ,
    complete: function( data )
    {
      var responseText = $.parseJSON( data['responseText'] );

      score_from_fb = responseText['data']['0']['score'];

      if( p === true )
      {
        console.log( "Current score: " + score_from_fb );
      }            
    }
  });
} ,

/** 
 *  Set User's Score
 * 
 *  Passes client-side gamer score to a server-side PHP script to 
 *  set the score on Facebook without publishing the application's
 *  access token.
 *
 *  Assumes global-scope definitions for variables:
 *    facebook_user_id
 *    facebook_user_name
 *    facebook_user_access_token
 *    EXAMPLE.currentslide // Gameplay progress data
 *    facebook_application_access_token
 *
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */         
facebookSetScore : function( s , p ) 
{ 
  $.ajax(
  {
    url: "http://www.EXAMPLE.com/actions/ajax/setscore" ,
    data: "id=" + facebook_user_id + "&access_token=" + facebook_user_access_token + "&name=" + facebook_user_name + "&score=" + s + "&last_seen=" + EXAMPLE.currentslide ,
    complete: function( data )
    {
      if( p === true )
      {
        console.log( data['responseText'] ); 
      }
    }        
  });
}

(4) 还有其他指示、技巧等吗?

我最大的建议是使用 Facebook Graph API Explorer 预先构建您的调用并记录处理响应时的所有内容(我假设您正在使用 Firebug 或类似的东西); Facebook 的 API 响应在所有调用中都不太“标准”(甚至请求也没有完全标准化),因此您有时可能无法相信自己的直觉。

(1) is it possible/right for FB to return the same access token (maybe for a set period)?

Yes, if you are requesting an access token for an already-valid user session, you will simply get the same token returned to you.

(2) Should I be using another/different URL or parameters to make the calls I've outlined above?

Your URL's look good at a glance. The best plan is to use Facebook's Graph API Explorer to check them.

(3) Can anyone point me to an example script (using the Facebook PHP SDK or not) that does this sort of thing?

I can offer a couple quickie helpers I wrote for a recent application that uses the Game/Score functionality Facebook offers. These may be more or less helpful for you:

// SERVER-SIDE
/**
 *  Simplified cURL function for Facebook API
 * 
 *  @param  string  $url    Properly encoded URL to cURL
 *  @param  string  $type   Expected return type
 *     
 *  @return string  $buffer Buffer of returned data (decoded if appropriate)
 *  
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */
function doCurl( $url , $type='JSON' )
{
  $ch = curl_init();
  curl_setopt( $ch , CURLOPT_URL , $url );
  curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT , 10 );
  curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
  $buffer = curl_exec( $ch );
  curl_close( $ch );

  if( strtolower( $type ) == 'json' )
  {
    $buffer = json_decode( $buffer );
  }    

  return $buffer;
}

/**
 *  Grab Data Thru the Graph API
 * 
 *  Structured call to the Graph API using cURL.  To grab general User info, 
 *  leave the $what parameter blank.
 * 
 *  @param  string  $token  User's access token
 *  @param  string  $what   API-specific reference to what data is requested
 *  @param  string  $who    
 * 
 *  @return string  $json   Decoded JSON object containing returned data
 * 
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */
function graphDo( $token , $what='' , $who="me" , $type='JSON' )
{
  return doCurl( 
    "https://graph.facebook.com/{$who}/{$what}?access_token={$token}" , $type 
  );
}



// CLIENT-SIDE 
/** 
 *  Get User's Current Score
 * 
 *  Assumes global-scope definitions for variables:
 *    facebook_user_access_token
 *
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */
facebookGetScore : function( p )
{
  var score_from_fb = '';

  $.ajax(
  {
    url: "https://graph.facebook.com/me/scores" ,
    data: 'access_token=' + facebook_user_access_token ,
    dataType: 'json' ,
    complete: function( data )
    {
      var responseText = $.parseJSON( data['responseText'] );

      score_from_fb = responseText['data']['0']['score'];

      if( p === true )
      {
        console.log( "Current score: " + score_from_fb );
      }            
    }
  });
} ,

/** 
 *  Set User's Score
 * 
 *  Passes client-side gamer score to a server-side PHP script to 
 *  set the score on Facebook without publishing the application's
 *  access token.
 *
 *  Assumes global-scope definitions for variables:
 *    facebook_user_id
 *    facebook_user_name
 *    facebook_user_access_token
 *    EXAMPLE.currentslide // Gameplay progress data
 *    facebook_application_access_token
 *
 *  @author Andrew Kozak  < www.andrewkozak.com >
 */         
facebookSetScore : function( s , p ) 
{ 
  $.ajax(
  {
    url: "http://www.EXAMPLE.com/actions/ajax/setscore" ,
    data: "id=" + facebook_user_id + "&access_token=" + facebook_user_access_token + "&name=" + facebook_user_name + "&score=" + s + "&last_seen=" + EXAMPLE.currentslide ,
    complete: function( data )
    {
      if( p === true )
      {
        console.log( data['responseText'] ); 
      }
    }        
  });
}

(4) Any other pointers, tips, etc?

My biggest tip would be to use the Facebook Graph API Explorer to structure your calls beforehand and to log everything while working through the responses (I assume you're using Firebug or something comparable); Facebook's API responses are not quite "standard" across all calls (even the requests aren't completely standardized) so you may not be able to trust your intuition at times.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文