I would like to get images from my Instagram account to my web page. So I try to use FB php sdk and get accessToken first according this documentation. But it returns null. I don't know what is wrong with the code.
public function getMedia()
{
$fb = new \Facebook\Facebook([
'app_id' => self::APP_ID,
'app_secret' => self::APP_SECRET,
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
$helper = $fb->getRedirectLoginHelper(); // Whichever helper I use access-token is null
dd($helper->getAccessToken());
}
I need help with it. It could be so simple.
EDIT:
After few hours I have this, but the last command throws an Facebook\Exceptions\FacebookResponseException Invalid OAuth access token signature. As I see the token is app id and app secret joined with pipe. "733163597544229|xxxxxxxxxxxxx9d14362xxxx3a6". This should work but does not work.
public function getMedia()
{
$fb = new \Facebook\Facebook([
'app_id' => self::APP_ID_FB,
'app_secret' => self::APP_SECRET_FB,
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
$token = $fb->getApp()->getAccessToken();
$response = $fb->get('https://graph.instagram.com/me/media?fields=media_url,media_type', $token->getValue());
}
If I've understood the docs correctly, if you want to get an access token dynamically, according to https://developers.facebook.com/docs/facebook-login/web, you need enable fb-login for your app
https://developers.facebook.com/apps/
select your app
add fb-login & follow the tips.
Otherwise you should just be able to get an access token for your app from the web interface and use that over and over.
See also : https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
There's also:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Did%2Cname&version=v9.0
Which enables you to generate an access token, and test out a call to the graph api, AND allows you to export code you can copy/paste:
try {
// Returns a `FacebookFacebookResponse` object
$response = $fb->get(
'/me',
'{access-token}'
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
EDIT:
I see in your original question you state:
As I see the token is app id and app secret joined with pipe. "733163597544229|xxxxxxxxxxxxx9d14362xxxx3a6". This should work but does not work.
According to the docs, if you want to supply an access token as {app_id}|{client-token} (not sure what secret you're using here) you should append this to the URL, which is not in the URL you're using.
See example here: https://developers.facebook.com/docs/facebook-login/access-tokens#clienttokens
The URL they use is:
curl -i -X GET "https://graph.facebook.com/{your-user-id}/accounts?access_token={user-access-token}
So for you this be:
$response = $fb->get('https://graph.instagram.com/me/media?fields=media_url,media_type&access_token=733163597544229|{client_token}');
EDIT 2:
I managed to get your sample working so perhaps these screen shots will help:
PHP Code:
<?php
$accessToken="EAAJIZAj**************************************************************************************************************************************************************************ZD";
require_once __DIR__ . '/Facebook/autoload.php'; // change path as needed
//echo __DIR__ . '/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '642**********502',
'app_secret' => '0185*****************f743',
'default_graph_version' => 'v2.10',
'default_access_token' => "{$accessToken}"
]);
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me');
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
?>
I took the source code from https://github.com/facebookarchive/php-graph-sdk and copied the src/Facebook dir into my project. I amended the path location in my code
require_once __DIR__ . '/Facebook/autoload.php'; // change path as needed
//echo __DIR__ . '/Facebook/autoload.php'; //<< comment out everything else and check the path is correct with this.
Working code: (same as above) with successful output shown at the bottom of the screen shot.
If you need to get the app secret go to the apps settings to uncover it:
Seems you were right - the access token does have an expiry and I had to refresh mine since using it yesterday.
As far as I know this will probably not work to get the access token .
To get access token you need to implement the login with facebook in your app to get the access token . If your app is only used by limited user then you can get access token on this link https://developers.facebook.com/tools/explorer/ but if your app is used by wide range of user and each user has their own data then you need to implement oauth2 in your app
Related
I have a facebook login button on a site, which used to work. I haven't changed anything as far as I know, but now it just gives a Not Found error:
The requested URL /https://www.facebook.com/v3.0/dialog/oauth was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Not sure if it would help, but this is in my fbConfig.php file:
require_once __DIR__ . '/facebook-php-sdk/autoload.php';
// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
//some code to set the correct $appId and $appSecret that developers.facebook gave me
$redirectURL = $url; //Callback URL
$fbPermissions = array('email'); //Optional permissions
$fb = new Facebook(array(
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v3.0',
));
// Get redirect login helper
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
// Try to get access token
try {
if(isset($_SESSION['facebook_access_token'])){
$accessToken = $_SESSION['facebook_access_token'];
}else{
$accessToken = $helper->getAccessToken();
}
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
A cursory glance at The PHP Docs indicates the current default_graph_version version is v2.2. So that means 1 of 2 things:
You're using a version that doesn't exist
You're using a beta version which is caveat emptor
Try bringing the version back to v2.2 and seeing if it works. Also ensure you're using an up-to-date, unmodified, official version of their SDKs.
I am struggling going round in circles getting an Facebook App to post to a Page's Wall, as that Page.
** Note: I put out a 300 point bounty to update an outdated answer of a related, well-viewed, existing question. Happy to award anyone who also answers there with the updated, working, solution
In brief:
I have the App Secret and ID
I have Page ID
I am relying on an in-code approach to generating the token I need.
It is based on a solution I saw posted on the SDK GitHub page but it does not work
I am using API v 2.9
I am using the latest PHP SDK
It's just been hard.
The solution I used is purely based on the one below:
<?php
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__ . '/Facebook');
require_once __DIR__ . '/Facebook/autoload.php';
use Facebook\FacebookRequest;
$app_id = {{your app-id}};
$app_secret = {{your app-secret}};
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => '{{your app-version}}',
]);
$token = $fb->get(
'/oauth/access_token?client_id=' . $app_id . '&'.
'client_secret=' . $app_secret . '&'.
'grant_type=client_credentials');
$get_token = $token -> getdecodedBody();
$access_token = $get_token['access_token'];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/{{your facebook name}}', $access_token);
} 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;
}
$body = $response->getBody();
print_r($body);
?>
I am certainly not lazy. I have been stuck on this issue for weeks.
I have tried the following different solutions and have gotten stuck in either a permissions related issue that was also related to depracated functionality and API calls or getting the right token to do it.
Posting to a facebook page from a website using curl (using a pure CURL approach - "The user hasn't authorized the application to perform this action")
Facebook SDK returned an error: You must provide an access token. Php Facebook Api - (suggests that I support login and redirection callback - yet I do not want any user intervention everytime when posting onto the page)
Graph returned an error: Invalid appsecret_proof provided in the API argument - Previous attempt was based on this example but the appsecret-proof issue
Simple example to post to a Facebook fan page via PHP? - Another CURL-based approach that failed me
https://stackoverflow.com/a/14212125/919426 - Best explained step by
step process for permissions and tokens, but still failed
Update:
Tried the following and got the error "Invalid appsecret_proof provided in the API argument"
$fb = new Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.9',
]);
$postData = [
'message' => "Test Message",
'picture' => 'https://www.website.com/image.jpg'
];
try
{
// 'LONG_LIVED_PAGE_ACCESS_TOKEN' obtained by going to https://developers.facebook.com/tools/debug/accesstoken and clicking
// "Extend Access Token"
$response = $fb->post('/' . 'PAGE_ID' . '/feed', $postData,"LONG_LIVED_PAGE_ACCESS_TOKEN");
}
catch (FacebookResponseException $e)
{
var_dump("Facebook Response Exception occured: \n" . $e);
exit;
}
catch(FacebookSDKException $e)
{
var_dump("Generic Facebook SDK Exception occured: \n" . $e);
exit;
}
catch(Exception $e)
{
var_dump("Uknown Exception occured while attempting to call the Facebook SDK API: \n" . $e);
exit;
}
There are countless more that I have tried and failed.
I have am using FB's Javascript SDK on the client and PHP SDK on the server.
I can see when I use getSignedRequest() I get the signed request containing the code property and the correct userId. However for the life in me I can't figure out how to go on to use this signedRequest to obtain a valid access token which I can use to create further calls for things like user information. I have tried querying for the access code by attempting to instantiate a signed request or calling the ->getAccessToken() method on the $facebook object as well as the jsHelper object but nothing is returned to me. Here's my code:
require_once 'src/autoload.php';
$facebook = new Facebook\Facebook([
'app_id' => $AppId,
'app_secret' => $AppSecret,
'default_graph_version' => 'v2.8',
]);
$jsHelper = $facebook->getJavaScriptHelper();
$signedRequest = $jsHelper->getSignedRequest();
if ($signedRequest) {
try {
$codeField = $signedRequest->get('code');
$g = $facebook->getAccessToken();
//I would hope this would be the access token, but sadly it's an empty
value.
error_log($g);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
error_log("fbResp Ex: ". $e->getMessage());
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
error_log("SDK Ex: ". $e->getMessage());
exit;
}
I never used JavaScriptHelper but AccessToken comes from helper not Facebook object itself. Try
$g = $jsHelper->getAccessToken();
I have been stumped for a while now. I'm attempting to write myself a small app to automatically post to a number of groups that I am members of in FB. I'm a PHP novice, but this is about my strongest skill set for what FB allows in terms of access that I can tell. So far, I CAN post to my own wall no problem but once I try and post to my own FB testing group I'm stumped. Here is my code so far...
<?php
require_once __DIR__ . '/vendor/autoload.php';
require 'src/config.php';
require 'src/facebook.php';
$fb = new Facebook\Facebook([
'app_id' => $config['App_ID'],
'app_secret' => $config['App_Secret'],
'default_graph_version' => 'v2.8',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'Test post to my feed.',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/{group_id}/feed', $linkData, $config['Access_Token']);
} 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;
}
?>
Currently the error that this is generating is:
Graph returned an error: (#200) Insufficient permission to post to target on behalf of the viewer
I have made the app Public and generated the access token with manage_pages and publish_pages. Unfortunately I'm out of ideas as of this point. Any help would be greatly appreciated. Thanks in advance.
OK. I figured out my problem at this point. It was that I had to go into the App Settings in my FB user account and change my App from "Only Me" to Public. Once I did that I was able to post to my groups. Next will be to figure out how to post into the proper fields for a "Sell Something" type of post and then to test it in groups that I'm not an admin of.
I figure it has to be possible to post into non-admin groups since there are a number of services out there for FB auto-posting and they have to get around it somehow.
I've been trying to implement the Facebook OAuth SDK for the past couple of days but keep running into a weird broken link error.
I have followed their instructions on the facebook SDK and used this code for login.php (???? to censor app ID and secret)
$fb = new Facebook\Facebook ([
'app_id' => '????????????????',
'app_secret' => '????????????????',
'default_graph_version' => 'v.2.4'
]);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('http://url.ca/login-callback.php');
This redirects to the login-callback.php file which is what Facebook recommends. Using their provided template code for login-callback.php, mine looks like this:
<?php
session_start();
require_once 'src/Facebook/autoload.php';
//Create the Facebook service
$fb = new Facebook\Facebook ([
'app_id' => '????????????????',
'app_secret' => '????????????????',
'default_graph_version' => 'v.2.4'
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
// Logged in!
$_SESSION['facebook_access_token'] = (string) $accessToken;
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
}
?>
But after being redirected from login.php (clicking on the a href element), I arrive at this:
Sorry, this page isn't available
The link you followed may be broken, or the page may have been removed.
On the Facebook page, no prompt to login, no nothing. I've made my app public already and added this Url to the app as well as ensuring OAuth is enabled, but nothing seems to be working. Does anyone with experience using Facebook OAuth have any idea what's going on?
Is that 'v.2.4' a typo in your question?
The string used in the API should be v2.4 - if you have an extra '.' it's linking you to a URL similar to the real URL of the login dialog, but with an invalid version number in the path