From 16a32604f5f2459418dd94f31de499990f0dfb69 Mon Sep 17 00:00:00 2001 From: emkael Date: Wed, 24 Jan 2018 11:48:36 +0100 Subject: Tweaks to FB token auto-renewal --- bin/fb-user-token.php | 55 +++++++++++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 24 deletions(-) (limited to 'bin/fb-user-token.php') diff --git a/bin/fb-user-token.php b/bin/fb-user-token.php index 943bf4c..3aeb8aa 100644 --- a/bin/fb-user-token.php +++ b/bin/fb-user-token.php @@ -3,29 +3,36 @@ $basePath = dirname(__FILE__); $configFile = $basePath . '/../config/facebook.json'; -$config = json_decode(file_get_contents($configFile), TRUE); -$firstLink = - 'https://graph.facebook.com/oauth/client_code?' . - http_build_query([ - 'access_token' => $config['user_token'], - 'client_id' => $config['app_id'], - 'client_secret' => $config['app_secret'], - 'redirect_uri' => 'http://rss.emkael.info/facebook.php' - ]); -$firstResponse = json_decode(file_get_contents($firstLink)); - -$secondLink = - 'https://graph.facebook.com/oauth/access_token?' . - http_build_query([ - 'client_id' => $config['app_id'], - 'code' => $firstResponse->code, - 'redirect_uri' => 'http://rss.emkael.info/facebook.php' - ]); -$secondResponse = json_decode(file_get_contents($secondLink)); - -$config['user_token'] = $secondResponse->access_token; - -print json_encode($config); -fwrite(STDERR, 'FB API token renewed, expires on: ' . date('Y-m-d H:i:s', strtotime('+' . $secondResponse->expires_in . ' seconds')) . PHP_EOL); +$expiryFile = $basePath . '/fb-user-token-expiry'; + +if (!file_exists($expiryFile) || trim(file_get_contents($expiryFile)) == date('Y-m-d')) { + + $config = json_decode(file_get_contents($configFile), TRUE); + $firstLink = + 'https://graph.facebook.com/oauth/client_code?' . + http_build_query([ + 'access_token' => $config['user_token'], + 'client_id' => $config['app_id'], + 'client_secret' => $config['app_secret'], + 'redirect_uri' => 'http://rss.emkael.info/facebook.php' + ]); + $firstResponse = json_decode(file_get_contents($firstLink)); + + $secondLink = + 'https://graph.facebook.com/oauth/access_token?' . + http_build_query([ + 'client_id' => $config['app_id'], + 'code' => $firstResponse->code, + 'redirect_uri' => 'http://rss.emkael.info/facebook.php' + ]); + $secondResponse = json_decode(file_get_contents($secondLink)); + + $config['user_token'] = $secondResponse->access_token; + + fwrite(STDERR, 'FB API token renewed, expires on: ' . date('Y-m-d H:i:s', strtotime('+' . $secondResponse->expires_in . ' seconds')) . PHP_EOL); + file_put_contents($configFile, json_encode($config)); + file_put_contents($expiryFile, date('Y-m-d', strtotime('+' . $secondResponse->expires_in . ' seconds'))); + +} ?> -- cgit v1.2.3