Facebook SDK 5 - reading feeds of a page - php

I am trying to read the posts of a facebook page, using the actual Facebook SDK 5 for PHP. I have created a facebook app, downloaded and "required" the SDK successfully, but I cannot get the request to run, since it always throws a Invalid OAuth access token signature exception.
The code I have so far:
$fb = new Facebook\Facebook([
'app_id' => $appid,
'app_secret' => $secret,
'default_graph_version' => 'v2.5'
]);
$accesstoken = file_get_contents("https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $appid
. "&client_secret=" . $secret
. "&grant_type=client_credentials" );
//following lines are something I just tried, there have been multiple
//Variantions, none ever worked
$cilent = $fb->getOAuth2Client();
$accessToken = $cilent->getLongLivedAccessToken($accesstoken);
All in all my main issues are:
how to get a valid access token? Since I just want to read public data (feeds of a page), I do not need some special permissons and I am quite confused which on Type of access token I need.
Are there any settings within the facebook app I need to make, or make sure, to get this up and running?
I have googled the web for examples, but I could find examples either using older SDKs (if used at all), or showing how to post data.
I do not have too much experience with that topic and I would appreciate some explanation, or a piece of example.
[UPDATE]
I could manage to get the feeds, some dive through the source was needed.
$fb = new Facebook\Facebook([
'app_id' => 'xxx',
'app_secret' => 'xxx',
'default_graph_version' => 'v2.5'
]);
$req = $fb->get(
'/<page-id>/feed?fields=full_picture,message,name,picture,story,posts&limit=20',
$fb->getApp()->getAccessToken());
In case of success everything one is looking for is included in $res. For sake of simplicity I removed the error handling.
Because everything is desinged to read public data, there is no need for any access-token huzzle, however, retrieving user Data, posting or something else, is not possible with this solution.
Cheers!

Related

Code using facebook php sdk stopped working suddenly - what happened?

I have an old piece of php code calling Facebook, that used to work fine until a week ago. Now it suddenly stopped working. Here are the relevant lines involved:
<?php
require_once __DIR__ . '/facebook-sdk-v562/autoload.php';
// -- skipping here less relevant lines --
// Initialize Facebook Environment:
$default_graph_version = 'v2.10';
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => $default_graph_version
]);
// Redirect to phase2 for facebook login:
$helper = $fb->getRedirectLoginHelper();
$fbPermissions = ['manage_pages', 'publish_pages'];
$loginUrl = $helper->getLoginUrl($phase2_url, $fbPermissions);
header('Location: ' . $loginUrl);
Now upon reaching the header line, I get: "Sorry, something went wrong. We're working on getting this fixed as soon as we can." -- I have a feeling (not sure) it has to do with using old versions of things? Has something changed in the recent days (May 2022)?
EDIT:
I've made certain updates in order to match new Graph API version. I used compose to download the new php sdk, I modified the require_once accordingly, and I modified v2.10 to v13.0. I still get the exact same error.
I checked the value of $loginUrl that gives me the error after redirection, and it is (shortened): https://www.facebook.com/v13.0/dialog/oauth?client_id=[***]&state=[***]&response_type=code&sdk=php-sdk-5.7.0&redirect_uri=[my correct url]&scope=manage_pages%2Cpublish_pages
I don't know why, but omitting the "permissions" argument to getLoginUrl altogether -- solved the issue.

How to automaticaly post on Facebook page with PHP

I'm trying to find solution for automatic posting to my funpage from PHP script, but without user prompt.
My usecase is quite simple - every friday there is event related with my funpage and I would like to post on site wall some information about it (loaded from database) using cron script written in PHP. I would like to use my account to do it.
I found a lot of articles related to autoposting but most of them are stale.
I created new FB application and few lines of code:
$fb = new \Facebook\Facebook([
'app_id' => '1897212530527861',
'app_secret' => $app_secret,
'default_access_token' => $app_access_token,
'default_graph_version' => 'v2.9',
]);
$params = [
'link' => 'www.myurl.com',
'message' => 'Info about the meeting',
];
$response = $fb->post('/my.funpage/feed', $params);
Currently I am reaching error:
The user hasn't authorized the application to perform this action
Might it be related to missing permissions in applciation configuration? I requested for publish_pages and manage_pages, but I can not review it while
there is message.

Facebook Graph API: retrieve basic profile information without access_token?

Just that, I'm reading the documentation and it's seems like you can get access to the basic information without auth. But i'm getting an error
the code
$fb = new Facebook([
'app_id' => '...',
'app_secret' => '...',
'default_graph_version' => 'v2.2'
]);
$response = $fb->get('/1000785'); // a valid ramdom user_id
and the response
Type: Facebook\Exceptions\FacebookSDKException
Message: You must provide an access token.
File: ...src/Facebook/FacebookRequest.php
So, should I need to implement the "classic" login anyway?
Ok, just to clarify this issue. It's enough just generating an app access token.
How to generate Facebook App Access Token?
Simply, concatenating app_id and app_secret with a pipe symbol.
$appAccessToken = $config['app_id'] . '|' . $config['app_secret'];
$response = $fb->get('/0123456789', $appAccessToken);
Cheers!

Facebook PHP SDK: Unknown path components

I'm trying to validate Facebook App ID and App Secret. With Graph Explorer, I'm able to use access token in shape of {APP_ID}|{APP_SECRET} to get app details on /v2.5/{APP_ID} endpoint.
It doesn't work with PHP SDK though. The error I'm getting is:
Unknown path components: /{APP_ID}
The code I used is this:
$facebook = new Facebook\Facebook( [
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => '2.5',
] );
$facebook->get( '/' . $app_id, $app_id . '|' . $app_secret );
It does the validation, because with invalid app ID I'm getting:
Error validating application. Cannot get application info due to a system error.
And with invalid secret:
Invalid OAuth access token signature.
How can I get the app details just like in graph explorer? I have no idea what I'm doing wrong, the request seems to be correct. Please help.
There is a typo in default_graph_version. It needs to be prefixed with v (standing for version), so the correct declaration is:
'default_graph_version' => 'v2.5',

how do you reuse fb access tokens after the redirect in php

I've just gotten started with the latest facebook SDK (5.0). It's been a number of years since I last used it, and there's one thing I can't seem to get around...
Following the example code they have here: https://developers.facebook.com/docs/php/howto/example_facebook_login/5.0.0
I'm able to get a perfectly working login. My problem is, how do you keep this login alive on the next page load when you aren't being redirected back from facebook?
you used to be able to store the user access token, then reuse that token to keep the session authenticated. In version 5.0 of the SDK, I'm not seeing a way to do that, and i'm pretty lost how you remain logged in.
I wouldn't be asking this here, but I've been looking for a couple days now and have found an abundance of articles using older code that doesn't line up with the current 5.0 sdk I'm trying to use. I'm guessing this is something small that I've been missing or over looking, but I'd love any information you guys can give me.
At the end of the exemple in the link you give, there is this line:
$_SESSION['fb_access_token'] = (string) $accessToken;, so the access token is stored in the PHP session and then accessible from page to page.
You can also store it in your database as a field in your users table.
Below great upgrade guides:
Facebook PHP SDK v3.x to v5.x
Facebook PHP SDK v4.0 to v5
I know it's too late but I just wanted to leave an answer as a record. From FB official doc:
Configuration options
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_access_token' => '{access-token}',
'enable_beta_mode' => true,
'default_graph_version' => 'v2.3',
'http_client_handler' => 'guzzle',
'persistent_data_handler' => 'memory',
'url_detection_handler' => new MyUrlDetectionHandler(),
'pseudo_random_string_generator' => new MyPseudoRandomStringGenerator(),
]);
If you don't provide a default_access_token in the configuration
options, or you wish to use a different access token than the default,
you can explicitly pass the access token as an argument to the get(),
post(), and delete() methods.
$res = $fb->get('/me', '{access-token}');
$res = $fb->post('/me/feed', ['foo' => 'bar'], '{access-token}');
$res = $fb->delete('/{node-id}', '{access-token}');

Categories