Xây Dựng Chức Năng Đăng Nhập Facebook Trên Website Bằng SDK

Như những bài trước ở mục develop facebook mình đã có nói đến cách xây dựng một số chức năng facebook trên website bằng SDK facebook , bài này mình dựa theo tài liệu của facebook develop viết lại cách xây dựng chức năng đăng nhập bằng facebook trên website của bạn

Cũng như hiện nay bạn bắt gặp nhiều website yêu cầu bạn đăng nhập để sử dụng những tính năng , trong đó thường có đăng nhập bằng facebook , việc đăng nhập bằng facebook sẽ trở nên dễ dàng và nhanh chống hơn rất nhiều so với kiểu chuyền thống.

Tài Liệu Tham Khảo

Quá trình xác thực bằng facebook

Để xác thực bằng facebook chúng ta sẽ trải qua 4 bước cơ bản như sau:

Đầu tiên, từ trang web của mình, chúng ta yêu cầu người dùng cho phép truy cập vào thông tin của người dùng (Từ thông tin này ta sẽ dùng để đăng nhập vào hệ thống). Thực ra ở bước này ta sẽ chuyển hướng người dùng đến trang xác thực của facebook.

Tiếp theo, người dùng sẽ xác nhận và cung cấp cho ta các quyền để truy cập vào thông tin của người dùng.

Sau đó, facebook sẽ chuyển hướng người dùng về lại trang web của ta cùng với thông tin về quyền truy cập mà người dùng đã cho phép.

Từ thông tin facebook trả về, ta sẽ gọi các hàm API của facebook để lấy thông tin của người dùng như user name, email…

Với những thông tin đã có được, ta tiến hành đăng nhập cho người dùng ( chẳng hạn lưu vào session rằng người dùng đã đăng nhập), nếu muốn ta có thể sử dụng thông tin người dùng để lưu vào database.

Tôi đã hệ thống các bước trên lại thành sơ đồ đơn giản như sau:

hướng dẫn cấu hình , cài đặt facebook login bằng sdk

Bước 1 : các bạn truy cập vào địa chỉ sau Tại Đây tiến hành tạo cho mình một app id facebook.
nếu đã có apps id thì các bạn bỏ qua bước này


Bước 2 : Mã này tải và khởi chạy JavaScript SDK trong trang HTML của bạn. Thay thế {app-id} bằng ID ứng dụng của bạn và {api-version} bằng phiên bản API Đồ thị để sử dụng. Nếu bạn không có lý do cụ thể cho việc sử dụng phiên bản cũ hơn, hãy chỉ định phiên bản mới nhất: v5.0.
Code Đầy Đủ
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>

function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console
.log('statusChangeCallback');
console
.log(response); // The current login status of the person.
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI
();
} else { // Not logged into your webpage or we are unable to tell.
document
.getElementById('status').innerHTML = 'Please log ' +
'into this webpage.';
}
}


function checkLoginState() { // Called when a person is finished with the Login Button.
FB
.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback
(response);
});
}


window
.fbAsyncInit = function() {
FB
.init({
appId
: '{app-id}',
cookie
: true, // Enable cookies to allow the server to access the session.
xfbml
: true, // Parse social plugins on this webpage.
version
: '{api-version}' // Use this Graph API version for this call.
});


FB
.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback
(response); // Returns the login status.
});
};


(function(d, s, id) { // Load the SDK asynchronously
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js
= d.createElement(s); js.id = id;
js
.src = "https://connect.facebook.net/en_US/sdk.js";
fjs
.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
console
.log('Welcome! Fetching your information.... ');
FB
.api('/me', function(response) {
console
.log('Successful login for: ' + response.name);
document
.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}

</script>


// The JS SDK Login Button

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

<div id="status">
</div>

</body>
</html>

ví dụ về lấy mã truy cập từ facebook sdk

Để SDK JavaScript đặt cookie bao gồm yêu cầu được đánh dấu (có bao gồm thông tin về người dùng đã đăng nhập), đầu tiên bạn phải khởi chạy SDK JavaScript với tùy chọn {cookie: true}.
<html>
<body>

<p><a href="#" onClick="logInWithFacebook()">Log In with the JavaScript SDK</a></p>

<script>
logInWithFacebook
= function() {
FB
.login(function(response) {
if (response.authResponse) {
alert
('You are logged in &amp; cookie set!');
// Now you can redirect the user or do an AJAX request to
// a PHP script that grabs the signed request from the cookie.
} else {
alert
('User cancelled login or did not fully authorize.');
}
});
return false;
};
window
.fbAsyncInit = function() {
FB
.init({
appId
: 'your-app-id',
cookie
: true, // This is important, it's not enabled by default
version
: 'v2.2'
});
};

(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js
= d.createElement(s); js.id = id;
js
.src = "https://connect.facebook.net/en_US/sdk.js";
fjs
.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</body>
</html>
Sau khi người dùng đăng nhập thành công, chuyển hướng người dùng (hoặc tạo yêu cầu AJAX) đến một tập lệnh PHP lấy mã truy cập từ yêu cầu được đánh dấu tồn tại trong cookie.
# /js-login.php
$fb
= new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);

$helper
= $fb->getJavaScriptHelper();

try {
$accessToken
= $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo
'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo
'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}

if (! isset($accessToken)) {
echo
'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}

// Logged in
echo
'<h3>Access Token</h3>';
var_dump
($accessToken->getValue());

$_SESSION
['fb_access_token'] = (string) $accessToken;

// User is logged in!
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');



Artikel Terkait