I need to post a message on my own Facebook page; and I need to do it programmatically (in my case using Python). I managed to do this part using this code (in Python):
import urllib, urllib2
access_token='XXXX'
fb_page_id='YYYY' # my page ID
post_data = {'access_token':access_token, 'message':'hey this is a test!'}
request_path = str(fb_page_id)+'/feed'
post_data = urllib.urlencode(post_data)
response = urllib2.urlopen(
'https://graph.facebook.com/%s' % request_path, post_data
)
The ID of the generated post on the FB page is correctly returned:
In [11]: response.readlines()
Out[11]: ['{"id":"135386143198208_461964357207050"}']
Problem:
In order to generate the access_token
and make the API request above I had to manually follow the three steps detailed here.
But in practice this manual process is unacceptable as I need to run this task from a cron job. Hence I need to automate it because access_token
in Facebook is temporary. I.e. I need to get an access token each time I run this script. How to do that?
Feel free to use any scripting tool in your answer (curl, JavaScript, Java, PHP) as long you communicate the steps involved. Note that I need to do this using any server-side language (Python/Ruby/PHP).
If you extend your (User) access token, you can then request a (Page) access token which does not in fact expire at all.
See the "Extending Page access tokens" section of the following document: https://developers.facebook.com/docs/howtos/login/extending-tokens/
You cannot retrieve a short-lived token programmatically. It defeats the purpose of user interaction.
Facebook intentionally has made it this way to ensure the user has full manual control over what apps they install.
Once the user grants initial access you can then automate the process up to two months (or earlier if the user invalidates the token, for example by changing their password)
by doing an HTTP request to
https://graph.facebook.com/oauth/access_token?
grant_type=fb_exchange_token&
client_id=APP_ID&
client_secret=APP_SECRET&
fb_exchange_token=SHORT_LIVED_ACCESS_TOKEN
After these two months are over, the user must be the one to re grant access to the application giving a new short lived token which you can then re-extend using the code above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With