2

i searched for 2 days about my problem find a lot of solution but none worked for me. I want to make a facebook application that i will access from cronjob once for 20 minutes. This app shoult post to my page a photo with description in a album. The problem is the token access that expires ... so the code ...

//connect to api
$facebook = new Facebook(array(
          'appId'  => APP_ID,
          'secret' => APP_SECRET
        ));

//get the page token
$page_id = 222506244512259;
$page_info = $facebook->api("/$page_id?fields=access_token");

$page_info['access_token']; //so if i use this token is ok but it expires in 2 hours

//now we try to use something else to extend the time

$token_url="https://graph.facebook.com/oauth/access_token?client_id=".APP_ID."&client_secret=".APP_SECRET."&grant_type=fb_exchange_token&fb_exchange_token=".$facebook->getAccessToken();

//so if i use this formula i will receive a token that never expires, is ok but if I try to use the acces token for posting it doesn work is not valid

$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$page_info['access_token'] = $params['access_token'];


//and this is the rest code for posting

$image['file'] = 'images/rezultate/'.$link;
$args = array( 'access_token' => $page_info['access_token'], 'message' => ':-) <3', 'no_story' => 0);
$args['image'] = '@' . $image['file'];
$target_url = "https://graph.facebook.com/356048711158011/photos";

$ch = curl_init(); 
curl_setopt ($ch,CURLOPT_URL,$target_url); 
curl_setopt ($ch, CURLOPT_POST, 1); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_exec($ch); 
curl_close ($ch);

I updated the code but still not working, maybe you some something wrong...

define('TITLU', 'Postare automată'); //titlu aplicatie
define('APP_ID',123096994520827); //id aplicatie
define('APP_SECRET', '25dedb6a969e9bd934e1ea9f16944a83'); //secret aplicatie
define('TABEL', 'postareautomata'); //numar random maxim


//start facebook
$facebook = new Facebook(array(
      'appId'  => APP_ID,
      'secret' => APP_SECRET
));

//get page id and 2 hour page token
$page_id = 222506244512259;
$page_info = $facebook->api("/$page_id?fields=access_token");
//access token 2 hours
$page_info['access_token'];

//here i get my account but for nothing
$acc = $facebook->api("/100001036884257/accounts");
//echo var_export($acc, true);


//here i get the long token it returns a code value but when i used down don`t work
$longtoken = 'https://graph.facebook.com/oauth/access_token?client_id='.APP_ID.'&client_secret='.APP_SECRET.'&grant_type=fb_exchange_token&fb_exchange_token='.$facebook->getAccessToken();     
$response = file_get_contents($longtoken);
$params = null;
parse_str($response, $params);
$longtoken = $params['access_token'];

echo"Acces Token short: ".$page_info['access_token'];
echo"<br />Acces Token long: ".$longtoken;

//here i get my folder picture and pictures
$a = file_get_contents('http://www.ingersidemon.ro/proiecte/pitzi-world.ro/.facebook/postareautomata/images/rezultate/');
$dom = new DOMDocument;
$dom->loadHTML($a);
$nodes = $dom->getElementsByTagName('a');
$nrpoze = $dom->getElementsByTagName('a')->length - 1;
$picid = get_last_picture();
$link = $nodes->item($picid['id'] + 1)->getAttribute('href');
//echo "Link poza: ".$link;



if($picid['id'] + 1 <= $nrpoze) {
    $data = array(
        'link' => $link,
        'desc' => ':-) <3'
    );
    insert_picture($data);
//and here is the bog problem if i use short acces token it works for 2 hours but the long never work
    $params = array('access_token' => '$longtoken', 'message' => ':-) <3');
    $params['source'] = '@' . realpath('images/rezultate/'.$link);
    $facebook->setFileUploadSupport(true);
    $post_id = $facebook->api('/'.$page_id.'/photos','post',$params);

}

Update 3: The app is working good but only if i acces it, not from cronjob, and the acces token is for 2 months, in cronjob gives

PHP Fatal error: Uncaught OAuthException: A user access token is required to request this resource.

define('TITLU', 'Postare automată'); //titlu aplicatie
define('APP_ID',123096994520827); //id aplicatie
define('APP_SECRET', '25dedb6a969e9bd934e1ea9f16944a83'); //secret aplicatie
define('TABEL', 'postareautomata'); //numar random maxim

$facebook = new Facebook(array(
      'appId'  => APP_ID,
      'secret' => APP_SECRET
));


// Get User
$user = $facebook->getUser();


// ask for the extended token and get it from session ...
$facebook->setExtendedAccessToken();
$access_token = $_SESSION["fb_".APP_ID."_access_token"];
// now set it into the facebook object ....
$facebook->setAccessToken($access_token);
// now our fb object will use the new token as usual ...
$accessToken = $facebook->getAccessToken();
echo $access_token;

$params = array(
                'access_token' => 'AAABv9MChnvsBAALtC4XoywkLdGQMzmJHYbN8G2RjgZCGlzR6DnkB8X12FZCE6XIZB81KkYevIYzC2pu5UvVZBoOFvw8j0cgjLeHcwvcOpwZDZD',
                'message'=> "cron"
        );
    $post_id = $facebook->api('/'.$page_id.'/feed','post',$params);
user1910532
  • 35
  • 1
  • 11

4 Answers4

0

Use a App Token found in Access Token Tool.

Emil Aspman
  • 996
  • 1
  • 17
  • 26
0

The normal access token expires in 2 hours, and the extended token lasts for 2 months.

If you want the extended token, go though this: How to extend access token validity since offline_access deprecation

(You can use Facebook's Debug Tool to check the validity of your access token.)

Community
  • 1
  • 1
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
  • Thank you, I already used this funcion, it gives me the long acces token but when i used as param to $post_id = $facebook->api('/'.$page_id.'/photos','post',$params); [18-Dec-2012 11:37:02] PHP Fatal error: Uncaught OAuthException: A user access token is required to request this resource. thrown in /home/ingersid/public_html/proiecte/pitzi-world.ro/.facebook/postareautomata/base_facebook.php on line 1249 [18-Dec-2012 11:37:03] CSRF state token does not match one provided. You can see the code up. – user1910532 Dec 18 '12 at 10:57
  • Have you asked for the "publish_stream" permission ? – Sahil Mittal Dec 18 '12 at 11:13
  • If I use cronjob how to ask? i set now if (!$user) { echo $loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream,offline_access', 'redirect_uri' => 'https://apps.facebook.com/apppostauto/')); //login url for offline access } – user1910532 Dec 18 '12 at 11:55
  • You don't need to validate the user while using the cron, if you have the extended token. If the user has permitted for the publish_actions at any time before, just use his extended_access_token in your cron and post. This will definitely work. – Sahil Mittal Dec 18 '12 at 12:13
  • Hello, I updated the post please go to update 3 ... is ok? and cron doesn„t work only if i acces manualy. – user1910532 Dec 18 '12 at 12:31
  • did you followed what i said in the above comment? Also, don't use the offline_access permission, it has been removed now. Simply use the extended_token as I said. https://developers.facebook.com/roadmap/offline-access-removal/ – Sahil Mittal Dec 18 '12 at 12:45
  • Sorry, i am a little confuse extended_access_token should be a function? This?:https://graph.facebook.com/oauth/access_token? client_id=APP_ID& client_secret=APP_SECRET& grant_type=fb_exchange_token& fb_exchange_token=EXISTING_ACCESS_TOKEN – user1910532 Dec 18 '12 at 12:57
  • Choose proper sender and receiver: $facebook->api('/'.$RECEIVER_ID.'/feed','POST',$params); $params = array( 'access_token' => $["SENDER_EXT_TOKEN"], ....); – Sahil Mittal Dec 18 '12 at 12:58
  • Thank you i was deleted page id variable, now trying to post to page. – user1910532 Dec 18 '12 at 13:01
  • Ok the cron and manualy acces the app, the only succes post is from manyaly. now i am verry confused, so please help me take from 0. Now i have to get a good token from cron, what shoul i use? – user1910532 Dec 18 '12 at 13:06
  • just run the cron with the above mentioned code. This will post the Feed on the page on behalf of the 'SENDER'. What is unclear to you? – Sahil Mittal Dec 18 '12 at 13:14
  • It doesnt post. Only if i as a person acces the app post, from cron doesnt post. as a error in cron i receive wich is already set. if you want me to help is it ok to give here my skype id, and i pay you. i hope i dont violate the rules from stackoverflow. – user1910532 Dec 18 '12 at 13:21
0

See my answer to a similar question here

From the developers page:

By using a long-lived user access token, querying the [User ID]/accounts endpoint will now provide page access tokens that do not expire for pages that a user manages.

Community
  • 1
  • 1
Pete
  • 10,720
  • 25
  • 94
  • 139
  • Thank you, so i used the all code from here: https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/ where to me $access_token = $facebook->getAccessToken(); and i receive: Curent token: AAABv9MChnvsBACTlYqcLNWXnrq5QwlwqPKZAQPDZBFnllrNFyywBOZAdZCn3yl91zJznZAuWNjWHHlo1NfY3r0WXr2VZBQg76XLTM3lg4mDQNmIbTuvuzZALKRXcMUQTCcZD And the succes long token from facebook code wich lives 2 months: AAABv9MChnvsBAALtC4XoywkLdGQMzmJHYbN8G2RjgZCGlzR6DnkB8X12FZCE6XIZB81KkYevIYzC2pu5UvVZBoOFvw8j0cgjLeHcwvcOpwZDZD All is good but when i use the token as a param to post error. – user1910532 Dec 18 '12 at 09:42
  • [18-Dec-2012 11:37:02] PHP Fatal error: Uncaught OAuthException: A user access token is required to request this resource. thrown in /home/ingersid/public_html/proiecte/pitzi-world.ro/.facebook/postareautomata/base_facebook.php on line 1249 [18-Dec-2012 11:37:03] CSRF state token does not match one provided. – user1910532 Dec 18 '12 at 09:48
-1

Page tokens only last as long as the user access token used to acquire them. You can't have an infinitely lasting token. You need to be able to periodically renew your token and deal with tokens that unexpectedly expire. There is some more information in a FB blog post from last year.

AndrewF
  • 1,827
  • 13
  • 25
  • yes i know, there are tokens that expires in 2 months ... is ok for 2 moths but not 2 hours – user1910532 Dec 18 '12 at 00:46
  • Again, even the long-lived tokens can expire at _any time_ when the user token expires. That means it can potentially expire just a few seconds after it has been acquired. – AndrewF Oct 31 '18 at 21:44