Post to Facebook on Behalf of Your User with Python/Django

Posting on facebook through python is fairly simple: you need acquire your user’s facebook access token, which you use to access the users facebook wall.
Step 1: Create the facebook app
First, create a new facebook app on https://developers.facebook.com/apps and note down the APP_ID and APP_SECRET. Store this information in your django settings.py file.
Step 2: Acquire an oauth code
To acquire an oauth code, simply redirect your user to the following url:
https://graph.facebook.com/oauth/authorize along with these arguments:

'client_id': Your facebook app id
'redirect_uri': The url of your web app which will handle the redirect back from facebook
'scope': types of privileges to request from the user

We get:

def acquire_facebook_oauth_code(request):
    redirect_uri = 'http://your_cool_web_app/handle_facebook_redirect/'
    attrs = {'client_id': settings.FACEBOOK_APP_ID,
             'redirect_uri': redirect_uri,
             'scope':'offline_access,publish_stream,manage_pages'}
    code_url = 'https://graph.facebook.com/oauth/authorize?%s'  % urllib.urlencode(attrs)
    return redirect(code_url)

Step 3: Handle the redirect from facebook
Upon successful signin and approval of your user, facebook will redirect back to the ‘redirect_uri’ used above, with an additional ‘code’ argument in the following format:
http://your_cool_web_app/handle_facebook_redirect/?code=……………
We can now use this code to acquire the access_token:

def handle_facebook_redirect(request):
    code = request.GET.get('code')
    attrs = {'client_id': settings.FACEBOOK_APP_ID,
             'client_secret': settings.FACEBOOK_APP_SECRET,
             'code': code }
    access_token_url = 'https://graph.facebook.com/oauth/access_token?%s' % urllib.urlencode(attrs)
    r = requests.get(access_token_url)
    access_token = urlparse.parse_qs(r.content)['access_token'][0]
    # save the access_token for your user
    user_profile = request.user.get_profile()
    user_profile.facebook_access_token = access_token
    user_profile.save()
    return redirect('facebook_succeeded_page')

Step 4: Final step, use the access token to share on the facebook wall
Now that we have the access token saved, we can update the users status by sending a post request to https://graph.facebook.com/feed:

@login_required
def share_on_facebook(request):
    payload = dict(message="Your fancy facebook wall status"),
                   access_token=request.user.get_profile().facebook_access_token)
    req = requests.post('https://graph.facebook.com/feed', data=payload)
    return redirect('facebook_share_succeeded_page')

Make sure to import urllib, urlparse and requests when using the above code. The first two are built into python but requests can be installed with:

sudo pip install requests

Leave a comment

Your email address will not be published. Required fields are marked *