Skip to content

Instantly share code, notes, and snippets.

@reactmore
Created October 9, 2020 09:41
Show Gist options
  • Save reactmore/a8752200c032ef6fb8c252f294d25f00 to your computer and use it in GitHub Desktop.
Save reactmore/a8752200c032ef6fb8c252f294d25f00 to your computer and use it in GitHub Desktop.
Auto POST Facebook API
public function facebook_share() {
//---------------------------------------------------
// Call Facebook SDK
// GET : https://github.com/facebookarchive/php-graph-sdk
require_once APPPATH . "third_party/facebook/vendor/autoload.php";
//---------------------------------------------------
// GET TOKEN
// https://developers.facebook.com/tools/explorer/
// As you can see, currently this is set to ‘Graph API Explorer’. Select your Facebook App instead. Now click the ‘get token’ button which you can also see in the image above. Select ‘Get User Access Token’ and make sure the ’publish_pages’, ‘manage_pages’ and ‘publish_actions’ permissions are ticked, then click the ‘Get Access Token’ button. Now click the ‘get token’ button again and select your Facebook page. You now have your Access Token which we need to convert into the non-expiring Access Token.
// Get a non-expiring Access Token for your App:
// To do so, pass your App ID, App Secret and Access Token into the following URL:
// https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=your_app_id&client_secret=your_app_secret&fb_exchange_token=token_from_graph
// Get Token Access respon and paste to $pageaccesstoken
$pageAccessToken ='non-expiring_Access_Token';
//---------------------------------------------------
// GET CONFIGURATION
// https://developers.facebook.com/tools/explorer/
$fb = new \Facebook\Facebook([
'app_id' => 'YOUR_APP_ID',
'app_secret' => 'YOUR_APP_SECRET',
'default_graph_version' => 'v2.10',
]);
// And Post property to Facebook
$linkData = [
'link' => 'www.google.com',
'message' => 'Your Message Post,
];
//---------------------------------------------------
// Documentation : https://developers.facebook.com/docs/graph-api/reference/v8.0/page/feed#publish
//---------------------------------------------------
try {
$response = $fb->post('/me/feed', $linkData, $pageAccessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: '.$e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: '.$e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment