Você está na página 1de 23

Facebook API Integration

By Michelle Sollicito
ECSTeam
Atlanta, GA
Social networking is increasingly becoming a key component to developing deep relationships with
customers. Social media is a powerful means of discovering trends, gaining feedback from customers,
interacting with customers and their friends and marketing to customers in various ways.
http://www.businessnewsdaily.com/8!"social"media"#$#.html
%ow integrating such social media data with internal systems is becoming increasingly important &
especially with '() systems and data mining/analytics systems, but also with product catalogs and
shopping carts to provide a more personali*ed e+perience for users based upon their social media
preferences.
http://data"informed.com/,"approaches"for"integrating"social"media"data"with"enterprise"systems/
(ecogni*ing this, -acebook has provided an open source set of apis providing access to -acebook data &
the .raph /01, 'hat /01, 'redits /01 and /ds /01. 2he .raph /01 is the api most useful for data integration
as it provides access to information about people, their posts, their comments and their likes. 2his paper
aims to e+plain how to use the -acebook .raph api effectively to integrate such data into internal business
systems.
1. Introduction
This paper will first introduce the Facebook Graph API and the different tools that are
available when using it. It will then illustrate how to set up authorization and access to
the API and the different types of authorization and access available to programs.
Then a real data e!traction" e!ample will be provided of how to retrieve posts from a
Facebook group and place that data in a database table. An e!ample of how to
automatically post to a Facebook group will also be provided.
2. Trends
Trend towards using social media to deepen relationships. People are buying via social
media# are getting recommendations via social media# are reading feedback on products
on social media# are learning about alternatives on social media# are trying to self service
or get support on social media.
$ompanies are realizing the value of the data and need to integrate it into their internal
systems# especially their $%& systems.
Example: Utilities and social media
'tilities want to educate their customers about the products and services they offer. They
want to be $orporate $itizens# helping customers with their electrical appliances# helping
them during financial difficulties to keep their electric or gas on# helping them to budget
effectively# helping them to reduce their bills# but most importantly they want to help
customers when an outage happens ( help them to )uickly report outages# help them to
find out how long an outage might last and to cope without the electricity*gas for the
+hopefully short, period of time they are without it.
-uring the snowstorms in Atlanta# utility customers shared information on the
.nowed/utAtlanta Facebook group about how prepared +or otherwise, they believed
their power company to be. They uploaded photos such as this one0
1. 'sing Facebook to communicate about companies
They shared information about how to prepare for power outages0
2. 'sing Facebook to help others self support
..and they watched the total of outages growing as the storm got worse over time..
3. 'sing Facebook to evaluate company performance
As a result of the huge Facebook activity during the snowstorms# the utility companies
recognized the need to integrate Facebook data into their internal systems in order to
effectively monitor their relationships with their customers.
3. Problem
Integrating data from Facebook into internal systems is made easier because Facebook
made available the Facebook Graph API but it does not solve the whole problem.
.ecurity is one of the biggest issues involved in Facebook data integration. In order to
obtain the activity data from Facebook# one of two types of security gateways must be
used. 4ither the Facebook user must allow" an app to link their Facebook profile to the
Internal data profile +and allow that app to e!tract certain kinds of data from their
profile,# or the Facebook user must post to a Facebook group or page owned by the
company in )uestion. The app itself must also have been set up with an authentication
key that is appropriate to the conte!t in which the app will be used.
Facebook solves this problem using /Auth# a popular open authorization protocol which
allows applications to access each other5s data. For more information about /Auth
+version 2 is the current version, see http0**tutorials.6enkov.com*oauth2*inde!.html
To see how the process of authorizing an app to access Facebook data looks to the user#
see an e!ample here http0**www.wikihow.com*Authorize7an7App7to7$onnect7with7
Facebook Take note in particular of step 8 where the user is informed of the type of
information being authorized +in this case# your public profile# friend list and email
address,0
9. Prompting the user for permission to access their data
If a user voluntarily 6oins a company Facebook group or Facebook page and posts
information# it is a little easier to gain access to that data because by 6oining the group or
page# the user has in effect provided authorization to the company to own that data.
In this case# the application needs an app id and an authorization key in order to re)uest
access to the Facebook page or Facebook group +again different types of data may be
re)uested, but once the application has been granted access it can read or post to that
page*group depending upon the re)uested access type.
Authentication is also an issue with the Facebook api in the sense that it can be difficult
to associate a Facebook profile with an e!isting customer in the company database. In
cases where the user e!plicitly allows the app to link the Facebook profile to the internal
customer account# this problem is resolved. :owever# in cases where the Facebook user
is 6ust one of the users in a Facebook group or page# the usual way to link the user5s
profile to a customer record in the database is via the email address associated with the
Facebook account. /f course# if the primary email address on the Facebook account does
not coincide with the email used to identify the customer in the internal database# it is
possible that social media data could be accumulated under the wrong different dummy"
customer account. :owever# the social media data will still be useful# and it is possible to
use other mechanisms to flush out these disparities.
4. Getting Started
4.1 Creating a Facebook App
To create a Facebook app# first login to Facebook and go to your home page. Then type
into the url0 https0**developers.facebook.com*
$lick on Apps" and then select $reate a ;ew App" from the submenu.
<. Apps menu on -eveloper page
4nter a -isplay ;ame +this is the name that will be listed for your app under Apps" on
users5 Facebook pages so choose carefully=
$hoose a ;amespace ( this might be your company name for e!ample ( but be careful to
have no capital letters in the ;amespace due to naming conventions.
If it is not a test version of another app# leave the ;o highlighted. Then select a category
for your app. In this case# Apps for Pages" is the correct category.
>. $reating an app
As soon as you create your app# your app is assigned an app id and a secret# see below.
These are very important and you should take note of them now as you need them later.
?ou can see the App .ecret if you click on .how +you may have to enter your Facebook
password in order to do that,.
Take a good look around the -ashboard while you are here as it can be very useful later
as your apps grow and develop# and gain more of an audience.
4.2. Granting App ermi!!ion!
@. The app dashboard
The .tatus A %eview section# for e!ample# is very important because it is where you
re)uest permission for your app to collect different kinds of data.
For e!ample# if you want to post to a group or page using the app# you will need
manageBpages" permission in order to get an access token +security key, to allow you to
access the page*group# and you will need publishBactions" permission to allow your app
to actually post posts to the group or page.
For more information about permissions your app might need and why# see this article
https0**developers.facebook.com*docs*facebook7login*permissions*v2.C
%e)uest the permissions you need here now before moving on.
D. Granting permissions to an app
". Acce!! Token!
The ne!t thing you need to do is to generate a security access token. In order to do this# it
is important to first understand how access tokens work.
".1 Type! o# Facebook Acce!! Token!
Firstly# it is important to know a little of the basics of /Auth 2.C which is the protocol
used by Facebook for security purposes.
The general principle of /Auth is that a http get" call is made to an /Auth uri indicating
which permissions are re)uired in the scope" parameter# and the app re)uesting the
permissions is identified using the clientBid" parameter. A redirectBuri" parameter
indicates which url to redirect to on successful grant of the permissions identified.
There are four types of access token available to developers at this time via the /Auth
mechanism.
The $!er Acce!! token is used to obtain information about the user by prompting the
user with a dialog and asking the user for permission to access their data# as illustrated in
illustration 9.# above. This kind of token can only be generated with permission from the
user and re)uires user interaction.
The App Acce!! token is used to modify the settings for an app# and re)uires a server to
server call using a pre7agreed secret.
The age Acce!! token is used to read# write and modify information on or related to a
Facebook page. It can be a little confusing# because you cannot obtain a age Acce!!
token until you have first obtained a $!er Acce!! token for the user who owns that page#
and have been granted the manageBpages" permission for that user. ;ote that for now#
age Acce!! tokens can also be used to manage groups# though it is possible that will
change in future versions of the Facebook API.
The Client Token +AppId, is a uni)ue identifier used to identify a particular app or
application. It is embedded into the app or application and is used to access app7level
APIs. ?ou can see the AppId on your dashboard.
In addition# there are two types of $!er Acce!! token! ( short7term and long7term tokens.
.hort7lived $!er Acce!! token! typically e!pire after a couple of hours and are generated
via web logins# similarly to in illustration 9.# above. Eong7term $!er Acce!! token! are
obtained using a short7lived $!er Acce!! token, an app id and the app secret combined#
and are used time and time again by the same application over a longer period of time.
Eong7term $!er Acce!! token! typically e!pire after FFFF
A typical generic get call that will return a short7lived 'ser Access token looks something
like this# and m%!t always be made server side for security reasons +anyone who can see
this call containing your app id# app secret and a short lived token# could potentially use
the long7term token generated to do anything they wanted to to your Facebook page,00
GET /oauth/access_token?
client_id={app-id}
&client_secret={app-secret}
&grant_type=client_credentials
It is possible to avoid generating and using app access tokens. ?ou can send in the
appBid and the appBsecret instead# see below0
http ://graph.ace!ook.co"/endpoint?key=#alue&access_token=app_id$
app_secret
A typical generic get call that will return a long7term $!er Acce!! token looks something
like this# and m%!t always be made server side for security reasons +anyone who can see
this call containing your app id# app secret and a short lived token# could potentially use
the long7term token generated to do anything they wanted to to your Facebook page,0
GET /oauth/access_token?
grant_type=!_e%change_token&
client_id={app-id}&
client_secret={app-secret}&
!_e%change_token={short-li#ed-token}
".2 &A%th 'ith Facebook
A typical direct Facebook /Auth call looks like this +in this case to get the access token
for an application with the manageBpages" permission,0
https0**www.facebook.com*dialog*oauthG
clientBidHAPPEI$ATI/;BI-AredirectBuriHhttps0**www.facebook.com*connect*loginBsu
ccess.htmlAresponseBtypeHcodeItokenAdisplayHpopupAscopeHmanageBpages
If you want to capture the result +access token, programmatically# you can add
AtypeHuserBagent or AtypeHwebBserver to your /Auth call to receive the result as a
parameter in the url of the redirect page either like this0
http0**yourredirecturiJcodeHKaccesstokenL
/r like this0
http0**yourredirecturiAcodeHKaccesstokenL
A typical /Auth re)uest in $J*.;et +using the Facebook .-M for .;et# available here
http0**facebooksdk.net* or via ;uget, for reading the stream" from a user5s groups looks
like this0
string AppID = "[put your appid here]";
string AppSecret = "[put your app secret here]";
// using Facebook SDK for !"# to read fro$ groups
%ar fb = ne& FacebookFacebook'(ient)*;
dyna$ic resu(t = fb+et)"oauth/access,token"- ne&
.
c(ient,id = AppID-
c(ient,secret = AppSecret-
grant,type = "c(ient,credentia(s"-
scope = "user,groups-read,strea$"-
redirect,uri = redirect/r(
0*;
app,token = resu(taccess,token;
This is an e!ample of re)uesting permissions to post to a user5s groups0
// using Facebook SDK for !"# to post to groups
%ar fb = ne& FacebookFacebook'(ient)*;
dyna$ic resu(t = fb+et)"oauth/access,token"- ne&
.
c(ient,id = AppID-
c(ient,secret = AppSecret-
grant,type = "c(ient,credentia(s"-
scope = "user,groups-pub(ish,strea$"-
redirect,uri = redirect/r(
0*;
app,token = resu(taccess,token;

In this case the app token returned provides the app with the permissions to read all the
user groups associated with that app.
P:P and Python code for using /Auth 2.C is provided here0
http0**hayageek.com*facebook7dialog7oauth*
To find out more about access tokens see this page0
https0**developers.facebook.com*docs*facebook7login*access7tokens
For more detail about how /Auth 2.C works in Facebook see
https0**developers.facebook.com*docs*reference*dialogs*oauth
For a more general introduction to /Auth# as stated before# a great tutorial to provide a
basic understanding is this one0 http0**tutorials.6enkov.com*oauth2*inde!.html
It should be noted many respected web services providers including twitter# ?ahoo= and
Google all use /Auth 2.C as their authentication protocol.
Ne aware that even long7term access tokens eventually e!pire and this article e!plains
how to handle those situations0 http0**facebooksdk.net*docs*web*handling7e!pired7access7
tokens*
(. Fin)ing *o%r age +) or Gro%p +)
/nce you have the access token# you are going to need to know the id of the resource for
which you want to find information ( in this case it will be the Page Id or the Group Id.
If you do not know your page id for your Facebook page or group# the best way to find it
is to do the following0
1, Go to the url of your Facebook page. For e!ample# it might be something like
this0
https0**www.facebook.com*groups*snowedoutatlanta*
or it might be something like this0
https0**www.facebook.com*groups*23><82123131@9>*
or a page may have a url like this0
https0**www.facebook.com*T!tToAd
2, From the Page or Group main page# go to the %eport Group" option under the
Gear" icon see below
:over over the %eport Group" option and right click your mouse and select $opy link
address". Paste the contents of your clipboard into notepad or similar. ?ou should get
something that looks like this0 https0**www.facebook.com*a6a!*report.phpG
contentBtypeH1AcidH38@D38>@3>8<3D2
The cid parameter contains your Page Id. .o# in this case# the Page Id is
38@D38>@3>8<3D2.
;ote that there are many other ways to get your Page Id but this one consistently works
+others work in some circumstances but not in others,.
,. Te!ting $-.!
In order to determine the urls needed within your code it is a good idea to first get
ac)uainted with a wonderful tool provided by Facebook to help with generating calls to
the Graph API. It is called the Graph API 4!plorer" and makes working with the Graph
API a great deal easier.
To see it in action go to this url0
https0**developers.facebook.com*tools*e!plorer
?ou should see something that looks like this0
;ote that it automatically creates a short7term access token to be used during the session
at the top of the page.
Also note that it works in two modes0 Graph API and FOE Ouery. -uring this tutorial we
will mainly use the Graph API because FOE will soon be retired*discontinued# but the
FOE Ouery is*was an e!tremely powerful .OE7like tool for )uerying Facebook ob6ects
and was very useful for )uickly finding information so you may want to learn something
about it# while bearing in mind that it will not be around forever0 If you do# this is a great
resource0
https0**developers.facebook.com*docs*reference*f)l*
'sing the Graph API mode# it is possible to test out urls and )ueries and see the kinds of
results obtained. Ny default# the me" )uery showing the currently logged in Facebook
user5s id and name is provided.
$hange the )uery from0
*meGfieldsHid#name
to0
*Kpage id for your Facebook pageL*feed
to see the news feed for your Facebook page or Facebook group.
For e!ample# my .nowed/utAtlanta group feed )uery would look like this0
*38@D38>@3>8<3D2*feed
.ee below0
?ou will see that the main data returned is a group of Post" ob6ects. Post ob6ects have
properties such as message"# picture"# link"# name"# caption" and description".
For full details of the Post ob6ect# see this link
https0**developers.facebook.com*docs*graph7api*reference*v2.C*post
For full details of the feed call# see this link0
https0**developers.facebook.com*docs*graph7api*reference*v2.C*page*feed
For a general introduction to using the Graph API 4!plorer I recommend this link#
although it is a little out of date it is still a very good overview.
https0**developers.facebook.com*blog*post*<1@*
The Graph API 4!plorer is a great way to try out different )ueries to the Graph API
)uickly and easily without having to write code. /nce you are confident you have the
correct '%Es*)ueries# you can then go on to write your code in your chosen
implementation language.
/. 0riting the Co)e
.o now your app has permissions and a security access token# and you have an idea of the
)ueries you want to write to get the information you need from Facebook# it is time to
start writing code against the Facebook API. It is possible to write code using a multitude
of programming languages. For illustration purposes# here we will produce some code in
$J * A.P.;et and some code in 6avascript using F:%.
:ere is an e!ample 6avascript function to retrieve the username field for a Facebook user#
given the userid". The Facebook userid is the number that looks something like this0
1CCCCC998DD>D>9
+in fact if you call this function with the above userid# the username returned is
msollicito" +my facebook username,.
;ote that this code uses the user" Facebook API ob6ect referenced here0
https0**developers.facebook.com*docs*graph7api*reference*v2.C*user
function get'serId+userid, P
var urlHQhttps0**graph.facebook.com*Q I userid I QGfieldsHusernameQR
var !hr H new F&E:ttp%e)uest+,R
!hr.open+QG4TQ# url# false,R
!hr.onload H function +e, P
if +!hr.ready.tate HHH 9, P
if +!hr.status HHH 2CC, P
struseridH!hr.responseTe!tR
S
else P
struseridH!hr.statusTe!tR
S
S
SR
!hr.onerror H function +e, P
struseridH!hr.statusTe!tR
SR
!hr.send+null,R
S
?ou can use 6avascript to retrieve posts from a group or page feed using the following url0
var graph'%E H Qhttps0**graph.facebook.com*Kput your group or page id hereL*feedGQ I
QcallbackHdisplayPostsAQ I
QdateBformatH'AQ I
QlimitH<CCCCCCAaccessBtokenHKput your access token hereLQR
If you run the following code0
** $all the Graph API here
function getPosts+, P
var posts H document.create4lement+QpostsQ,R
posts.src H graph'%ER
document.body.append$hild+posts,R
S
.. when the element posts" is added to the page# that invokes the call to the graph'%E
which in turn retrieves some posts as data and sends the data as an ob6ect +post-ata, to
the callback displayPosts" referred to in the graph'%E. The posts retrieved are# of
course# posts from the group +or page, identified by the id placed into the url between
https0**graph.facebook.com* and *feedG"
displayPosts" takes the post data# and if there are some posts in that data# it creates a
new graph'%E with a new parameter ( until ( indicating the time until which to retrieve
posts# using the createdBtime of the last post previously retrieved. This new url will be
used in the ne!t fetch of the post data.
Then it processes the data that came back during this fetch of the post data# getting the
userid first +using the function we talked about earlier ( get'serId, and then processing
the Facebook API Post" ob6ect ( in this case# we are displaying updatedBtime#
createdBtime and the message# but we could access any of the fields" of the Facebook
API Post ob6ect here# see https0**developers.facebook.com*docs*graph7
api*reference*v2.C*post for details.
**display posts using Tavascript
function displayPosts+post-ata, P
if +post-ata.data.length U2, P
document.get4lementNyId+Qdiv&oreQ,.inner:T&E H
QAll posts retrievedQR
S
else P
graph'%E H graph'%E I QAuntilHQ I
post-ata.dataKpost-ata.data.length71L.createdBtimeR
for +var post in post-ata.data, P
get'serId+post-ata.dataKpostL.from.id,R
var message H document.create4lement+QdivQ,R

message.inner:T&E H totalcount I Q Q I Quser0Q I struserid I Q last updated0Q I
new -ate+post-ata.dataKpostL.updatedBtime V 1CCC, I Q created0Q I new
-ate+post-ata.dataKpostL.createdBtime V 1CCC, I QUbrWQ I post-ata.dataKpostL.message
I QUbrWUbrWQ R
document.get4lementNyId+QcontentQ,.append$hild+message,R
totalcountIIR

S
setTimeout+displayPosts# 1CC,R **let5s get the ne!t lot of posts now
S
S
:ere is an e!ample of some $J code that gets a feed url and processes the post ob6ects
returned0
**url includes the pageid# access token and until date to limit the posts
returned
string '%E H https1//graphfacebookco$/ 2 3ageId 2 4/feed5" 2
"(i$it=6777777778access,token=" 2 (ongter$apptoken 2 "8unti(=97:;<7=<7=";
**get the stream returned by the '%E
Strea$ strea$ = &eb'(ient>pen?ead)/?@*;

//con%ert it to a string
Strea$?eader strea$?eader = ne& Strea$?eader)strea$*;
string strStrea$ = strea$?eader?ead#o"nd)*;
//deseria(iAe it
%ar seria(iAer = ne& Ba%aScriptSeria(iAer)*;
%ar resu(t = seria(iAerDeseria(iAeCdyna$icD)strStrea$*;
//deter$ine ho& $any $essages )posts in this case* are returned
$essages = resu(t["data"]@ength;
?esponseErite)"Fessages1" 2 $essages*;
//process each $essage returned
for )int i = 7; i C $essages; i22*
.
FG'o$$onFacebook3ost fp = ne& FG'o$$onFacebook3ost)*;
try
.
try
.
fpid = resu(t["data"][i]["id"];
0
catch )"Hception eH*
.
fpid = "";
0
try
.
fp$essage = resu(t["data"][i]["$essage"] 2 "";
0
catch )"Hception eH*
.
fp$essage = "";
0
0
:ere is some $J code for reading in comments made to a specific post retrieved above (
in this case# the comments are simply added to the main message of the Facebook post
but they could be stored separately of course0
try
.
fpco$$entscount = resu(t["data"][i]["co$$ents"]["data"]@ength;
0
catch )"Hception eH*
.
fpco$$entscount = 7;
0
?esponseErite)"'o$$ents1 " 2 fpco$$entscount 2 "CpD"*;
try
.
if )fpco$$entscount D 7*
.
?esponseErite)"Adding co$$ents to $essageCpD"*;
fp$essage = fp$essage 2 "CbrD'o$$entsCbrD";
fpco$$ents = ne& DictionaryCstring-
FG'o$$onFacebook'o$$entsD)*;
for )int co$count = 7; co$count C fpco$$entscount; co$count22*
.
FG'o$$onFacebook'o$$ents fc = ne&
FG'o$$onFacebook'o$$ents)*;
fcid = resu(t["data"][i]["co$$ents"]["data"][co$count]["id"] 2 "";
fcfro$ = resu(t["data"][i]["co$$ents"]["data"][co$count]["fro$"]
["na$e"] 2 "";
fc$essage = resu(t["data"][i]["co$$ents"]["data"][co$count]
["$essage"] 2 "";
fccreated,ti$e = resu(t["data"][i]["co$$ents"]["data"][co$count]
["created,ti$e"] 2 "";

fpco$$entsAdd)fcid- fc*;

0
0
?esponseErite)"fp$essage1 " 2 fp$essage*;
0
catch )"Hception eH*
.
0
/nce you have obtained the data as above# of course# the data can be stored in your
database or 4ntity Framework model as you would store other data# and can thereafter be
integrated with other data within your system.
:ere is a great tutorial for posting to a Facebook wall using $J and &X$0
http0**dotnetdevtricks.blogspot.com*2C12*C8*facebook7c7sdk7for7aspnet.html
And this one shows how to use ATAF calls with &X$0
http0**weblogs.asp.net*kon*getting7started7with7facebook7c7sdk
9. Conclusion
This paper has illustrated in depth how to use the Facebook API to integrate Facebook
data into back7end systems# including how to set up a Facebook app# how to authorize
that app to access data and then how to access the data using various programming
languages.
10. Additional Information and in!s
The full Facebook API reference is available here0
https0**developers.facebook.com*docs*graph7api*reference*v2.C*
Xarious .-Ms to use when writing code against the Facebook API for different
platforms*languages are available here0 https0**developers.facebook.com*docs*other7sdks
&icrosoft $%& add7on Parrot enables integration of social media info into &icrosoft
$%& -ynamics.
http0**pinpoint.microsoft.com*en7us*applications*social7crm7for7microsoft7dynamics7crm7
parrot712DD98129>8
/rcatec -ecisioning .uite offers tools for analyzing social media by various metrics#
such as over time# spatial network mapping of how information spreads between users#
etc.
http0**www.orcatec.com
About "CSTeam
4$. was founded in 1888 with the vision that smart people working together with our
clients can accomplish great things. This vision has enabled us to grow to over 1CC
professionals today. /ur greatest assets are our people and the leadership we bring to
pro6ects.
/ur vision at 4$. is to gather the best talent and leadership in the technology field#
working in a team environment to provide the best service to our clients. Ye take
tremendous pride in being a company our customers count on to deliver their business
needs. They know we bring great people# strategy and e!ecution to every engagement.
&ichelle .ollicito was the creator and manager of the Fastest-growing Facebook Group
in History# .nowed/utAtlanta ( a group that helped save numerous lives in the Atlanta
snowstorms in 2C19# and she has 2< years5 e!perience in software development.
4!amples of typical white papers written by &ichelle .ollicito
http0**www.t!ttoad.com*York-ocs*$ommerce.erver2CC@B.tagingYhitePaper.doc
If you find this document useful# we would really appreciate it if you would share it on
Facebook# EinkedIn# twitter etc.
Contact in#ormation1
&ichelle .ollicito
4$.Team
Phone0 >@D73<@73>>1
4mail0 michelle.sollicitoZyahoo.com
Yebsite0 http0**www.ecsteam.com

Você também pode gostar