Facebook-OpenGraph

 view release on metacpan or  search on metacpan

lib/Facebook/OpenGraph.pm  view on Meta::CPAN

        redirect_uri => $self->redirect_uri,
        code         => $code,
    };
    return $self->_get_token($query_ref);
}

sub get_user_token_by_cookie {
    my ($self, $cookie_value) = @_;

    croak 'cookie value is not given' unless $cookie_value;

    my $parsed_signed_request = $self->parse_signed_request($cookie_value);

    # https://github.com/oklahomer/p5-Facebook-OpenGraph/issues/1#issuecomment-41065480
    # parsed content should be something like below.
    # {
    #     algorithm => "HMAC-SHA256",
    #     issued_at => 1398180151,
    #     code      => "SOME_OPAQUE_STRING",
    #     user_id   => 44007581,
    # };
    croak q{"code" is not contained in cookie value: } . $cookie_value
        unless $parsed_signed_request->{code};

    # Redirect_uri MUST be empty string in this case.
    # That's why I didn't use get_user_token_by_code().
    my $query_ref = +{
        code         => $parsed_signed_request->{code},
        redirect_uri => '',
    };
    return $self->_get_token($query_ref);
}

# Access Tokens > Expiration and Extending Tokens
# https://developers.facebook.com/docs/facebook-login/access-tokens/
sub exchange_token {
    my ($self, $short_term_token) = @_;

    croak 'short term token is not given' unless $short_term_token;

    my $query_ref = +{
        grant_type        => 'fb_exchange_token',
        fb_exchange_token => $short_term_token,
    };
    return $self->_get_token($query_ref);
}

sub _get_token {
    my ($self, $param_ref) = @_;

    croak 'app_id and secret must be set' unless $self->app_id && $self->secret;

    $param_ref = +{
        %$param_ref,
        client_id     => $self->app_id,
        client_secret => $self->secret,
    };

    my $response = $self->request('GET', '/oauth/access_token', $param_ref);
    # Document describes as follows:
    # "The response you will receive from this endpoint, if successful, is
    # access_token={access-token}&expires={seconds-til-expiration}
    # If it is not successful, you'll receive an explanatory error message."
    #
    # It, however, returnes no "expires" parameter on some edge cases.
    # e.g. Your app requests manage_pages permission.
    # https://developers.facebook.com/bugs/597779113651383/
    if ($response->is_api_version_eq_or_later_than('v2.3')) {
        # As of v2.3, to be compliant with RFC 6749, response is JSON formatted
        # as described below.
        # {"access_token": <TOKEN>, "token_type":<TYPE>, "expires_in":<TIME>}
        # https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.3#confirm
        return $response->as_hashref;
    }

    my $res_content = $response->content;
    my $token_ref = +{ URI->new("?$res_content")->query_form };
    croak "can't get access_token properly: $res_content"
        unless $token_ref->{access_token};

    return $token_ref;
}

sub get {
    return shift->request('GET', @_)->as_hashref;
}

sub post {
    return shift->request('POST', @_)->as_hashref;
}

# Deleting > Objects
# https://developers.facebook.com/docs/reference/api/deleting/
sub delete {
    return shift->request('DELETE', @_)->as_hashref;
}

# For those who got used to Facebook::Graph
*fetch   = \&get;
*publish = \&post;

# Using ETags
# https://developers.facebook.com/docs/reference/ads-api/etags-reference/
sub fetch_with_etag {
    my ($self, $uri, $param_ref, $etag) = @_;

    # Attach ETag value to header
    # Returns status 304 without contnet, or status 200 with modified content
    my $header   = ['IF-None-Match' => $etag];
    my $response = $self->request('GET', $uri, $param_ref, $header);

    return $response->is_modified ? $response->as_hashref : undef;
}

sub bulk_fetch {
    my ($self, $paths_ref) = @_;

    my @queries = map {
        +{
            method       => 'GET',
            relative_url => $_,

lib/Facebook/OpenGraph.pm  view on Meta::CPAN

1;
__END__

=head1 NAME

Facebook::OpenGraph - Simple way to handle Facebook's Graph API.

=head1 VERSION

This is Facebook::OpenGraph version 1.31

=head1 SYNOPSIS

  use Facebook::OpenGraph;

  # fetching public information about given objects
  my $fb = Facebook::OpenGraph->new;
  my $user = $fb->fetch('zuck');
  my $page = $fb->fetch('oklahomer.docs');
  my $objs = $fb->bulk_fetch([qw/zuck oklahomer.docs/]);

  # get access_token for application
  my $token_ref = Facebook::OpenGraph->new(+{
      app_id => 12345,
      secret => 'FooBarBuzz',
  })->get_app_token;

  # user authorization
  my $fb = Facebook::OpenGraph->new(+{
      app_id       => 12345,
      secret       => 'FooBarBuzz',
      namespace    => 'my_app_namespace',
      redirect_uri => 'https://sample.com/auth_callback',
  });
  my $auth_url = $fb->auth_uri(+{
      scope => [qw/email publish_actions/],
  });
  $c->redirect($auth_url);

  my $req = Plack::Request->new($env);
  my $token_ref = $fb->get_user_token_by_code($req->query_param('code'));
  $fb->set_access_token($token_ref->{access_token});

  # publish photo
  $fb->publish('/me/photos', +{
      source  => '/path/to/pic.png',
      message => 'Hello world!',
  });

  # publish Open Graph Action
  $fb->publish_action($action_type, +{$object_type => $object_url});

=head1 DESCRIPTION

Facebook::OpenGraph is a Perl interface to handle Facebook's Graph API.
This module is inspired by L<Facebook::Graph>, but mainly focuses on simplicity
and customizability because we must be able to keep up with frequently changing
API specification.

This module does B<NOT> provide ways to set and validate parameters for each
API endpoint like Facebook::Graph does with Any::Moose. Instead it provides
some basic methods for HTTP request. It also provides some handy methods that
wrap C<request()> for you to easily utilize most of Graph API's functionalities
including:

=over 4

=item * API versioning that was introduced at f8, 2014.

=item * Acquiring user, app and/or page token and refreshing user token for
long lived one.

=item * Batch Request

=item * FQL

=item * FQL with Multi-Query

=item * Field Expansion

=item * Etag

=item * Wall Posting with Photo or Video

=item * Creating Test Users

=item * Checking and Updating Open Graph Object or Web Page with OGP

=item * Publishing Open Graph Action

=item * Deleting Open Graph Object

=item * Posting Staging Resource for Open Graph Object

=back

In most cases you can specify endpoints and request parameters by yourself and
pass them to request() so it should be easier to test latest API specs. Other
requesting methods merely wrap request() method for convinience.

=head1 METHODS

=head2 Class Methods

=head3 C<< Facebook::OpenGraph->new(\%args) >>

Creates and returns a new Facebook::OpenGraph object.

I<%args> can contain...

=over 4

=item * app_id

Facebook application ID. app_id and secret are required to get application
access token. Your app_id should be obtained from
L<https://developers.facebook.com/apps/>.

=item * secret

Facebook application secret. It should be obtained from
L<https://developers.facebook.com/apps/>.

=item * version

This declares Facebook Platform version. From 2014-04-30 they support versioning
and migrations. Default value is undef because unversioned API access is also
allowed. This value is prepended to the end point on C<request()> unless
you specify one in requesting path.

  my $fb = Facebook::OpenGraph->new(+{version => 'v2.0'});
  $fb->get('/zuck');      # Use version 2.0 by accessing /v2.0/zuck
  $fb->get('/v1.0/zuck'); # Ignore the default version and use version 1.0

  my $fb = Facebook::OpenGraph->new();
  $fb->get('/zuck'); # Unversioned API access since version is not specified
                     # on initialisation or reqeust.

As of 2015-03-29, the latest version is v2.3. Detailed information should be
found at L<https://developers.facebook.com/docs/apps/versions> and
L<https://developers.facebook.com/docs/apps/migrations>.

=item * ua

This should be L<Furl::HTTP> object or similar object that provides same
interface. Default is equivalent to Furl::HTTP->new(capture_request => 1).
You B<SHOULD> install 2.10 or later version of Furl to enable capture_request
option. Or you can specify keep_request option for same purpose if you have Furl
2.09. Setting capture_request option is B<strongly> recommended since it gives
you the request headers and content when C<request()> fails.

  my $fb = Facebook::OpenGraph->new;
  $fb->post('/me/feed', +{message => 'Hello, world!'});
  #2500:- OAuthException:An active access token must be used to query information about the current user.
  #POST /me/feed HTTP/1.1
  #Connection: keep-alive
  #User-Agent: Furl::HTTP/2.15

lib/Facebook/OpenGraph.pm  view on Meta::CPAN

API documentation says.

=head3 C<< $fb->is_beta >>

Accessor method that returns whether to use Beta tier or not.

=head3 C<< $fb->json >>

Accessor method that returns JSON object. This object will be passed to
Facebook::OpenGraph::Response via C<create_response()>.

=head3 C<< $fb->use_appsecret_proof >>

Accessor method that returns whether to send appsecret_proof parameter on API
call. Official document is not provided yet, but PHP SDK has this option and
you can activate this option from App Setting > Advanced > Security.

=head3 C<< $fb->use_post_method >>

Accessor method that returns whether to use POST method for every API call and
alternatively set method=(GET|POST|DELETE) query parameter. PHP SDK works this
way. This might work well when you use multi-query or some other functions that use GET method while query string can be very long and you have to worry about
the maximum length of it.

=head3 C<< $fb->version >>

Accessor method that returns Facebook Platform version. This can be undef
unless you explicitly on initialisation.

=head3 C<< $fb->uri($path, \%query_param) >>

Returns URI object with specified path and query parameter. If is_beta returns
true, the base url is https://graph.beta.facebook.com/ . Otherwise its base url
is https://graph.facebook.com/ . C<request()> automatically determines if it
should use C<uri()> or C<video_uri()> based on target path and parameters so
you won't use C<uri()> or C<video_uri()> directly as long as you are using
requesting methods that are provided in this module.

=head3 C<< $fb->video_uri($path, \%query_param) >>

Returns URI object with specified path and query parameter. This should only be
used when posting a video.

=head3 C<< $fb->site_uri($path, \%query_param) >>

Returns URI object with specified path and query parameter. It is mainly used to
generate URL for Auth dialog, but you can still use this when redirecting users
to your Facebook page, App's Canvas page or any location on facebook.com.

  my $fb = Facebook::OpenGraph->new(+{is_beta => 1});
  $c->redirect($fb->site_uri($path_to_canvas));
  # https://www.beta.facebook.com/$path_to_canvas

=head3 C<< $fb->parse_signed_request($signed_request_str) >>

It parses signed_request that Facebook Platform gives to you on various
situations. situations may include

=over 4

=item * Given as a URL fragment on callback endpoint after login flow is done
with Login Dialog

=item * POSTed when Page Tab App is loaded

=item * Set in a form of cookie by JS SDK

=back

Fields in returning value are introduced at
L<https://developers.facebook.com/docs/reference/login/signed-request/>.

  my $req = Plack::Request->new($env);
  my $val = $fb->parse_signed_request($req->query_param('signed_request'));

=head3 C<< $fb->auth_uri(\%args) >>

Returns URL for Facebook OAuth dialog. You can redirect your user to this
URL for authorization purpose.

If Facebook Platform version is set on initialisation, that value is
prepended to the path.
L<https://developers.facebook.com/docs/apps/versions#dialogs>.

See the detailed flow at L<https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow>.
Optional values are shown at L<https://developers.facebook.com/docs/reference/dialogs/oauth/>.

  my $auth_url = $fb->auth_uri(+{
      display       => 'page', # Dialog's display type. Default value is 'page.'
      response_type => 'code',
      scope         => [qw/email publish_actions/],
  });
  $c->redirect($auth_url);

=head3 C<< $fb->set_access_token($access_token) >>

Set $access_token as the access token to be used on C<request()>. C<access_token()>
returns this value.

=head3 C<< $fb->get_app_token >>

Obtain an access token for application. Give the returning value to
C<set_access_token()> and you can make request on behalf of your application.
This access token never expires unless you reset application secret key on App
Dashboard so you might want to store this value within your process like
below...

  package MyApp::OpenGraph;
  use parent 'Facebook::OpenGraph';

  sub get_app_token {
      my $self = shift;
      return $self->{__app_access_token__}
          ||= $self->SUPER::get_app_token->{access_token};
  }

Or you might want to use L<Cache::Memory::Simple> or something similar to
refetch token at an interval of your choice. Maybe you want to store token on
DB and override this method to return the stored value.

=head3 C<< $fb->get_user_token_by_code($given_code) >>

Obtain an access token for user based on C<$code>. C<$code> should be obtained
on your callback endpoint which is specified on C<eredirect_uri>. Give the
returning access token to C<set_access_token()> and you can act on behalf of
the user.

FYI: I<expires> or I<expires_in> is B<NOT> returned on some edge cases. The
detail and reproductive scenario should be found at
L<https://developers.facebook.com/bugs/597779113651383/>.

  # On OAuth callback page which you specified on $fb->redirect_uri.
  my $req          = Plack::Request->new($env);
  my $token_ref    = $fb->get_user_token_by_code($req->query_param('code'));
  my $access_token = $token_ref->{access_token};
  my $expires      = $token_ref->{expires}; # named expires_in as of v2.3

=head3 C<< $fb->get_user_token_by_cookie($cookie_value) >>

Obtain user access token based on the cookie value that is set by JS SDK.
Cookie name should be determined with C<js_cookie_name()>.

FYI: I<expires> or I<expires_in> is B<NOT> returned on some edge cases. The
detail and reproductive schenario should be found at
L<https://developers.facebook.com/bugs/597779113651383/>.

  if (my $cookie = $c->req->cookie( $fb->js_cookie_name )) {
    # User is not logged in yet, but cookie is set by JS SDK on previous visit.
    my $token_ref = $fb->get_user_token_by_cookie($cookie);
    # {
    #     "access_token" : "new_token_string_qwerty",
    #     "expires" : 5752 # named expires_in as of v2.3
    # };
  }
  else {
    return $c->redirect( $fb->auth_uri );
  }

=head3 C<< $fb->exchange_token($short_term_token) >>

Exchange short lived access token for long lived one. Short lived tokens are
ones that you obtain with C<get_user_token_by_code()>. Usually long lived
tokens live about 60 days while short lived ones live about 2 hours.

FYI: I<expires> or I<expires_in> is B<NOT> returned on some edge cases. The
detail and reproductive schenario should be found at
L<https://developers.facebook.com/bugs/597779113651383/>.

  my $extended_token_ref = $fb->exchange_token($token_ref->{access_token});
  my $access_token       = $extended_token_ref->{access_token};
  my $expires            = $extended_token_ref->{expires};
                           # named expires_in as of v2.3

If you loved the way old offline_access permission worked, and are looking for a
substitute you might want to try this.

=head3 C<< $fb->get($path, \%param, \@headers) >>

Alias to C<request()> that sends C<GET> request.

  my $path = 'zuck'; # should be ID or username
  my $user = $fb->get($path);
  #{
  #    name   => 'Mark Zuckerberg',

lib/Facebook/OpenGraph.pm  view on Meta::CPAN


Generates and returns the name of cookie that is set by JS SDK on client side
login. This value can be parsed as signed request and the parsed data structure
contains 'code' to exchange for acess token. See C<get_user_token_by_cookie()>
for detail.

=head3 C<< $fb->create_response($http_status_code, $http_status_message, \@response_headers, $response_content) >>

Creates and returns L<Facebook::OpenGraph::Response>. If you wish to use
customized response class, then override this method to return
MyApp::Better::Response.

=head3 C<< $fb->prep_param(\%param) >>

Handles sending parameters and format them in the way Graph API spec states.
This method is called in C<request()> so you don't usually use this method
directly.

=head3 C<< $fb->prep_fields_recursive(\@fields) >>

Handles fields parameter and format it in the way Graph API spec states.
The main purpose of this method is to deal with Field Expansion
(L<https://developers.facebook.com/docs/graph-api/using-graph-api/#fieldexpansion>).
This method is called in C<prep_param> which is called in C<request()> so you
don't usually use this method directly.

  # simple fields
  $fb->prep_fields_recursive([qw/name email albums/]); # name,email,albums

  # use field expansion
  $fb->prep_fields_recursive([
      'name',
      'email',
      +{
          albums => +{
              fields => [
                  'name',
                  +{
                      photos => +{
                          fields => [
                              'name',
                              'picture',
                              +{
                                  tags => +{
                                      limit => 2,
                                  },
                              }
                          ],
                          limit => 3,
                      }
                  }
              ],
              limit => 5,
          }
      }
  ]);
  # 'name,email,albums.fields(name,photos.fields(name,picture,tags.limit(2)).limit(3)).limit(5)'

=head3 C<< $fb->publish_action($action_type, \%param) >>

Alias to C<request()> that optimizes body content and endpoint to send C<POST>
request to publish Open Graph Action.

  my $res = $fb->publish_action('give', +{crap => 'https://sample.com/poop/'});
  #{id => 123456}

=head3 C<< $fb->create_test_users(\@settings) >>

  my $res = $fb->create_test_users([
      +{
          permissions => [qw/publish_actions/],
          locale      => 'en_US',
          installed   => 'true',
      },
      +{
          permissions => [qw/publish_actions email read_stream/],
          locale      => 'ja_JP',
          installed   => 'true',
      }
  ])
  #[
  #    +{
  #        id           => 123456789,
  #        access_token => '5678uiop',
  #        login_url    => 'https://www.facebook.com/........',
  #        email        => '.....@tfbnw.net',
  #        password     => '.......',
  #    },
  #    +{
  #        id           => 1234567890,
  #        access_token => '5678uiopasadfasdfa',
  #        login_url    => 'https://www.facebook.com/........',
  #        email        => '.....@tfbnw.net',
  #        password     => '.......',
  #    },
  #];

Alias to C<request()> that optimizes to create test users for your application.

=head3 C<< $fb->publish_staging_resource($file_path) >>

Alias to C<request()> that optimizes body content to send C<POST> request to upload image to Object API's staging environment.

  my $fb = Facebook::OpenGraph->new(+{
      access_token => $USER_ACCESS_TOKEN,
  });
  my $res = $fb->publish_staging_resource('/path/to/file');
  #{
  #  uri => 'fbstaging://graph.facebook.com/staging_resources/MDExMzc3MDU0MDg1ODQ3OTY2OjE5MDU4NTM1MzQ=',
  #};

=head3 C<< $fb->check_object($object_id_or_url) >>

Alias to C<request()> that sends C<POST> request to Facebook Debugger to
check/update object.

  $fb->check_object('https://sample.com/object/');
  $fb->check_object($object_id);

=head1 AUTHOR



( run in 1.111 second using v1.01-cache-2.11-cpan-e1769b4cff6 )