27

I'm trying to use the Facebook Graph API to grab photo albums from Facebook and place them on a website I'm working on. I am using PHP as my language with the Codeigniter framework and am redirecting to a Facebook URL to get an access token for the user. Facebook returns an access token to me and I grab it and insert it into my database.

That being said, when I try to grab the JSON data for the photo album by going to to a the graph URL, it returns an error. The graph URL and error are:

https://graph.facebook.com/1298926000574/photos?access_token=[MY ACCESS TOKEN]

My access token: AQBxqdB64GHNTGY5Yp_IOuMY7NerwNtXVVrp2HwT1qXj02zqU-63KJDyB2jzqurlJ4M0vd7TAu7upA6T7ZYQzIChr2PgD1dpu-6Iebi0WVILbBSBOu-yj7sgcHSGS-Ew4Yio0I9In-1O5jOxbYLDMbI0Zmwk-F1-u-7a8iVvTJram8PvpmdRt5eg

Returned error:

{
"error": {
  "message": "Malformed access token [MY ACCESS TOKEN]",
  "type": "OAuthException",
  "code": 190
}
} 

I'm really unsure why Facebook keeps returning this error to me. The access token is quite long and I'm storing it in my database as a "text" field. I followed their instructions and now they are shooting me in the foot. Any help would be much appreciated.

user1470807
  • 271
  • 1
  • 3
  • 4
  • Are the square-bracketed words put there by you? – Jasper Mogg Jun 21 '12 at 01:50
  • Yes, its just there to show where the access token is in the URL and error JSON – user1470807 Jun 21 '12 at 02:49
  • Have you tried to bypass storing in the database and instead using it directly from the returned data from Facebook? My point is ensuring that the storage and querying back out of the token is not to blame. – Nick Jun 21 '12 at 05:13
  • There's definitely something wrong with that access token - none of mine seem to have underscores or dashes in them... is it encoded in some way? – Jasper Mogg Jun 21 '12 at 12:26
  • 4
    **Do not post real access tokens publicly**! Make sure you change some of the characters in all your access tokens and try to invalidate them by logging out and logging in again as soon as you are done with this question! – Emil Vikström Jun 21 '12 at 13:27
  • Are you sure that's the access token and not the `code` from the auth flow? – Igy Jun 21 '12 at 16:31
  • It appears that the Code is the only thing returned to me from Facebook. Is there further things that must be done to obtain the access token? – user1470807 Jun 21 '12 at 18:32
  • Yes. see the [Authentication](https://developers.facebook.com/docs/authentication/) documentation – Igy Jun 22 '12 at 10:38
  • The sad thing is that when I copy the exact url and paste it to the browser, the right data is returned but when I run my android code, it fails. – Eenvincible Jul 09 '14 at 19:16

6 Answers6

71

I had this same problem and I found this post searching for a solution. I noticed that 'our' access token had a lot of odd symbols, while others are just an Alphanumeric string.

I believe that the mistake you (and I) made was mixing the code with the access_token

After sending the facebook user to your api to confirm access, they get returned to your website with $_GET['code']. This code needs to be verified with Facebook, who will return the access_token on success.

$app_id = [YOUR_APP_ID];
$app_secret = [YOUR_APP_SECRET];
$my_url = [THE_SAME_AS_THE_POST_BEFORE];
$code = $_GET['code'];

$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;

$response = file_get_contents($token_url);
$params = null;
json_decode($response, $params);
$access_token = $params['access_token'];

More info about fetching an access_token with PHP

More info about using the correct redirect_uri

Gijs P
  • 1,325
  • 12
  • 28
  • 1
    +1 for the great explanation! However,`parse_str` not working. I think it's because API may have been changed slightly. Instead, `json_decode` does the job. – Tharindu Thisarasinghe Aug 19 '17 at 10:37
3

One wp plugin was returning same error, and this was the solution, it may be related to your problem:

Php requests the access_token, and facebook servers return it.

The returned message containing access_token USED to be a like:

access_token=.......

But for newly created applications (2012), facebook servers return:

access_token=.....&expires=.....

If your code is parsing this wrongly, as in

$access_token=str_replace('access_token=','',$message);

then your $access_token wrongly contains the extra &expires etc.

it should be parsed like:

parse_str($message,$ar); $access_token=$ar['access_token'];
Johan
  • 637
  • 7
  • 11
2

I had the same problem. Figured how it's working and here's for anyone who's sinking in the same mud.

require 'facebook-php-sdk/facebook.php';
$facebook = new Facebook(array(
  'appId'  => 'APP ID',
  'secret' => 'SECRET KEY',
));

// Get User ID
$user = $facebook->getUser();  
if ($user) {
    $accessToken = $facebook->getAccessToken();
        try {
            $url = "https://graph.facebook.com/1298926000574/photos?access_token=".$accessToken;

            $photos = $facebook->api($url);
            var_dump($photos);
        } catch (FacebookApiException $e) {
            $user = null;
        }
    }   
} else {
    //echo "You need to login";
    header("Location:".$facebook->getLoginUrl());
}
Himal
  • 33
  • 5
1

You are sending code instead of access_token in your request.

The solution for Laravel Socialite users:

Use:

$response = Socialite::driver($provider)->getAccessTokenResponse($request['code']);
$user = Socialite::driver($provider)->userFromToken($response['access_token']);

Instead of:

$user = Socialite::driver($provider)->user();
Mahmoud Zalt
  • 30,478
  • 7
  • 87
  • 83
1

tl;dr

The access token should consist of your app id and your access token with a pipe (|) character between them: 123456789012345|AbCDefGHijKLMNOpqRSTUVwxYZ.

Creating and using an access token

Note: In this tutorial I use only dummy credentials. They will be in the same style as real ones would be but their exact value is just a series of incremented numbers or characters. Never post your actual credentials online!

Creating an access token

Requirements:

  • App id: 123456789012345
  • App secret: ZYxwVUTSRqpONMLKjiHGfeDCbA

If you follow the access token creation guide you will find this URL where you can create one:

GET /oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials

If we insert in our dummy credentials the GET request's URI should look like this:

 http://graph.facebook.com/oauth/access_token?client_id=123456789012345&client_secret=ZYxwVUTSRqpONMLKjiHGfeDCbA&grant_type=client_credentials

The response will be:

{
  "access_token": "123456789012345|AbCDefGHijKLMNOpqRSTUVwxYZ",
  "token_type": "bearer"
}

The access token consists of your app id followed by a pipe (|) then the string that could be called the actual access token.

Using the access token

Requirements:

  • Access token: 123456789012345|AbCDefGHijKLMNOpqRSTUVwxYZ
  • Whatever other credential you need. User id in this example: 1234567890

In this example I will follow the official facebook guide on sending notifications. They showed this template:

POST /{recipient_userid}/notifications?access_token=... &template=...&href=...

That means, after you fill in your credentials an example POST request should look like this:

http://graph.facebook.com/1234567890/notifications?access_token=123456789012345|AbCDefGHijKLMNOpqRSTUVwxYZ&template=Test&ref=notif_test
totymedli
  • 29,531
  • 22
  • 131
  • 165
-1

As error says it's malformed exception means error in formatting the request.

https://graph.facebook.com/me/photos/?access_token=[your_accesstoken]

So it would be like

https://graph.facebook.com/me/photos/?access_token=AQBxqdB64GHNTGY5Yp_IOuMY7NerwNtXVVrp2HwT1qXj02zqU-63KJDyB2jzqurlJ4M0vd7TAu7upA6T7ZYQzIChr2PgD1dpu-6Iebi0WVILbBSBOu-yj7sgcHSGS-Ew4Yio0I9In-1O5jOxbYLDMbI0Zmwk-F1-u-7a8iVvTJram8PvpmdRt5eg
Vikalp Patel
  • 10,669
  • 6
  • 61
  • 96