-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathOpenGraph.pm
1421 lines (1097 loc) · 45.9 KB
/
OpenGraph.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Facebook::OpenGraph;
use strict;
use warnings;
use 5.008001;
use Facebook::OpenGraph::Response;
use HTTP::Request::Common;
use URI;
use Furl::HTTP;
use Data::Recursive::Encode;
use JSON 2 ();
use Carp qw(croak);
use Digest::SHA qw(hmac_sha256 hmac_sha256_hex);
use MIME::Base64::URLSafe qw(urlsafe_b64decode);
use Scalar::Util qw(blessed);
our $VERSION = '1.31';
sub new {
my $class = shift;
my $args = shift || +{};
return bless +{
app_id => $args->{app_id},
secret => $args->{secret},
namespace => $args->{namespace},
access_token => $args->{access_token},
redirect_uri => $args->{redirect_uri},
batch_limit => $args->{batch_limit} || 50,
is_beta => $args->{is_beta} || 0,
json => $args->{json} || JSON->new->utf8,
use_appsecret_proof => $args->{use_appsecret_proof} || 0,
use_post_method => $args->{use_post_method} || 0,
version => $args->{version} || undef,
ua => $args->{ua} || Furl::HTTP->new(
capture_request => 1,
agent => __PACKAGE__ . '/' . $VERSION,
),
}, $class;
}
# accessors
sub app_id { shift->{app_id} }
sub secret { shift->{secret} }
sub ua { shift->{ua} }
sub namespace { shift->{namespace} }
sub access_token { shift->{access_token} }
sub redirect_uri { shift->{redirect_uri} }
sub batch_limit { shift->{batch_limit} }
sub is_beta { shift->{is_beta} }
sub json { shift->{json} }
sub use_appsecret_proof { shift->{use_appsecret_proof} }
sub use_post_method { shift->{use_post_method} }
sub version { shift->{version} }
sub uri {
my $self = shift;
my $base = $self->is_beta ? 'https://graph.beta.facebook.com/'
: 'https://graph.facebook.com/'
;
return $self->_uri($base, @_);
}
sub video_uri {
my $self = shift;
my $base = $self->is_beta ? 'https://graph-video.beta.facebook.com/'
: 'https://graph-video.facebook.com/'
;
return $self->_uri($base, @_);
}
sub site_uri {
my $self = shift;
my $base = $self->is_beta ? 'https://www.beta.facebook.com/'
: 'https://www.facebook.com/'
;
return $self->_uri($base, @_);
}
sub _uri {
my ($self, $base, $path, $param_ref) = @_;
my $uri = URI->new_abs($path || '/', $base);
$uri->query_form(+{
$uri->query_form, # when given $path is like /foo?bar=bazz
%{ $param_ref || +{} }, # additional query parameter
});
return $uri;
}
# Login for Games on Facebook > Checking Login Status > Parsing the Signed Request
# https://developers.facebook.com/docs/facebook-login/using-login-with-games
sub parse_signed_request {
my ($self, $signed_request) = @_;
croak 'signed_request is not given' unless $signed_request;
croak 'secret key must be set' unless $self->secret;
# "1. Split the signed request into two parts delineated by a '.' character
# (eg. 238fsdfsd.oijdoifjsidf899)"
my ($enc_sig, $payload) = split(m{ \. }xms, $signed_request);
# "2. Decode the first part - the encoded signature - from base64url"
my $sig = urlsafe_b64decode($enc_sig);
# "3. Decode the second part - the 'payload' - from base64url and then
# decode the resultant JSON object"
my $val = $self->json->decode(urlsafe_b64decode($payload));
# "It specifically uses HMAC-SHA256 encoding, which you can again use with
# most programming languages."
croak 'algorithm must be HMAC-SHA256'
unless uc( $val->{algorithm} ) eq 'HMAC-SHA256';
# "You can compare this encoded signature with an expected signature using
# the payload you received as well as the app secret which is known only to
# your and ensure that they match."
my $expected_sig = hmac_sha256($payload, $self->secret);
croak 'Signature does not match' unless $sig eq $expected_sig;
return $val;
}
# Detailed flow is described here.
# Manually Build a Login Flow > Logging people in > Invoking the login dialog
# https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/
#
# Parameters for login dialog are shown here.
# Login Dialog > Parameters
# https://developers.facebook.com/docs/reference/dialogs/oauth/
sub auth_uri {
my ($self, $param_ref) = @_;
$param_ref ||= +{};
croak 'redirect_uri and app_id must be set'
unless $self->redirect_uri && $self->app_id;
# "A comma separated list of permission names which you would like people
# to grant your app."
if (my $scope_ref = ref $param_ref->{scope}) {
croak 'scope must be string or array ref' unless $scope_ref eq 'ARRAY';
$param_ref->{scope} = join q{,}, @{ $param_ref->{scope} };
}
# "The URL to redirect to after a button is clicked or tapped in the
# dialog."
$param_ref->{redirect_uri} = $self->redirect_uri;
# "Your App ID. This is called client_id instead of app_id for this
# particular method in order to be compliant with the OAuth 2.0
# specification."
$param_ref->{client_id} = $self->app_id;
# "If you are using the URL redirect dialog implementation, then this will
# be a full page display, shown within Facebook.com. This display type is
# called page."
$param_ref->{display} ||= 'page';
# "Response data is included as URL parameters and contains code parameter
# (an encrypted string unique to each login request). This is the default
# behaviour if this parameter is not specified."
$param_ref->{response_type} ||= 'code';
my $uri = $self->site_uri('/dialog/oauth', $param_ref);
# Platform Versioning > Making Versioned Requests > Dialogs.
# https://developers.facebook.com/docs/apps/versions#dialogs
$uri->path( $self->gen_versioned_path($uri->path) );
return $uri->as_string;
}
sub set_access_token {
my ($self, $token) = @_;
$self->{access_token} = $token;
}
# Access Tokens > App Tokens
# https://developers.facebook.com/docs/facebook-login/access-tokens/#apptokens
sub get_app_token {
my $self = shift;
# Document does not mention what grant_type is all about or what values can
# be set, but RFC 6749 covers the basic idea of grant types and its Section
# 4.4 describes Client Credentials Grant.
# http://tools.ietf.org/html/rfc6749#section-4.4
return $self->_get_token(+{grant_type => 'client_credentials'});
}
# Manually Build a Login Flow > Confirming identity > Exchanging code for an access token
# https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
sub get_user_token_by_code {
my ($self, $code) = @_;
croak 'code is not given' unless $code;
croak 'redirect_uri must be set' unless $self->redirect_uri;
my $query_ref = +{
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 => $_,
}
} @$paths_ref;
return $self->batch(\@queries);
}
# Making Multiple API Requests > Making a simple batched request
# https://developers.facebook.com/docs/graph-api/making-multiple-requests
sub batch {
my $self = shift;
my $responses_ref = $self->batch_fast(@_);
# Devide response content and create response objects that correspond to
# each request
my @data = ();
for my $r (@$responses_ref) {
for my $res_ref (@$r) {
my $response = $self->create_response(
$res_ref->{code},
$res_ref->{message},
[ map { $_->{name} => $_->{value} } @{ $res_ref->{headers} } ],
$res_ref->{body},
);
croak $response->error_string unless $response->is_success;
push @data, $response->as_hashref;
}
}
return \@data;
}
# doesn't create F::OG::Response object for each response
sub batch_fast {
my $self = shift;
my $batch = shift;
# Other than HTTP header, you need to set access_token as top level
# parameter. You can specify individual token for each request so you can
# act as several other users and pages.
croak 'Top level access_token must be set' unless $self->access_token;
# "We currently limit the number of requests which can be in a batch to 50"
my @responses = ();
while(my @queries = splice @$batch, 0, $self->batch_limit) {
for my $q (@queries) {
if ($q->{method} eq 'POST' && $q->{body}) {
my $body_ref = $self->prep_param($q->{body});
my $uri = URI->new;
$uri->query_form(%$body_ref);
$q->{body} = $uri->query;
}
}
my @req = (
'/',
+{
access_token => $self->access_token,
batch => $self->json->encode(\@queries),
},
@_,
);
push @responses, $self->post(@req);
}
return \@responses;
}
# Facebook Query Language (FQL) Overview
# https://developers.facebook.com/docs/technical-guides/fql/
sub fql {
my $self = shift;
my $query = shift;
return $self->get('/fql', +{q => $query}, @_);
}
# Facebook Query Language (FQL) Overview: Multi-query
# https://developers.facebook.com/docs/technical-guides/fql/#multi
sub bulk_fql {
my $self = shift;
my $batch = shift;
return $self->fql($self->json->encode($batch), @_);
}
sub request {
my ($self, $method, $uri, $param_ref, $headers) = @_;
$method = uc $method;
$uri = $self->uri($uri) unless blessed($uri) && $uri->isa('URI');
$uri->path( $self->gen_versioned_path($uri->path) );
$param_ref = $self->prep_param(+{
$uri->query_form(+{}),
%{$param_ref || +{}},
});
# Securing Graph API Requests > Verifying Graph API Calls with appsecret_proof
# https://developers.facebook.com/docs/graph-api/securing-requests/
if ($self->use_appsecret_proof) {
$param_ref->{appsecret_proof} = $self->gen_appsecret_proof;
}
# Use POST as default HTTP method and add method=(POST|GET|DELETE) to query
# parameter. Document only says we can send HTTP DELETE method or, instead,
# HTTP POST method with ?method=delete to delete object. It does not say
# POST with method=(get|post) parameter works, but PHP SDK always sends POST
# with method parameter so... I just give you this option.
# Check PHP SDK's base_facebook.php for detail.
if ($self->{use_post_method}) {
$param_ref->{method} = $method;
$method = 'POST';
}
$headers ||= [];
# Document says we can pass access_token as a part of query parameter,
# but it actually supports Authorization header to be compliant with the
# OAuth 2.0 spec.
# http://tools.ietf.org/html/rfc6749#section-7
if ($self->access_token) {
push @$headers, (
'Authorization',
sprintf('OAuth %s', $self->access_token),
);
}
my $content = q{};
if ($method eq 'POST') {
if ($param_ref->{source}
|| $param_ref->{file}
|| $param_ref->{upload_phase}
|| $param_ref->{captions_file}) {
# post image, video or caption file
# https://developers.facebook.com/docs/reference/api/video/
# When posting a video, use graph-video.facebook.com .
# base_facebook.php has an equivalent part in isVideoPost().
# ($method == 'POST' && preg_match("/^(\/)(.+)(\/)(videos)$/", $path))
# For other actions, use graph.facebook.com/VIDEO_ID/CONNECTION_TYPE
if ($uri->path =~ m{\A /.+/videos \z}xms) {
$uri->host($self->video_uri->host);
}
# Content-Type should be multipart/form-data
# https://developers.facebook.com/docs/reference/api/publishing/
push @$headers, (Content_Type => 'form-data');
# Furl::HTTP document says we can use multipart/form-data with
# HTTP::Request::Common.
my $req = POST $uri, @$headers, Content => [%$param_ref];
$content = $req->content;
my $req_header = $req->headers;
$headers = +[
map {
my $k = $_;
map { ( $k => $_ ) } $req_header->header($k);
} $req_header->header_field_names
];
}
else {
# Post simple parameters such as message, link, description, etc...
# Content-Type: application/x-www-form-urlencoded will be set in
# Furl::HTTP, and $content will be treated properly.
$content = $param_ref;
}
}
else {
$uri->query_form($param_ref);
}
my ($res_minor_version, @res_elms) = $self->ua->request(
method => $method,
url => $uri,
headers => $headers,
content => $content,
);
my $res = $self->create_response(@res_elms);
# return F::OG::Response object on success
return $res if $res->is_success;
# Use later version of Furl::HTTP to utilize req_headers and req_content.
# This Should be helpful when debugging.
my $msg = $res->error_string;
if ($res->req_headers) {
$msg .= "\n" . $res->req_headers . $res->req_content;
}
croak $msg;
}
# Securing Graph API Requests > Verifying Graph API Calls with appsecret_proof > Generating the proof
# https://developers.facebook.com/docs/graph-api/securing-requests/
sub gen_appsecret_proof {
my $self = shift;
croak 'app secret must be set' unless $self->secret;
croak 'access_token must be set' unless $self->access_token;
return hmac_sha256_hex($self->access_token, $self->secret);
}
# Platform Versioning > Making Versioned Requests
# https://developers.facebook.com/docs/apps/versions
sub gen_versioned_path {
my ($self, $path) = @_;
$path = '/' unless $path;
if ($self->version && $path !~ m{\A /v(?:\d+)\.(?:\d+)/ }x) {
# If default platform version is set on initialisation
# and given path doesn't contain version,
# then prepend the default version.
$path = sprintf('/%s%s', $self->version, $path);
}
return $path;
}
sub js_cookie_name {
my $self = shift;
croak 'app_id must be set' unless $self->app_id;
# Cookie is set by JS SDK with a name of fbsr_{app_id}. Official document
# is not provided for more than 3 yaers so I quote from PHP SDK's code.
# "Constructs and returns the name of the cookie that potentially houses
# the signed request for the app user. The cookie is not set by the
# BaseFacebook class, but it may be set by the JavaScript SDK."
# The cookie value can be parsed as signed request and it contains 'code'
# to exchange for access toekn.
return sprintf('fbsr_%d', $self->app_id);
}
sub create_response {
my $self = shift;
return Facebook::OpenGraph::Response->new(+{
json => $self->json,
map {
$_ => shift
} qw/code message headers content req_headers req_content/,
});
}
sub prep_param {
my ($self, $param_ref) = @_;
$param_ref = Data::Recursive::Encode->encode_utf8($param_ref || +{});
# /?ids=4,http://facebook-docs.oklahome.net
if (my $ids = $param_ref->{ids}) {
$param_ref->{ids} = ref $ids ? join q{,}, @$ids : $ids;
}
# mostly for /APP_ID/accounts/test-users
if (my $perms = $param_ref->{permissions}) {
$param_ref->{permissions} = ref $perms ? join q{,}, @$perms : $perms;
}
# Source, file, video_file_chunk and captions_file parameter contains file path.
# It must be an array ref to work with HTTP::Request::Common.
for my $file (qw/source file video_file_chunk captions_file/) {
next unless my $path = $param_ref->{$file};
$param_ref->{$file} = ref $path ? $path : [$path];
}
# use Field Expansion
if (my $field_ref = $param_ref->{fields}) {
$param_ref->{fields} = $self->prep_fields_recursive($field_ref);
}
# Using Objects: Using the Object API
# https://developers.facebook.com/docs/opengraph/using-objects/#objectapi
my $object = $param_ref->{object};
if ($object && ref $object eq 'HASH') {
$param_ref->{object} = $self->json->encode($object);
}
return $param_ref;
}
# Using the Graph API: Reading > Choosing Fields > Making Nested Requests
# https://developers.facebook.com/docs/graph-api/using-graph-api/
sub prep_fields_recursive {
my ($self, $val) = @_;
my $ref = ref $val;
if (!$ref) {
return $val;
}
elsif ($ref eq 'ARRAY') {
return join q{,}, map { $self->prep_fields_recursive($_) } @$val;
}
elsif ($ref eq 'HASH') {
my @strs = ();
while (my ($k, $v) = each %$val) {
my $r = ref $v;
my $pattern = $r && $r eq 'HASH' ? '%s.%s' : '%s(%s)';
push @strs, sprintf($pattern, $k, $self->prep_fields_recursive($v));
}
return join q{.}, @strs;
}
}
# Using Actions > Publishing Actions
# https://developers.facebook.com/docs/opengraph/using-actions/#publish
sub publish_action {
my $self = shift;
my $action = shift;
croak 'namespace is not set' unless $self->namespace;
return $self->post(sprintf('/me/%s:%s', $self->namespace, $action), @_);
}
# Using Objects > Using the Object API > Images with the Object API
# https://developers.facebook.com/docs/opengraph/using-objects/
sub publish_staging_resource {
my $self = shift;
my $file = shift;
return $self->post('/me/staging_resources', +{file => $file}, @_);
}
# Test Users: Creating
# https://developers.facebook.com/docs/test_users/
sub create_test_users {
my $self = shift;
my $settings_ref = shift;
if (ref $settings_ref ne 'ARRAY') {
$settings_ref = [$settings_ref];
}
my @settings = ();
my $relative_url = sprintf('/%s/accounts/test-users', $self->app_id);
for my $setting (@$settings_ref) {
push @settings, +{
method => 'POST',
relative_url => $relative_url,
body => $setting,
};
}
return $self->batch(\@settings);
}
# Using Objects > Using Self-Hosted Objects > Updating Objects
# https://developers.facebook.com/docs/opengraph/using-objects/
sub check_object {
my ($self, $target) = @_;
my $param_ref = +{
id => $target, # $target is object url or open graph object id
scrape => 'true',
};
return $self->post(q{}, $param_ref);
}
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
#Content-Type: application/x-www-form-urlencoded
#Content-Length: 27
#Host: graph.facebook.com
#
#message=Hello%2C%20world%21
=item * namespace
Facebook application namespace. This is used when you publish Open Graph Action
via C<publish_action()>.
=item * access_token
Access token for user, application or Facebook Page.
=item * redirect_uri
The URL to be used for authorization. User will be redirected to this URL after
login dialog. Detail should be found at
L<https://developers.facebook.com/docs/reference/dialogs/oauth/>.
You must keep in mind that "The URL you specify must be a URL with the same
base domain specified in your app's settings, a Canvas URL of the form
https://apps.facebook.com/YOUR_APP_NAMESPACE or a Page Tab URL of the form
https://www.facebook.com/PAGE_USERNAME/app_YOUR_APP_ID"
=item * batch_limit
The maximum number of queries that can be set within a single batch request.
If the number of given queries exceeds this, then queries are divided into
multiple batch requests, and responses are combined so it seems just like a
single request.
Default value is 50 as API documentation says. Official documentation is
located at L<https://developers.facebook.com/docs/graph-api/making-multiple-requests/>
You must be aware that "each call within the batch is counted separately for
the purposes of calculating API call limits and resource limits."
See L<https://developers.facebook.com/docs/reference/ads-api/api-rate-limiting/>.
=item * is_beta
Weather to use beta tier. See the official documentation for details.
L<https://developers.facebook.com/support/beta-tier/>.
=item * json
JSON object that handles request parameters and API response. Default is
equivalent to JSON->new->utf8.
=item * use_appsecret_proof
Whether to use appsecret_proof parameter or not. Default is 0.
Long-desired official document is now provided at
L<https://developers.facebook.com/docs/graph-api/securing-requests/>
You must specify access_token and application secret to utilize this.
=back
my $fb = Facebook::OpenGraph->new(+{
app_id => 123456,
secret => 'FooBarBuzz',
ua => Furl::HTTP->new(capture_request => 1),
namespace => 'fb-app-namespace', # for Open Graph Action
access_token => '', # will be appended to request header in request()
redirect_uri => 'https://sample.com/auth_callback', # for OAuth
batch_limit => 50,
json => JSON->new->utf8,
is_beta => 0,
use_appsecret_proof => 1,
use_post_method => 0,
version => undef,
})
=head2 Instance Methods
=head3 C<< $fb->app_id >>
Accessor method that returns application id.
=head3 C<< $fb->secret >>
Accessor method that returns application secret.
=head3 C<< $fb->ua >>
Accessor method that returns L<Furl::HTTP> object.
=head3 C<< $fb->namespace >>
Accessor method that returns application namespace.
=head3 C<< $fb->access_token >>
Accessor method that returns access token.
=head3 C<< $fb->redirect_uri >>
Accessor method that returns URL that is used for user authorization.
=head3 C<< $fb->batch_limit >>
Accessor method that returns the maximum number of queries that can be set
within a single batch request. If the number of given queries exceeds this,
then queries are divided into multiple batch requests, and responses are
combined so it just seems like a single batch request. Default value is 50 as
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