从Facebook的Django服务器端身份验证中捕获access_token

时间:2012-03-31 15:37:17

标签: python django facebook facebook-graph-api oauth

我想捕获此网址(下方)

返回的access_token
  

https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URI&client_secret=YOUR_APP_SECRET&code=CODE_GENERATED_BY_FACEBOOK

但是,如果我HttpResponseredirect,它会带我到一个空白页面,其中包含access_token和expiry secs打印。我想捕获返回的access_token并在以后使用它。以下是我的代码

def fb_return(request):
  code = request.GET.get('code')
  fb_id = settings.FB_ID
  fb_s = settings.FB_SECRET    

  url = 'https://graph.facebook.com/oauth/access_token?client_id=%(id)s&redirect_uri=http://127.0.0.1:8000/facebook/return&client_secret=%(secret)s&code=%(code)s'%{'id':fb_id,'secret':fb_s,'code':code}
  return HttpResponseRedirect(url)

1 个答案:

答案 0 :(得分:4)

您可以使用urllib执行请求:

import urllib2
url = 'https://graph.facebook.com/oauth/access_token?client_id=%(id)s&redirect_uri=http://127.0.0.1:8000/facebook/return&client_secret=%(secret)s&code=%(code)s'%{'id':fb_id,'secret':fb_s,'code':code}
response = urllib2.urlopen(url)
html = response.read()

如果响应是json,你可以这样解码:

import simplejson
json = response.read()
dict = simplejson.load(json) 

Here's a similar question dealing with this

根据您的目的,可能更容易与Facebook互动: