catherine
catherine

Reputation: 22808

KeyError: access token

I have already test this before and it's work. Now the error back again and I didn't do any changes on my social app.

Here are my codes:

def get_profile(request, token=None):
    args = {
        'client_id': settings.FACEBOOK_APP_ID,
        'client_secret': settings.FACEBOOK_APP_SECRET,
        'redirect_uri': request.build_absolute_uri(reverse('social:fb_callback')),
        'code': token,
    }

    target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read()
    response = cgi.parse_qs(target)
    access_token = response['access_token'][-1]

    return access_token 

Upvotes: 0

Views: 5409

Answers (1)

santiagobasulto
santiagobasulto

Reputation: 11726

Obviously, your request is not successful and the response doesn't have an access token. According to facebook docs, when a request isn't good, it returns a response with an error element, something like:

{
  error: {
    message: "Missing redirect_uri parameter.",
    type: "OAuthException",
    code: 191
  }
}

So, in your function, you should do something like:

class FacebookAccessException(Exception): pass

def get_profile(request, token=None):
    ...
    response = json.loads(urllib_response)
    if 'error' in response:
        raise FacebookAccessException(response['error']['message'])

    access_token = response['access_token'][-1]
    return access_token 

PS:

Try to use better urllib. You should try Requests.

Upvotes: 1

Related Questions