简体   繁体   English

使用PHP 3.1.1和Javascript SDK进行Facebook Oauth 2.0登录

[英]Facebook Oauth 2.0 Login using PHP 3.1.1 and Javascript SDKs

I am trying to migrate to the new Facebook API for websites, and just can't get it to work smoothly. 我正在尝试迁移到用于网站的新Facebook API,只是无法使其正常运行。 I would like to use the Javascript and PHP SDKs together, but am having problems. 我想同时使用Javascript和PHP SDK,但是遇到了问题。 I can authenticate, but the page doesn't refresh automatically. 我可以进行身份​​验证,但是页面不会自动刷新。

I have searched throughout SO and the Facebook documentation, but still can't get this to work correctly. 我已经搜索了整个SO和Facebook文档,但是仍然无法正常工作。 I have read through http://developers.facebook.com/blog/post/534/ , dowloaded the latest PHP SDK (3.1.1), and basically copied the example on the aforementioned post from facebook. 我已经阅读了http://developers.facebook.com/blog/post/534/ ,下载了最新的PHP SDK(3.1.1),并基本上从facebook复制了上述示例中的示例。 I have made what I think are the correct settings in my app 'Migration' settings, but this could be where the problem lies. 我已经在我的应用程序“迁移”设置中做出了我认为正确的设置,但这可能是问题所在。 I can't post an image, so here are the setting: 我无法发布图片,因此设置如下:

  • Remove Deprecated API's: Enabled 删除不推荐使用的API:已启用
  • Forces use of login secret: Enabled 强制使用登录密码:已启用
  • Encrypted Access token: Enabled 加密访问令牌:已启用
  • Enhanced Auth Dialog: Enabled 增强的身份验证对话框:已启用
  • (Everything else is disabled) (所有其他功能均被禁用)

Here is the code: 这是代码:

<?php

require 'php-sdk/src/facebook.php';

$facebook = new Facebook(array(
  'appId'  => 'YOUR_APP_ID',
  'secret' => 'YOUR_APP_SECRET',
));

// See if there is a user from a cookie
$user = $facebook->getUser();

if ($user) {
  try {
  // Proceed knowing you have a logged in user who's authenticated.
  $user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
  echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
  $user = null;
  }
}

?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <body>
    <?php if ($user_profile) { ?>
      Your user profile is 
      <pre>            
         <?php print htmlspecialchars(print_r($user_profile, true)) ?>
      </pre> 
    <?php } else { ?>
      <fb:login-button></fb:login-button>
    <?php } ?>
    <div id="fb-root"></div>
    <script>               
      window.fbAsyncInit = function() {
         FB.init({
           appId: '<?php echo $facebook->getAppID() ?>', 
           cookie: true, 
           xfbml: true,
           oauth: true
         });
        FB.Event.subscribe('auth.login', function(response) {
          window.location.reload();
        });
        FB.Event.subscribe('auth.logout', function(response) {
          window.location.reload();
        });
       };
      (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
          document.getElementById('fb-root').appendChild(e);
      }());
    </script>
  </body>
</html>

I was going to write this as a comment but it got a bit long... :) 我本打算将其写为评论,但时间有点长... :)

A couple of pointers using the PHP SDK: 使用PHP SDK的几个指针:

$facebook->getUser(); 

This will work regardless of authentication. 无论身份验证如何,这都将起作用。 getUser() pulls publicly available data that does not require an access token, HOWEVER if you do have an access token and the user has provided email permissions for example, this method will also contain their email address. getUser()提取不需要访问令牌的公共可用数据,但是,如果您确实具有访问令牌并且用户提供了email权限,例如,此方法还将包含其电子邮件地址。

A better test for an authenticated user: 对于经过身份验证的用户的更好测试:

$code = $_REQUEST['code'] ? true : false;
if (!$code) {
    echo ("<script>window.top.location=\"...\"</script>");
}

will check if a user has authorised your app. 将检查用户是否已授权您的应用。

$access = $facebook->getAccessToken();

Make sure that you always request the Access Token (priority!) You will only ever recieve a signed request when you have been redirected from a facebook dialogue to your app. 确保始终请求访问令牌(优先级!),只有当您从Facebook对话重定向到应用程序时,您才会收到签名的请求。 (ie) oAUTH dialogue. (即)oAUTH对话。 This method of the SDK will also save your Access Token to a session variable. SDK的这种方法还将您的访问令牌保存到会话变量中。 You can call the getAccessToken() method on any subsequent app page where a PHP session is active EVEN WHEN no signed request has been issued. 您可以在任何随后有PHP会话处于活动状态的应用程序页面上调用getAccessToken()方法,即使没有发出签名请求也是如此。

Now that you have your valid access token for the logged in user, you can proceed with: 现在您已经拥有登录用户的有效访问令牌,可以继续进行以下操作:

$user = $facebook->api('/me');

or, simpler still: 或者,更简单地说:

$user = $facebook->getUser();

I tend to reserve API calls for more complex requests such as posting to a users feed / friends feed. 我倾向于将API调用保留用于更复杂的请求,例如发布到用户供稿/朋友供稿。

So to recap: 总结一下:

-> check for $code -> get signed request on first page after oAuth dialogue. ->检查$code code->在进行OAuth对话后,在首页上获得签名的请求。 -> If browser cookies are disabled (likely in ie) don't forget to pass your session to the next page with the SID constant. ->如果浏览器cookie被禁用(可能在ie中),请不要忘记使用SID常量将您的会话传递到下一页。 If you don't, you will loose your stored access token (not good!). 否则,您将丢失存储的访问令牌(不好!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM