给php项目添加facebook的登录

2011年5月12日 | 标签:

facebook已经超越Google,twitter和其它登录,国外项目基本上都有添加facebook登录需求,那么接下来就是跟着我们来给你的php添加fb登录吧(针对国内的项目就不用想了)。
先从https://github.com/facebook/php-sdk下载facebook的php sdk

然后把压缩包中的facebook.php文件添加到你的项目中

比如目录./lib/facebook.php

压缩包中有一个exmaple.php的文件打开它,可以看到基本的使用方法

    //引用facebook
    require_once(dirname(__FILE__) . '/lib/facebook.php');
    $facebook = new Facebook(array(
    'appId'  => '应用ID(AppID)',
    'secret' => '密钥(App Secret)',
    'cookie' => true,
    ));

facebook app申请地址 http://www.facebook.com/developers/apps.php
在需要使用登录的页面添加facebook js引用

    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId   : '<?php echo $facebook->getAppId(); ?>',
          session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
          window.location.reload();
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>

<div id="fb-root"></div>

在需要显示登录框的位置添加

<fb:login-button></fb:login-button>

如果需要获取用户email需要email的授权

<fb:login-button perms="email"></fb:login-button>

如果获取用户的好友列表则需要read_friendlists授权 更多权限列表参考网址 http://developers.facebook.com/docs/authentication/permissions/

目前还没有任何评论.
您必须在 登录 后才能发布评论.