1.首先通过前端FB.init初始化,其中很重要的参数就是appId,该参数需要在facebook developer平台申请,创建应用,添加相应的ip 地址或者域名。
2.引入facebook 提供的js,获取facebook用户信息
3.将用户信息传给后台程序,将用户信息存入数据库。
1 <script>
2 logInWithFacebook= function() {
3 FB.login(function(response) {
4 if (response.authResponse) {
5 var accessToken =response.authResponse.accessToken;
6 FB.api('/me?fields=name,email,first_name,last_name', function(response) {
7 userEmail=response.email;
8 if(response.email!=null){
9 $.ajax({
10 url:"<?=Yii::$app->urlManager->createUrl(['account/third-part-login']); ?>",
11 data:{
12 userName:response.name,
13 firstName:response.first_name,
14 lastName:response.last_name,
15 email:response.email,
16 access_token:accessToken,
17 third_part_type:'facebook',
18 openid:response.id,
19 image:''
20 },
21 dataType:"json",
22 type:"post",
23 success:function(data){
24 if(data.code=200){
25 window.location =data.url;
26 }
27 }
28 });
29 }else{
30 alert("It fails to login within third part.");
31 }
32
33 });
34
35 //alert('You are logged in & cookie set!');
36 // Now you can redirect the user or do an AJAX request to
37 // a PHP script that grabs the signed request from the cookie.
38 } else {
39 alert('User cancelled login or did not fully authorize.');
40 }
41 },{scope: 'email'});
42 return false;
43 };
44 window.fbAsyncInit = function() {
45 FB.init({
46 appId: "<?php echo Yii::$app->params['fb_app_id'];?>",
47 cookie: true, // This is important, it's not enabled by default
48 version: 'v2.9'
49 });
50 };
51
52 (function(d, s, id){
53 var js, fjs = d.getElementsByTagName(s)[0];
54 if (d.getElementById(id)) {return;}
55 js = d.createElement(s); js.id = id;
56 js.src = "//connect.facebook.net/en_US/sdk.js";
57 fjs.parentNode.insertBefore(js, fjs);
58 }(document, 'script', 'facebook-jssdk'));
59 </script>