php - 如何从 Facebook 获取访问 token

标签 php mysql facebook token

我无法获取 token 并在数据库中记录。因为 Facebook 更新了隐私政策,现在 token 的有效期为 60 天。我应该怎么办? ##

<?php
include('connect.ini.php');
require_once 'facebook.php'; 
/** Create our Application instance. */ 
$query = "SELECT app_id,app_secret FROM f_settings WHERE id=1";
$result = mysql_fetch_array(mysql_query($query));
$application_id = $result[0];
$application_secret = $result[1];
$facebook = new Facebook(array('appId' => $application_id,'secret' => $application_secret,'cookie' => true,));



if(isset($_POST['user_id']) && isset($_POST['status']) && isset($_POST['page_id']))
{
if($_POST['status'] == 'connected') // User is already connected with our         facebook application so he will be redirected to survey url
{
    $page_id = $_POST['page_id'];
    $query = "SELECT * FROM f_urls WHERE shrinked_url_id='$page_id'";
    $apply = mysql_query($query) or die('error 1');
    $result = mysql_fetch_array($apply) or die('error 2');
    $survey_url = $result['survey_url'];                
    die($survey_url);    // redirecting him to survey url 
}   
if($_POST['status'] == 'connecting')  // user is first time connecting to our application
{

    $me = $facebook->api('/me/permissions');        // Double checking wheather use has allowed our application     
    if($me['data']['0']['publish_stream'] == 1)
    {
        $user_id = $_POST['user_id'];       
        $query = "SELECT COUNT(*) FROM f_users WHERE facebook_id='$user_id'";   // for fraud detection we check wheather user is really first time connecting to our app by searching him in our database
        $apply = mysql_query($query) or die('e1');
        $result = mysql_fetch_array($apply) or die('e2');       
        if($result[0] == 0)                 // if user is first time connected we will redirect him to content url :-)  
        {
            $me = $facebook->api('/me');
            $facebook_id = $me['id'];
            $gender = $me['gender'];
            $email = $me['email'];
            $name = $me['namez'];               
            $date = date('d-m-Y');
            $ip = $_SERVER['REMOTE_ADDR'];              
            // Checking for updating facebook status

            $query = "SELECT * FROM f_settings WHERE id=1";
            $apply = mysql_query($query);
            $result = mysql_fetch_array($apply);

            $web_link = $result['web_link'];
            $pic_link = $result['pic_link'];        
            $status_msg = $result['status_message'];    
            $update_status = $result['update_status'];

            if($update_status == 'true')
            {
                try {                       
                    $facebook->api('/me/feed','POST',array('message'=>$status_msg,'link'=>$web_link,'picture'=>$pic_link)); 
                } catch (FacebookApiException $e){

                    }                       
            }

            $send_email = $result['send_email'];
            $message_subject = $result['message_subject'];
            $sender_name = $result['sender_name'];
            $reply_to = $result['reply_to'];
            $email_address = $result['email_address'];
            $message_body = $result['message_body'];

            if($send_email == 'true')
            {
                if($reply_to == false)
                {
                    $reply_to='no-reply@website.com';   
                }
                else
                {
                    $reply_to = $email_address; 
                }
                $headers = 'From:'.$sender_name.'<'.$email_address.'>'."\r\n";
                $headers .= 'To:'.$name.'<'.$email.'>'."\r\n".'Reply-To:'.$reply_to."\r\n";
                $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
                $headers .= "X-Priority: 3\r\n";
                $headers .= "X-Mailer: PHP". phpversion() ."\r\n";

                mail($email,$message_subject, str_replace('[user_name]',$name,$message_body) ,$headers);

            }               
            $id = $_POST['page_id'];                
            $query = "INSERT INTO f_users SET unlocked_url='$id',facebook_id='$facebook_id',name='$name',email='$email',gender='$gender',date='$date',ip='$ip'";
            if(mysql_query($query)) // Inserting this new user details into our database
            {
                $page_id = $_POST['page_id'];
                $query = "SELECT * FROM f_urls WHERE shrinked_url_id='$page_id'";
                $apply = mysql_query($query) or die('error 1');
                $result = mysql_fetch_array($apply) or die('error 2');
                die($result['content_url']);    // redirecting user to content url
            }
        }           
        else                // if user is trying to connect to our application for the second time he will be redirected to survey url
        {
            $page_id = $_POST['page_id'];
            $query = "SELECT * FROM f_urls WHERE shrinked_url_id='$page_id'";
            $apply = mysql_query($query) or die('error 1');
            $result = mysql_fetch_array($apply) or die('error 2');
            $survey_url = $result['survey_url'];                
            die($survey_url);    // redirecting him to survey url       
        }
    }
    else
    {
        die('you must connect');
    }
}
}
?>

我想将 token 保存在mysql数据库中,以便应用程序稍后进行搜索。

最佳答案

我之前已经实现了与您的请求类似的内容,这就是我所做的:

  1. 新用户:您需要用户对您的应用进行身份验证,并且 获取accesstoken,保存到数据库
  2. 已经是用户:从您的数据库中检查他/她的 token 并进行验证 是否仍然有效(60天),是否过期(超过60天) 或用户更改密码),您需要通过获取来扩展验证 一个新的 token 。

这是我的代码,希望对您有所帮助。

if ($user) {
  try {
    //check whether the user is in database, if not means 1st time authenticate
    mysql_connect($db_host, $db_user, $db_pass) or die (mysql_error());
    mysql_select_db($db_name) or die (mysql_error());
    $tbl_name="token";
    $sql="SELECT access_token from $tbl_name where userid = $user";
    $result=mysql_query($sql);
    $message="default message";
    $updatetoken="default update token";

    if (mysql_num_rows($result)){
        $CONDITION = 1;
        $message="get one user";

        while ($row = mysql_fetch_row($result)) {
            $access_token = $row[0];
        }
        $graph_url = "https://graph.facebook.com/me?". "access_token=" . $access_token;
        $response = curl_get_file_contents($graph_url);
        $decoded_response = json_decode($response);
        if ($decoded_response->error) {
            $facebook->setExtendedAccessToken();
            $access_token = $facebook->getAccessToken();
            //udpate table with this new created access_token
            $updatetoken="UPDATE $tbl_name SET access_token='$access_token' WHERE userid=$user";
            mysql_query($updatetoken) ;
        }
        else {
            $facebook->setAccessToken($access_token);
        }

    }
    else {
        $CONDITION = 2;
        $message="do not have that user";
        $facebook->setExtendedAccessToken();
        $access_token = $facebook->getAccessToken();
        $updatetoken="INSERT INTO $tbl_name(userid,access_token)VALUES('$user', '$access_token')";
        $result = mysql_query($updatetoken);
    }

我认为回答你的关键部分是检查代码的graph_url部分

关于php - 如何从 Facebook 获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20834308/

相关文章:

PHP preg_match 特定字段值

php - 使用 SQL 数据创建数组或 json

php - 循环遍历 PDO 中的数据

java - 使用 Java 的 Facebook OAuth 登录(仅限桌面)

PHP 排序速度

python - 安装后出现mysqlclient无法安装的错误?

mysql - 如何设置logstash.conf?

php - MySQL 计数未针对特定 ID 返回 0

node.js - generateJWT 不是一个函数

php - 使用 symfony2 进行 Facebook + UserBundle 身份验证