Home > Article > Backend Development > Authenticate users using Facebook Connect
Recently, there has been a lot of debate about lazy registration. It’s proven that the less users have to think, the higher the conversion rate! What a great idea! If everyone seems to have a Facebook profile, why not add one-click user registration? Today I'm going to show you how to do that.
Let us first create a database table.
CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(10), `oauth_uid` text, `username` text, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Pretty simple: We'll set up a user information table that contains the ID, username, first and last name, the URL to the user's picture, and the date of registration. Additionally, we have added the oauth_provider
and oauth_uid
fields to differentiate between different third-party open authentication protocols and their identifiers. For example, let's say next week you think it would be a good idea to ask Twitter users to join. It's simple; you just set another value for oauthprovider and avoid duplicating the oauthuid value.
Let's start by creating a new application. Name it and agree to the terms and conditions. Next, get the API Key and Secret in the Basic tab as shown below.
On the canvas tab, set the Canvas URL and Post-Authorization Redirect URL to your localhost and the path the script will handle - similar to http: //localhost.com/login_facebook.php?
. Note the question mark and domain at the end; both are required by Facebook. Just set your hosts
file to a valid domain name.
On the Connection tab, set the Connection URL to the same value and localhost.com
(or whatever you are using) as the base domain.
Now save, download the client library and extract the facebook.php
in the src
dir to the new directory created in the root directory.
The authentication process is divided into three steps:
Let’s do a quick test before registering and logging in.
# We require the library require("facebook.php"); # Creating the facebook object $facebook = new Facebook(array( 'appId' => 'YOUR_APP_ID', 'secret' => 'YOUR_APP_SECRET', 'cookie' => true )); # Let's see if we have an active session $session = $facebook->getSession(); if(!empty($session)) { # Active session, let's try getting the user id (getUser()) and user info (api->('/me')) try{ $uid = $facebook->getUser(); $user = $facebook->api('/me'); } catch (Exception $e){} if(!empty($user)){ # User info ok? Let's print it (Here we will be adding the login and registering routines) print_r($user); } else { # For testing purposes, if there was an error, let's kill the script die("There was an error."); } } else { # There's no active session, let's generate one $login_url = $facebook->getLoginUrl(); header("Location: ".$login_url); }
Now, visit http://localhost.com/login_facebook.php
and let’s see what happens. If you're redirected to Facebook and asked for permission, we're on the right track.
However, there may be two problems. First one: If you are redirected to Facebook but an error is displayed, there may be a missing value in the configuration. Go back to your application settings and check the "Connections" and "Canvas" tabs and make sure these fields are OK, as mentioned above.
There may be another issue where you see an error like "Uncaught CurlException: 60: SSL certificate problem, please verify that the CA certificate is OK." This happens because of the CURL settings. You have to open facebook.php
, find the makeRequest() method, and then find this line inside the function:
$opts = self::$CURL_OPTS;
Follow it by adding:
$opts[CURLOPT_SSL_VERIFYPEER] = false;
I hate hacking libraries, but I haven't found another way yet. Okay, let's move on to user registration. I also added a try/catch statement because if there is an old session key in the GET parameter in the URL, the script will terminate with a horrible error.
Next we will use MySQL. Note that I won't be implementing a data cleaner as I want the code to be as short as possible and get the job done. Remember this: always clean your data.
First, let's connect to the database.
mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD'); mysql_select_db('YOUR_DATABASE');
Now, let's handle the $session
condition in case we have a session.
# We have an active session; let's check if we've already registered the user $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']); $result = mysql_fetch_array($query); # If not, let's add it to the database if(empty($result)){ $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')"); $query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id()); $result = mysql_fetch_array($query); }
Please note that I am querying the database looking for facebook
as the oauth_provider
; if you want to accept other OAuth providers (like twitter, Google Accounts, Open ID, etc.) and oauth_uid
, this is usually a good idea as it is the identifier provided by the provider for their user accounts.
If we keep the oauth_provider
field as a text
field type, it may result in poor performance. Therefore, your best option is to set it to type ENUM.
We now have a $result
var that contains the value queried from the database. Next let's add some sessions. Add this line at the beginning of the script.
session_start();
After the empty($result)
condition, append the following:
if(!empty($user)){ # ... if(empty($result)){ # ... } # let's set session values $_SESSION['id'] = $result['id']; $_SESSION['oauth_uid'] = $result['oauth_uid']; $_SESSION['oauth_provider'] = $result['oauth_provider']; $_SESSION['username'] = $result['username']; }
由于对已登录的用户进行身份验证没有什么意义,因此在 session_start()
行下方添加:
if(!empty($_SESSION)){ header("Location: home.php"); }
在需要身份验证的脚本中,只需添加:
session_start(); if(!empty($_SESSION)){ header("Location: login_facebook.php"); }
如果您想显示用户名,请将其作为数组访问。
echo 'Welcome ' . $_SESSION['username']; # or.. echo 'Welcome ' . !empty($_SESSION) ? $_SESSION['username'] : 'guest';
Facebook 拥有大量连接功能,但我发现以下四个最有用。
我可能遗漏了一些东西,但 FQL 似乎比 Graph API 更灵活、更简单。幸运的是,Facebook 仍然允许开发人员使用它,尽管使用新库,它已经发生了一些变化。
如果您想要用户 ID、名字、姓氏、用户图片的平方缩略图、可用的最大用户图片以及他或她的性别,您可以使用 users.getInfo
方法。
$uid = $facebook->getUser(); $api_call = array( 'method' => 'users.getinfo', 'uids' => $uid, 'fields' => 'uid, first_name, last_name, pic_square, pic_big, sex' ); $users_getinfo = $facebook->api($api_call);
您可以检查 Users.getInfo 可用字段的完整列表。
使用 FQL 可以获得相同的结果。
$uid = $facebook->getUser(); $fql_query = array( 'method' => 'fql.query', 'query' => 'SELECT uid, first_name, last_name, pic_square, pic_big, sex FROM user WHERE uid = ' . $uid ); $fql_info = $facebook->api($fql_query);
以下是可使用 FQL 访问的表的列表,以及表用户可用的字段。
Facebook 为应用程序提供与用户数据的某些交互 - 只要获得授权即可。在旧的 API 中,额外权限的授权仅适用于 Javascript SDK(尽管我不太确定)。借助新的 API,我们可以轻松地将用户重定向到 Facebook 中的授权对话框,并在访问被授予或拒绝后返回到我们的网站。
在以下示例中,我们将重定向用户以授权帖子状态更新、照片、视频和注释、用户的真实电子邮件地址、生日以及对照片和视频的访问权限。
$uid = $facebook->getUser(); # req_perms is a comma separated list of the permissions needed $url = $facebook->getLoginUrl(array( 'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos' )); header("Location: {$url} ");
这是权限的完整列表。请注意,您可以指定用户接受时要定向到的 url 以及用户拒绝时要重定向到的 url。这些数组元素的键分别是 next
和 cancel_url
。这是一个简单的示例:
$url = $facebook->getLoginUrl(array( 'req_perms' => 'email', 'next' => 'http://localhost.com/thanks.php', 'cancel_url' => 'http://localhost.com/sorry.php' ));
如果未指定,则默认为请求脚本的位置。
由于用户可以轻松撤销权限,因此应用程序应始终在使用之前检查是否授予给定权限,特别是在发布某些内容时。我们将不得不使用旧版 API,因为新 API 似乎尚未完全实现它。
$uid = $facebook->getUser(); # users.hasAppPermission $api_call = array( 'method' => 'users.hasAppPermission', 'uid' => $uid, 'ext_perm' => 'publish_stream' ); $users_hasapppermission = $facebook->api($api_call); print_r($users_hasapppermission);
ext_perm
将仅支持旧的可用权限列表。
验证用户是否具有 publish_stream
权限后,让我们在墙上发布一些内容。
# let's check if the user has granted access to posting in the wall $api_call = array( 'method' => 'users.hasAppPermission', 'uid' => $uid, 'ext_perm' => 'publish_stream' ); $can_post = $facebook->api($api_call); if($can_post){ # post it! $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!')); echo 'Posted!'; } else { die('Permissions required!'); }
本质上,我们使用 POST 方法(第二个参数)和一个数组作为要发送的数据的第三个参数,对 /<user_id>/feed</user_id>
进行 API 调用。在这种情况下,第三个参数支持 message
、link
、picture
、caption
、name
和 description
。代码如下:
$facebook->api('/'.$uid.'/feed', 'post', array( 'message' => 'The message', 'name' => 'The name', 'description' => 'The description', 'caption' => 'The caption', 'picture' => 'http://i.imgur.com/yx3q2.png', 'link' => 'https://code.tutsplus.com ));
这是它的发布方式。
用户只需在他或她的墙上点击两次即可轻松撤销权限。您应该大量测试如果用户撤销对网站正常运行至关重要的一项或多项权限,或者即使应用程序被完全删除,可能会发生什么情况。这很重要。
虽然 Facebook 的身份验证功能确实很有用,但由于现在有很多人使用 Facebook,因此不建议将其用作网站中唯一的身份验证方法。那些没有 Facebook 帐户的人怎么办?他们不允许访问您的应用程序吗?感谢您的阅读!
The above is the detailed content of Authenticate users using Facebook Connect. For more information, please follow other related articles on the PHP Chinese website!