Debian Codegraph @

examples/facebook-canvas-json

raw
1 #!/usr/bin/perl
2 # Copyright David Leadbeater 2007 <http://dgl.cx>.
3 # Licensed under the same terms as Perl itself.
4
5 # A simple example of using WWW::Facebook::API within a facebook canvas.
6 # You will need to change the api_key, secret and app_path below to match your
7 # account. To get an api_key and secret, go to
8 # http://www.facebook.com/developers/editapp.php?new, choose "Use FBML" and
9 # enter a unique name for the canvas which you should put into app_path.
10
11 use strict;
12 use CGI;
13 use WWW::Facebook::API;
14 use Data::Dumper;
15
16 my $facebook = WWW::Facebook::API->new(
17 api_key => "change-me",
18 secret => "change-me",
19 app_path => "change-me",
20 parse => 1,
21 );
22
23 our %action_map = (
24 '' => \&index_page,
25 info => \&info_page,
26 );
27
28 sub main {
29
30 # Should also work with FastCGI (via CGI::Fast).
31 my $q = new CGI;
32 print $q->header;
33
34 redirect("Must be called in facebook canvas")
35 unless $facebook->canvas->in_fb_canvas($q);
36
37 my $params = $facebook->canvas->validate_sig($q);
38 if ( $params->{user} ) {
39
40 # Canvas takes care of setting up a session for us, no need to call the
41 # auth methods.
42 $facebook->session_key( $params->{session_key} );
43 }
44 else {
45
46 # User hasn't added app (could reject/display info/whatever)
47 # (Or handle later when a user is needed).
48 }
49
50 my ( $action, $param ) = ( $q->path_info =~ m!^/(\w+)/?(.*)! );
51 if ( my $s = $action_map{$action} ) {
52 $s->( $param, $params );
53 }
54 else {
55 div_error("Action unknown");
56 }
57
58 # Clear session_key (for if running under FastCGI).
59 $facebook->session_key(undef);
60 }
61
62 sub index_page {
63 my ( $param, $params ) = @_;
64
65 print "<fb:header/><div style='padding: 20px'>";
66
67 # You could do this easier by using <fb:name>, just showing some API stuff here.
68 my $name = "You";
69 if ($params) {
70 my $res =
71 $facebook->fql->query( query =>
72 "SELECT first_name FROM user WHERE uid=$params->{user}" );
73 $name = "Hi $res->[0]->{first_name}, you";
74 }
75 print "$name ", ( $params ? "have" : "have't" ),
76 " added this application. Some <a href='info'>info</a>.";
77 if ( !$params ) {
78 print "<a href='", $facebook->get_add_url,
79 "'>Add this application</a>.";
80 }
81 print "</div>";
82 }
83
84 sub info_page {
85 my ( $param, $params ) = @_;
86
87 print "<fb:header/><div style='padding: 20px'><pre>";
88 print Dumper($params);
89 print "</pre></div>";
90 }
91
92 sub redirect {
93 div_error("Please go <a href='"
94 . $facebook->get_app_url
95 . "'>to facebook</a>" );
96 exit;
97 }
98
99 sub div_error {
100 print "<div style='padding: 20px'>", join( "", @_ ), "</div>";
101 }
102
103 main();