如何在python中扩展facebook访问令牌

时间:2014-11-18 19:46:28

标签: facebook python-2.7 facebook-graph-api facebook-sdk-4.0

我正在使用Python facebook-sdk客户端库。 我目前有一个从https://developers.facebook.com/tools/accesstoken/获得的短期访问令牌,我将代码从站点复制到我的代码中进行身份验证。

       graph = facebook.GraphAPI(access_token)

此令牌会在60分钟后过期。我希望将其扩展为60天的生存令牌,以便每次过期时都不需要手动复制。我可以找到许多关于如何以不同格式执行此操作的答案,但不是python(或者至少不是简单地没有登录页面等)。

[供参考,我将使用的代码仅供我使用,因此,我不打算创建登录页面。我只是希望能够扩展我已有的令牌。

3 个答案:

答案 0 :(得分:13)

在最初询问问题时,不确定这是否在python的FB API中可用,但延长访问令牌到期的更简洁的方法是:

graph = facebook.GraphAPI(user_short_lived_token_from_client)
app_id = 'app_id' # Obtained from https://developers.facebook.com/
app_secret = 'app_secret' # Obtained from https://developers.facebook.com/

# Extend the expiration time of a valid OAuth access token.
extended_token = graph.extend_access_token(app_id, app_secret)
print extended_token #verify that it expires in 60 days

答案 1 :(得分:3)

这是一个经过编辑的版本,与最新的api版本兼容:

import requests
import json
access_token = 'your token'     # Obtained from https://developers.facebook.com/tools/accesstoken/
app_id = "your app id"          # Obtained from https://developers.facebook.com/        
client_secret = "app secret"    # Obtained from https://developers.facebook.com/

link = "https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=" + app_id +"&client_secret=" + client_secret + "&fb_exchange_token=" + access_token
s = requests.Session()
token = s.get(link).content
token=json.loads(token)
token=token.get('access_token')

print token

答案 2 :(得分:1)

根据他们关于extending short lived client tokens的小节,您需要接收您的短期客户端令牌,并在填写相关的应用数据后,从您的服务器向以下端点发送GET请求:

GET /oauth/access_token?  
  grant_type=fb_exchange_token&           
  client_id={app-id}&
  client_secret={app-secret}&
  fb_exchange_token={short-lived-token}

响应将包含您的长期访问令牌,然后可以将其传递回客户端或在您的服务器上使用。如果您目前没有执行HTTP操作的模块,我强烈推荐Requests