RanRag
RanRag

Reputation: 49597

Python: Check facebook user access token expired or not

I am using facepy facebook api to fetch messages from my facebook account. I have got myself long live access token with validity of 60days using the API. Now, in my program before querying for message I want to check wether my token has expired or not and if expired fetch a new one.

I am using get_extended_access_token which also returns a datetime instance describing when token expires. Now I think it is not a effecient way to use get_extended_access_token because everytime I am going to query for new message it will also fetch the access token(I know it is same as before) but I think this is a overhead.

So, I googled and found that we can also use

https://graph.facebook.com/debug_token?input_token=INPUT_TOKEN&access_token=ACCESS_TOKEN

to debug the token

So I supplied my long live access token instead of INPUT_TOKEN and ACCESS_TOKEN and it gave me a json response:

{
   "data": {
      "app_id": XXXXX,
      "is_valid": true,
      "application": "YYYYY",
      "user_id": ZZZZZZ,
      "issued_at": 1349261684,
      "expires_at": 1354445684,
      "scopes": [
         "read_mailbox"
      ]
   }
}

Now if you look at expires_at field it is showing 1354445684 seconds and when I tried to convert it into days/months it gave me 15676 days and when I checked the same token in graph explorer using the debug option it showed

expires_at: 1354445684(about 2 months)

Now, what I don't understand is how 1354445684 is equivalent to 2 months and how to achieve this in python.

Also comment on which is the better approach to check wether token has expired or not API or using the facebook url?

Upvotes: 0

Views: 3166

Answers (2)

Johannes Gorset
Johannes Gorset

Reputation: 8785

I recommend you rely on exceptions to verify whether the token was valid instead of making a separate request to guarantee it:

from facepy import GraphAPI

graph = GraphAPI(token)

try:
    graph.get('me')
except GraphAPI.OAuthError:
    # Redirect the user to renew his or her token

Upvotes: 2

C3roe
C3roe

Reputation: 96424

Now if you look at expires_at field it is showing 1354445684 seconds and when I tried to convert it into days/months it gave me 15676 days

Then you’ve done (or understood) something wrong.

expires_at 1354445684 is a Unix Timestamp, and equals Sun, 02 Dec 2012 10:54:44 +0000 translated into a human-readable date.

And that is pretty much two month from the issued_at timestamp 1349261684, a.k.a. Wed, 03 Oct 2012 10:54:44 +0000

Upvotes: 6

Related Questions