PHP cURL验证服务器上的Facebook API登录access_token?

问题描述 投票:0回答:1

任何人都可以分享一个工作示例,说明如何使用cURL在我的PHP服务器上验证我从浏览器获得的Facebook access_token,以便我可以验证浏览器的登录详细信息是否值得信任,然后在我的服务器上安全地为我的用户创建会话?

要查看,我想要做的工作是:

  1. 用户在浏览器上单击“继续使用Facebook”并获取access_token。
  2. 我把它发送到我的PHP服务器。
  3. 服务器向Facebook发送cURL请求以验证用户access_token。
  4. 如果access_token有效,则在我的服务器上为该用户创建会话。

我有自己的应用程序与电子邮件,谷歌和Facebook登录。我感谢任何帮助,谢谢。

php facebook api curl login
1个回答
0
投票

经过一段时间,我得到了一个有效的PHP脚本。

只需替换丢失的变量值,它应该工作。还要确保使用phpinfo()或其他方法在PHP服务器上运行cURL;

<?php

///////////////////////////////////////
// prep Facebook verification
///////////////////////////////////////

// sanitize login data
$_POST['facebook_access_token'] = filter_var($_POST['facebook_access_token'], FILTER_SANITIZE_STRING);

// set variables
$facebook_user_access_token = $_POST['facebook_access_token'];
$my_facebook_app_id = 'REPLACE';
$my_facebook_app_secret = 'REPLACE';
$facebook_application = 'REPLACE'; // in my case 'domain.com', as set up in Facebook

///////////////////////////////////////
// get facebook access token
///////////////////////////////////////
$curl_facebook1 = curl_init(); // start curl
$url = "https://graph.facebook.com/oauth/access_token?client_id=".$my_facebook_app_id."&client_secret=".$my_facebook_app_secret."&grant_type=client_credentials"; // set url and parameters
curl_setopt($curl_facebook1, CURLOPT_URL, $url); // set the url variable to curl
curl_setopt($curl_facebook1, CURLOPT_RETURNTRANSFER, true); // return output as string
$output = curl_exec($curl_facebook1); // execute curl call
curl_close($curl_facebook1); // close curl
$decode_output = json_decode($output, true); // decode the response (without true this will crash)

// store access_token
$facebook_access_token = $decode_output['access_token'];

///////////////////////////////////////
// verify my access was legitimate
///////////////////////////////////////
$curl_facebook2 = curl_init(); // start curl
$url = "https://graph.facebook.com/debug_token?input_token=".$facebook_user_access_token."&access_token=".$facebook_access_token; // set url and parameters
curl_setopt($curl_facebook2, CURLOPT_URL, $url); // set the url variable to curl
curl_setopt($curl_facebook2, CURLOPT_RETURNTRANSFER, true); // return output as string
$output2 = curl_exec($curl_facebook2); // execute curl call
curl_close($curl_facebook2); // close curl
$decode_output2 = json_decode($output2, true); // decode the response (without true this will crash)

// test browser and Facebook variables match for security
if ($my_facebook_app_id == $decode_output2['data']['app_id'] && $decode_output2['data']['application'] == $facebook_application && $decode_output2['data']['is_valid'] == true) {
    echo 'Success. Login is valid.';
}
else {
    echo 'Error.';
}

?>

特别感谢https://stackoverflow.com/a/16092226/6252345

© www.soinside.com 2019 - 2024. All rights reserved.