简体   繁体   中英

Capture access_token from facebook's server-side authentication in Django

I want to capture the access_token returned by this url(below)

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

But if I HttpResponseredirect, it takes me to a blank page with access_token and expiry secs printed. I want to capture the returned access_token and use it later. Below is my code

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)

You can use urllib to perform the request:

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()

If the response is json, you can decode it like so:

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

Here's a similar question dealing with this

Depending on what you are trying to do, there are probably easier ways to interact with Facebook:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM