Facebook API White Paper

Embed Size (px)

Citation preview

  • 8/11/2019 Facebook API White Paper

    1/23

    Facebook API Integration

    By Michelle SollicitoECSTeamAtlanta, GA

    Social networking is increasingly becoming a key component to developing deep relationships withcustomers. 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 andshopping carts to provide a more personali*ed e+perience for users based upon their social mediapreferences.

    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 integrationas it provides access to information about people, their posts, their comments and their likes. 2his paperaims to e+plain how to use the -acebook raph api effectively to integrate such data into internal businesssystems.

    1. IntroductionThis paper will first introduce the Facebook Graph API and the different tools that areavailable when using it. It will then illustrate how to set up authorization and access tothe 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 aFacebook group and place that data in a database table. An e!ample of how toautomatically post to a Facebook group will also be provided.

    2. TrendsTrend towards using social media to deepen relationships. People are buying via socialmedia# are getting recommendations via social media# are reading feedback on productson social media# are learning about alternatives on social media# are trying to self serviceor get support on social media.$ompanies are realizing the value of the data and need to integrate it into their internalsystems# especially their $%& systems.

    Example: Utilities and social media'tilities want to educate their customers about the products and services they offer. Theywant to be $orporate $itizens# helping customers with their electrical appliances# helping

    mailto:[email protected]://www.ecsteam.com/http://www.businessnewsdaily.com/815-social-media-2012.htmlhttp://www.businessnewsdaily.com/815-social-media-2012.htmlhttp://data-informed.com/4-approaches-for-integrating-social-media-data-with-enterprise-systems/mailto:[email protected]://www.ecsteam.com/http://www.businessnewsdaily.com/815-social-media-2012.htmlhttp://data-informed.com/4-approaches-for-integrating-social-media-data-with-enterprise-systems/
  • 8/11/2019 Facebook API White Paper

    2/23

    them during financial difficulties to keep their electric or gas on# helping them to budgeteffectively# helping them to reduce their bills# but most importantly they want to helpcustomers when an outage happens ( help them to )uickly report outages# help them tofind 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 thenowed/utAtlanta Facebook group about how prepared +or otherwise, they believedtheir 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

  • 8/11/2019 Facebook API White Paper

    3/23

    2. 'sing Facebook to help others self support

    ..and they watched the total of outages growing as the storm got worse over time..

  • 8/11/2019 Facebook API White Paper

    4/23

  • 8/11/2019 Facebook API White Paper

    5/23

    3. ProblemIntegrating data from Facebook into internal systems is made easier because Facebookmade 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 toobtain the activity data from Facebook# one of two types of security gateways must beused. 4ither the Facebook user must allow" an app to link their Facebook profile to theInternal 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 thecompany in )uestion. The app itself must also have been set up with an authenticationkey 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 whichallows 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$onnect7with7Facebook Take note in particular of step 8 where the user is informed of the type ofinformation being authorized +in this case# your public profile# friend list and emailaddress,0

    9. Prompting the user for permission to access their data

    http://tutorials.jenkov.com/oauth2/index.htmlhttp://tutorials.jenkov.com/oauth2/index.htmlhttp://www.wikihow.com/Authorize-an-App-to-Connect-with-Facebookhttp://www.wikihow.com/Authorize-an-App-to-Connect-with-Facebookhttp://tutorials.jenkov.com/oauth2/index.htmlhttp://www.wikihow.com/Authorize-an-App-to-Connect-with-Facebookhttp://www.wikihow.com/Authorize-an-App-to-Connect-with-Facebook
  • 8/11/2019 Facebook API White Paper

    6/23

    If a user voluntarily 6oins a company Facebook group or Facebook page and postsinformation# 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)uestaccess to the Facebook page or Facebook group +again different types of data may bere)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 difficultto associate a Facebook profile with an e!isting customer in the company database. Incases where the user e!plicitly allows the app to link the Facebook profile to the internalcustomer account# this problem is resolved. :owever# in cases where the Facebook useris 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 theFacebook account. /f course# if the primary email address on the Facebook account doesnot 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 touse 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 typeinto the url0 https0**developers.facebook.com*

    $lick on Apps" and then select $reate a ;ew App" from the submenu.

    https://developers.facebook.com/https://developers.facebook.com/
  • 8/11/2019 Facebook API White Paper

    7/23

  • 8/11/2019 Facebook API White Paper

    8/23

    >. $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 lateras your apps grow and develop# and gain more of an audience.

  • 8/11/2019 Facebook API White Paper

    9/23

    4.2. Granting App ermi!!ion!

    @. The app dashboard

    The tatus %eview section# for e!ample# is very important because it is where youre)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 needmanageBpages" permission in order to get an access token +security key, to allow you toaccess the page*group# and you will need publishBactions" permission to allow your appto actually post posts to the group or page.

    For more information about permissions your app might need and why# see this articlehttps0**developers.facebook.com*docs*facebook7login*permissions*v2.C

    %e)uest the permissions you need here now before moving on.

    https://developers.facebook.com/docs/facebook-login/permissions/v2.0https://developers.facebook.com/docs/facebook-login/permissions/v2.0
  • 8/11/2019 Facebook API White Paper

    10/23

    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# itis 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 protocolused by Facebook for security purposes.

    The general principle of /Auth is that a http get" call is made to an /Auth uri indicatingwhich permissions are re)uired in the scope" parameter# and the app re)uesting the

    permissions is identified using the clientBid" parameter. A redirectBuri" parameterindicates 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 /Authmechanism.

  • 8/11/2019 Facebook API White Paper

    11/23

  • 8/11/2019 Facebook API White Paper

    12/23

    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 somethinglike this# and m%!t always be made server side for security reasons +anyone who can seethis call containing your app id# app secret and a short lived token# could potentially usethe 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 tokenfor an application with the manageBpages" permission,0https0**www.facebook.com*dialog*oauthclientBidHAPPEI$ATI/;BI- redirectBuriHhttps0**www.facebook.com*connect*loginBsuccess.html responseBtypeHcode token displayHpopup scopeHmanageBpages

    If you want to capture the result +access token, programmatically# you can addtypeHuserBagent or typeHwebBserver to your /Auth call to receive the result as a

    parameter in the url of the redirect page either like this0http0**yourredirecturiJcodeHKaccesstokenL

    /r like this0 http0**yourredirecturi codeHKaccesstokenL

    A typical /Auth re)uest in $J*.;et +using the Facebook -M for .;et# available herehttp0**facebooksdk.net* or via ;uget, for reading the stream" from a user5s groups lookslike this0

    string AppID = "[put your appid here]" ;string AppSecret = "[put your app secret here]" ;

    http://graph.facebook.com/endpoint?key=value&access_token=app_idhttp://graph.facebook.com/endpoint?key=value&access_token=app_idhttp://graph.facebook.com/endpoint?key=value&access_token=app_idhttp://graph.facebook.com/endpoint?key=value&access_token=app_idhttps://www.facebook.com/dialog/oauth?client_id=APPLICATION_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=code+token&display=popup&scope=manage_pageshttps://www.facebook.com/dialog/oauth?client_id=APPLICATION_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=code+token&display=popup&scope=manage_pageshttps://www.facebook.com/dialog/oauth?client_id=APPLICATION_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=code+token&display=popup&scope=manage_pageshttp://facebooksdk.net/http://facebooksdk.net/http://graph.facebook.com/endpoint?key=value&access_token=app_idhttps://www.facebook.com/dialog/oauth?client_id=APPLICATION_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=code+token&display=popup&scope=manage_pageshttps://www.facebook.com/dialog/oauth?client_id=APPLICATION_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=code+token&display=popup&scope=manage_pageshttps://www.facebook.com/dialog/oauth?client_id=APPLICATION_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=code+token&display=popup&scope=manage_pageshttp://facebooksdk.net/
  • 8/11/2019 Facebook API White Paper

    13/23

    // using Facebook SDK for ! # to read fro$ groups

    %ar fb = ne& Facebook Facebook'(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(t access,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& Facebook Facebook'(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(t access,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 here0http0**hayageek.com*facebook7dialog7oauth*

    To find out more about access tokens see this page0https0**developers.facebook.com*docs*facebook7login*access7tokens

    For more detail about how /Auth 2.C works in Facebook seehttps0**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= andGoogle all use /Auth 2.C as their authentication protocol.

    http://hayageek.com/facebook-dialog-oauth/https://developers.facebook.com/docs/facebook-login/access-tokenshttps://developers.facebook.com/docs/reference/dialogs/oauthhttp://tutorials.jenkov.com/oauth2/index.htmlhttp://tutorials.jenkov.com/oauth2/index.htmlhttp://hayageek.com/facebook-dialog-oauth/https://developers.facebook.com/docs/facebook-login/access-tokenshttps://developers.facebook.com/docs/reference/dialogs/oauthhttp://tutorials.jenkov.com/oauth2/index.html
  • 8/11/2019 Facebook API White Paper

    14/23

    Ne aware that even long7term access tokens eventually e!pire and this article e!plainshow to handle those situations0 http0**facebooksdk.net*docs*web*handling7e!pired7access7tokens*

    (. 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 forwhich 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 itis to do the following0

    1, Go to the url of your Facebook page. For e!ample# it might be something likethis0https0**www.facebook.com*groups*snowedoutatlanta*

    or it might be something like this0https0**www.facebook.com*groups*23>*

    or a page may have a url like this0https0**www.facebook.com*T!tToAd

    2, From the Page or Group main page# go to the %eport Group" option under theGear" icon see below

    :over over the %eport Group" option and right click your mouse and select $opy linkaddress". Paste the contents of your clipboard into notepad or similar. ?ou should getsomething that looks like this0 https0**www.facebook.com*a6a!*report.phpcontentBtypeH1 cidH38@D38>@3>8@3>8

  • 8/11/2019 Facebook API White Paper

    15/23

    ;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 getac)uainted with a wonderful tool provided by Facebook to help with generating calls tothe Graph API. It is called the Graph API 4!plorer" and makes working with the GraphAPI a great deal easier.

    To see it in action go to this url0https0**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 sessionat the top of the page.

    https://developers.facebook.com/tools/explorerhttps://developers.facebook.com/tools/explorer
  • 8/11/2019 Facebook API White Paper

    16/23

    Also note that it works in two modes0 Graph API and FOE Ouery. -uring this tutorial wewill mainly use the Graph API because FOE will soon be retired*discontinued# but theFOE Ouery is*was an e!tremely powerful OE7like tool for )uerying Facebook ob6ectsand 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 greatresource0

    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 ofresults obtained. Ny default# the me" )uery showing the currently logged in Facebookuser5s id and name is provided.

    $hange the )uery from0 *me fieldsHid#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

  • 8/11/2019 Facebook API White Paper

    17/23

    ?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 linkhttps0**developers.facebook.com*docs*graph7api*reference*v2.C*postFor full details of the feed call# see this link0https0**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*

  • 8/11/2019 Facebook API White Paper

    18/23

    /. 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 multitudeof programming languages. For illustration purposes# here we will produce some code in$J * A P.;et and some code in 6avascript using :%.

    :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 this01CCCCC998DD>D>9+in fact if you call this function with the above userid# the username returned ismsollicito" +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,

    var urlHQhttps0**graph.facebook.com*Q userid Q fieldsHusernameQRvar !hr H new &E:ttp%e)uest+,R!hr.open+QG4TQ# url# false,R!hr.onload H function +e, if +!hr.ready tate HHH 9, if +!hr.status HHH 2CC, struseridH!hr.responseTe!tR S

    else struseridH!hr.statusTe!tR S SSR!hr.onerror H function +e, struseridH!hr.statusTe!tRSR!hr.send+null,RS

    ?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*feed Q QcallbackHdisplayPosts Q QdateBformatH' Q QlimitH

  • 8/11/2019 Facebook API White Paper

    19/23

    If you run the following code0** $all the Graph API here function getPosts+, 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'%Ewhich in turn retrieves some posts as data and sends the data as an ob6ect +post-ata, tothe callback displayPosts" referred to in the graph'%E. The posts retrieved are# ofcourse# posts from the group +or page, identified by the id placed into the url betweenhttps0**graph.facebook.com* and *feed "

    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 beused 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 theuserid first +using the function we talked about earlier ( get'serId, and then processingthe 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 FacebookAPI Post ob6ect here# see https0**developers.facebook.com*docs*graph7api*reference*v2.C*post for details.

    **display posts using avascriptfunction displayPosts+post-ata, if +post-ata.data.length U2, document.get4lementNyId+Qdiv&oreQ,.inner:T&E H QAll posts retrievedQR S else graph'%E H graph'%E Q untilHQ post-ata.dataKpost-ata.data.length71L.createdBtimeR

    for +var post in post-ata.data, get'serId+post-ata.dataKpostL.from.id,R

    var message H document.create4lement+QdivQ,R

    message.inner:T&E H totalcount Q Q Quser0Q struserid Q last updated0Q new -ate+post-ata.dataKpostL.updatedBtime V 1CCC, Q created0Q new-ate+post-ata.dataKpostL.createdBtime V 1CCC, QUbrWQ post-ata.dataKpostL.message QUbrWUbrWQ R

    https://graph.facebook.com/https://developers.facebook.com/docs/graph-api/reference/v2.0/posthttps://developers.facebook.com/docs/graph-api/reference/v2.0/posthttps://developers.facebook.com/docs/graph-api/reference/v2.0/posthttps://graph.facebook.com/https://developers.facebook.com/docs/graph-api/reference/v2.0/posthttps://developers.facebook.com/docs/graph-api/reference/v2.0/post
  • 8/11/2019 Facebook API White Paper

    20/23

  • 8/11/2019 Facebook API White Paper

    21/23

  • 8/11/2019 Facebook API White Paper

    22/23

    And this one shows how to use A A calls with &X$0http0**weblogs.asp.net*kon*getting7started7with7facebook7c7sdk

    9. ConclusionThis paper has illustrated in depth how to use the Facebook API to integrate Facebookdata into back7end systems# including how to set up a Facebook app# how to authorizethat app to access data and then how to access the data using various programminglanguages.

    10. Additional Information and in!s

    The full Facebook API reference is available here0https0**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 ourclients 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 taketremendous pride in being a company our customers count on to deliver their businessneeds. They know we bring great people# strategy and e!ecution to every engagement.

    http://weblogs.asp.net/kon/getting-started-with-facebook-c-sdkhttps://developers.facebook.com/docs/graph-api/reference/v2.0/https://developers.facebook.com/docs/other-sdkshttp://pinpoint.microsoft.com/en-us/applications/social-crm-for-microsoft-dynamics-crm-parrot-12884912469http://pinpoint.microsoft.com/en-us/applications/social-crm-for-microsoft-dynamics-crm-parrot-12884912469http://www.orcatec.com/http://weblogs.asp.net/kon/getting-started-with-facebook-c-sdkhttps://developers.facebook.com/docs/graph-api/reference/v2.0/https://developers.facebook.com/docs/other-sdkshttp://pinpoint.microsoft.com/en-us/applications/social-crm-for-microsoft-dynamics-crm-parrot-12884912469http://pinpoint.microsoft.com/en-us/applications/social-crm-for-microsoft-dynamics-crm-parrot-12884912469http://www.orcatec.com/
  • 8/11/2019 Facebook API White Paper

    23/23

    &ichelle ollicito was the creator and manager of the Fastest-growing Facebook Groupin History # nowed/utAtlanta ( a group that helped save numerous lives in the Atlantasnowstorms 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 onFacebook# EinkedIn# twitter etc.

    Contact in#ormation&ichelle ollicito4$ TeamPhone0 >@D73>1

    4mail0 michelle.sollicitoZyahoo.comYebsite0 http0**www.ecsteam.com

    http://www.txttoad.com/WorkDocs/CommerceServer2007_StagingWhitePaper.dochttp://var/www/apps/conversion/tmp/scratch_1/[email protected]://www.ecsteam.com/http://www.txttoad.com/WorkDocs/CommerceServer2007_StagingWhitePaper.dochttp://var/www/apps/conversion/tmp/scratch_1/[email protected]://www.ecsteam.com/