- I want people to log in to my site with their Facebook accounts.
- I need to pull some info from their Facebook profile and add it to my site's database
I have tried using the OAuth 2.0 method which makes a redirect to this url
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID
&redirect_uri=YOUR_REDIRECT_URI
&scope=COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES
&state=SOME_ARBITRARY_BUT_UNIQUE_STRING
I successfully authenticated the user but now the main problem arose. How do I access the data which is sent as response all I can see is a GET
variable named code
and some long text. How do I convert to usable data?
I use php for my website
Exchange the code for a user access token
Once the user has authorized your app, you should make a server side request to exchange the code returned above for a user access token.
The client_secret parameter must be the App Secret as shows in your app's settings. The body of the response to this request will be a url encoded string of the form:
You should parse this string and use the access_token value to make requests to the Graph API. You should also persist the access token in your database in order to make further requests to the API without having to re-authenticate the user.
Once the access token expiry time is reached, the token will become invalid and can no longer be used in requests to the API. To obtain a new user access token, you must pass the user through this flow again. However, if the user has not deauthorized your app and you're asking for no permissions beyond those which the user has already granted your application, then no dialog will be displayed and the user will be transparently redirected to your redirect_uri with a fresh code which can be exchanged for a fresh user access token.
If there is an issue exchanging the code for a user access token, the authorization server will issue an HTTP 400 and return the error as a JSON object in the body of the response:
For further reference checkout http://developers.facebook.com/docs/authentication/server-side/
Making requests to the Graph API
With a valid user access token, you can make requests to read and write data from the Graph API. A common first request would be to get the basic information (including the id and name) of the user who just authenticated your app:
In OAuth 2.0 with facebook, the overall concept is simple as follows.
Step 1. Obtain "Authorization Code" by a GET request
Step 2. Obtain the "Access Token" by sending the authorization code as a POST request
Step 3. Use the access token got from above step and retrieve user resources
Use JSON WEB TOKEN(JWT) decoder to get the data which is in the token_id which you will get when you print the contents of GET['code']. In that select the token_id copy it and paste it in the online decoder
There is an official SDK for php from Facebook. Which makes life easier.
Check this sample code