2

我想通过 Graph API(使用 Perl)获取 FB 用户数据。
我有一个 facebook 应用程序,配置为“带有 FB 登录的网站”。
我正在使用Net::Facebook::Oauth2

该应用程序配置有这样的回调URL:"http://localhost/myfile.pl"

当我打开 localhost/myfile.pl 时,它可以让我登录 facebook 并让应用程序访问我的数据。但是当涉及到它应该回退并获取访问令牌时(至少我认为这就是它接下来应该做的),它会以无限循环结束。

http://localhost/myfile.pl包含以下内容:

#!"C:\strawberry\perl\bin\perl.exe"
use CGI::Carp qw(fatalsToBrowser);  # this makes perl showing (syntax) errors in browser

use CGI;
    my $cgi = CGI->new;

    use Net::Facebook::Oauth2;

    my $fb = Net::Facebook::Oauth2->new(
        application_id => 'xxxMY_APP_IDXXX', 
        application_secret => 'xxxMY_SECRETxxx',
        callback => 'http://localhost/myFile.pl'
    );

    ###get authorization URL for your application
    my $url = $fb->get_authorization_url(
        scope => ['offline_access','publish_stream'],
        display => 'page'
    );

    ####now redirect to this url
    print $cgi->redirect($url);

    ##once user authorizes your application facebook will send him/her back to your application
    ##to the callback link provided above

    ###in your callback block capture verifier code and get access_token

    my $fb = Net::Facebook::Oauth2->new(
        application_id => 'xxxMY_APP_IDxxx',
        application_secret => 'xxxMY_SECRETxxx',
        callback => 'http://localhost/myFile.pl'
    );

    my $access_token = $fb->get_access_token(code => $cgi->param('code'));
    ###save this token in database or session

    ##later on your application you can use this verifier code to comunicate
    ##with facebook on behalf of this user

    my $fb = Net::Facebook::Oauth2->new(
        access_token => $access_token
    );

    my $info = $fb->get(
        'https://graph.facebook.com/me' ##Facebook API URL
    );

    print $info->as_json;

我在 Perl 脚本中做错了吗?或者是因为我的回调的本地主机?

在此先感谢,
克里斯托夫·特沃迪

4

1 回答 1

2

你应该使用一个参数来阻止无限循环的发生。基本上,应用程序对 FB 进行身份验证,然后再次调用相同的脚本,它会看到它已通过身份验证并永远循环。

if ( ! defined $cgi->param('code') ){
  my $access_token = $fb->get_access_token(code => $cgi->param('code'));
  my $fb = Net::Facebook::Oauth2->new(
    application_id => 'xxxMY_APP_IDxxx',
    application_secret => 'xxxMY_SECRETxxx',
    callback => "http://localhost/myFile.pl";
  );
  ###get authorization URL for your application
  my $url = $fb->get_authorization_url(
    scope => ['offline_access','publish_stream'],
    display => 'page'
  );

  ####now redirect to this url
  print $cgi->redirect($url);

} else {
  ##later on your application you can use this verifier code to comunicate
  ##with facebook on behalf of this user
  my $access_token = $fb->get_access_token(code => $cgi->param('code'));
  my $fb = Net::Facebook::Oauth2->new(
    access_token => $access_token
  );

  my $info = $fb->get(
    'https://graph.facebook.com/me' ##Facebook API URL
  );

  print $info->as_json;
}
于 2013-01-29T12:54:22.823 回答