简体   繁体   English

Facebook,Oauth,PHP并在MySQL中存储access_tokens

[英]Facebook, Oauth, PHP and storing access_tokens in MySQL

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. 我已经开始尝试使用PHP通过我的网站获取FB数据的功能,但是可以在重新认证阶段提供一些帮助。

So far I have it so that a visitor can authenticate via FB and get their data. 到目前为止,我已经有了它,以便访客可以通过FB进行身份验证并获取其数据。 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). 为此,我存储了第一次访问时获得的访问令牌(在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 ... 当访问者返回时,我从数据库中检索了此访问令牌,并使用cURL函数尝试使用类似...的URL获取内容。

$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 ... 如有必要,我会通过这样的URL将访客浏览器发送回Facebook进行身份验证...

$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.) (我知道用于原始身份验证的URL在第一次访问时和随后的访问中都必须相同,因此现在我将所有开关都放在一个脚本中。)

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 ... 然后,使用此代码,我可以使用另一个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;

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). 然后,新的访问令牌返回到页面的主体中,我可以抓住它,更新本地MySQL数据库版本,并进行进一步的FB图请求(使用上面的$ graph_url)。

The Problem 问题

It looks like FB is returning the same access token to me on each call. 看起来FB在每次通话中都向我返回了相同的访问令牌。 I currently think I have the code write, and that I have misunderstood the FB/Oauth flow (but I of course could be wrong!). 我目前认为我已经编写了代码,并且误解了FB / Oauth流程(但是我当然可能错了!)。

So my questions are ... 所以我的问题是...

(1) is it possible/right for FB to return the same access token (maybe for a set period)? (1)FB是否有可能/有权返回相同的访问令牌(可能在设定的时间段内)?

(2) Should I be using another/different URL or parameters to make the calls I've outlined above? (2)我应该使用其他/不同的URL或参数进行上面概述的呼叫吗?

(3) Can anyone point me to an example script (using the Facebook PHP SDK or not) that does this sort of thing? (3)谁能指出我一个执行此类操作的示例脚本(是否使用Facebook PHP SDK)?

(4) Any other pointers, tips, etc? (4)还有其他指针,技巧等吗?

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. 皮特。

(1) is it possible/right for FB to return the same access token (maybe for a set period)? (1)FB是否有可能/有权返回相同的访问令牌(可能在设定的时间段内)?

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? (2)我应该使用其他/不同的URL或参数进行上面概述的呼叫吗?

Your URL's look good at a glance. 您的网址一目了然。 The best plan is to use Facebook's Graph API Explorer to check them. 最好的计划是使用Facebook的Graph API Explorer进行检查。

(3) Can anyone point me to an example script (using the Facebook PHP SDK or not) that does this sort of thing? (3)谁能指出我一个执行此类操作的示例脚本(是否使用Facebook PHP SDK)?

I can offer a couple quickie helpers I wrote for a recent application that uses the Game/Score functionality Facebook offers. 我可以提供我为最近使用Facebook提供的Game / Score功能的应用程序编写的快速帮助程序。 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? (4)还有其他指针,技巧等吗?

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 Graph API Explorer预先构造您的调用,并在处理响应时记录所有内容(我假设您正在使用Firebug或类似产品); 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. Facebook的API响应在所有调用中都不十分“标准”(即使请求未完全标准化),因此您有时可能无法相信自己的直觉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM