Chris Sunderland
Chris Sunderland

Reputation: 111

Using Facebook OAuth 2.0 - How do I fetch the access token?

I am new to OAuth, and I'm trying to use Facebook Connect with my web-application.

I have succeded in getting a verification token, but my problem is "fetching" the access token. How do I fetch it? The Facebook documentation tells me to fetch the access token with this URL:

https://graph.facebook.com/oauth/access_token?'
                + 'client_id=XXXXXXXXXXXX& redirect_uri=http://www.mysite.com/fbconn/index.html&display=touch&'
                + 'client_secret=axxxxxcxxxxxxxxxxx&code=' + code;

When I use this I see the access token on a blank page, but I want to fetch it with JavaScript (Ajax), PHP or something. Is this possible? I thought the access token would be appended to my redirect URI like the verfication code, but I never get redirected to my page. What am I doing wrong?

Upvotes: 5

Views: 14721

Answers (3)

Arthur Menezes
Arthur Menezes

Reputation: 21

Feel free to try the following PHP snippet for getting your access token:

//Fill in the parts in caps with your app details
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_YOU_GOT_FROM_THE_SERVER";

$token=file_get_contents($token_url); //Fetching the token from the URL

echo $token; //This is your access token

Thanks,

Upvotes: 2

Amir
Amir

Reputation: 9192

You need to add &type=user_agent to the request. You will get the AuthToken with a hash marker in the following format.

http://yourredirecturi#code=[accesstoken]

If you set the request to &type=web_server, you'll get the AuthToken as a query string parameter: http://yourredirecturi&code=[accesstoken].

Here is a full explanation of how to implement the Facebook's OAuth protocol. The code samples are in ASP.NET MVC, but it should translate well enough to any language:

Facebook Platform's OAuth 2.0 Protocol and ASP.NET MVC

Upvotes: 6

rahul
rahul

Reputation: 1

$token = file_get_contents("the access token URL"); 

will give you the access token.

Upvotes: -5

Related Questions