Displaying posts from owned facebook with the PHP SDK - php

So I admittedly am quite new to the facebook Graph api, but what I want to do feels like it should be doable.
All I want to do is display posts from a facebook page that is owned by me on a website.
Now I should say that I have achieved this with the api and the php sdk already, but its all of the access token stuff that is perplexing me, I just want a permanent access token so that I don't have to renew it in anyway.
Any help would be much appreciated

Just in case anyone landed on this question and was looking for direction on this subject too
$client = array(
"id" => {APP_ID},
"secret" => {APP_SECRET},
"token" => {ACCESS_TOKEN}, // Generated from the graph api explorer, with the 'manage_posts' extended permission ticked
"page" => {PAGE_ID}
);
FacebookSession::setDefaultApplication($client['id'], $client['secret']);
$session = new FacebookSession($client['token']);
try
{
$response = (new FacebookRequest($session, 'GET', '/oauth/access_token?grant_type=fb_exchange_token&client_id='.$client['id'].'&client_secret='.$client['secret'].'&fb_exchange_token='.$client['token']))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
$token = $data['access_token'];
$response = (new FacebookRequest($session, 'GET', '/'.$client['page'].'?fields=access_token'))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
echo "Access Token: ".$data['access_token']; // this is your never expiring access token
}
catch (FacebookRequestException $e) {
print_r($e);
}
catch (\Exception $e) {
print_r($e);
}
Obviously I do not recommend doing this in any form of production environment, but if you are in a local environment and just need the access token, feel free to use this to find out the access token.

Related

Facebook SDK 4 for PHP - no login grab some events

I try to use the Facebook SDK 4 for PHP,
but there is one thing that i don't understand : use it with an app access token!
i tried different tokens to initialize FaceBookSession, but i don't understand how it works... :/
with this sample code for example :
$request = new FacebookRequest(
$session,
'/480602392011337/events?fields=id,end_time,description,is_date_only,location,name,start_time&since='.date('Y-m-d',strtotime('-1 year')).'&until='.date('Y-m-d',strtotime('+1 year')).'&limit=500',
//'/480602392011337/events',
'GET'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
Thanks for the help! :)
I finally found the solution (thx Google), simply use FacebookSession::newAppSession();
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication('xxxxxx','xxxxxxx');
// Get the access token for this app
$session = FacebookSession::newAppSession();
// make the API call, $datas contains the events for the facebook fan page BDE Polytech Marseille
try {
$request = new FacebookRequest(
$session,
'GET',
'/{page-id}/events?fields=id,end_time,description,is_date_only,location,name,start_time&since='.strtotime('-1 year').'&until='.strtotime('+1 year').'&limit=500'
);
$response = $request->execute();
$datas = $response->getGraphObject()->asArray();
}catch (FacebookRequestException $e) {
echo $e->getMessage();
}catch (\Exception $e) {
echo $e->getMessage();
}

Check if already logged to facebook with PHP SDK 4.0

I want to check if already logged in to facebook when navigating to index.php so I would automatically redirect to homepage.
However, my code will only check after clicking on the loggin link.
Facebook\FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("myurl");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
header("location:home.php");
} else {
// show login url
echo 'Login';
}
I checked some other thread about Facebook PHP SDK but there is not much about sdk 4.0. And nothing that worked for me..
I tought I could add a token in the session, however it wouldn't work if I would already be logged in to facebook before my first visit... It would also cause problem if I would logout from facebook without logout from my website.
Since I found this question to be frequently asked without answer, I decided to share what I did with the community.
The $session variable in my code contains an access token which can be used for re-instanciating the session anywhere else simply doing a new FacebookSession('token').
Considering that, when logging in for the first time, I retrieve the token from the $sessionand store it in $_SESSION. Then, I created a simple util function which first check if the $_SESSIONvariable is set, then try to instanciate a new FacebookSession using the stored token. If the stoken is invalid, the session won't instanciate then I can detect it in my util function and return wether the user is actually logged in or not.
Note that an access token is invalidated when facebook user logout.
Login url + token storage :
FacebookSession::setDefaultApplication(Globals::FB_APP_ID, Globals::FB_APP_SECRET);
$helper = new Facebook\FacebookRedirectLoginHelper("http://localhost/PoubellesDeMerde/PoubellesDeMerde/index.php");
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (Exception $ex) {
// When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$_SESSION['token'] = $session->getToken();
} else {
// show login url
echo 'Login';
}
Util function :
public static function isLoggedIn()
{
$id=0;
if(isset($_SESSION['token']))
{
$session = new FacebookSession($_SESSION['token']);
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
$id = $graphObject->getProperty("id");
}
return $id!=0;
}

Facebook: "This authorization code has been used.","type":"OAuthException","code":100

I just upgraded to PHP 5.4.19 and facebook-php-sdk-v4.
Is it just me or has FB made the integration deliberately difficult?! For instance, I don't use Composer (can't install it on my shared host) so loading the new classes required a specific (discover-for-yourself) ordering - that was enough headache! The suggested solution at http://metah.ch/blog/2014/05/facebook-sdk-4-0-0-for-php-a-working-sample-to-get-started/ wasn't completely correct.
Anyway, when I finally got it to run and enabled "App Secret Proof for Server API calls" under the
App advanced settings tab as recommended by Facebook I got into a catch 22.
This is it:
1) To make an FB API call from my server, e.g. $request = new FacebookRequest($session, 'GET', '/me'); I must now provide an appsecret_proof argument.
2) To create an appsecret_proof I need an access_token i.e. $appsecret_proof= hash_hmac('sha256', $access_token, $app_secret);.
3) To get an access_token with only $_GET['code'] at this point, I must do code exchange via
GET https://graph.facebook.com/oauth/access_token?
client_id={app-id}
&redirect_uri={redirect-uri}
&client_secret={app-secret}
&code={code-parameter}.
4) To call FB for code exchange I get the error {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}.
Two questions arise therefore:
1) How else can I get an access_token except via code exchange, so that I can use that token to create an appsecret_proof and in turn call FacebookRequest?
2) Where/How do I put that appsecret_proof into FacebookRequest? Is it perhaps this way $request = new FacebookRequest($session, 'GET', '/me', array("appsecret_proof" => $appsecret_proof));? I cannot seem to find the specific instruction on how to use appsecret_proof with PHP API (it is clear how to do it via http with Graph API).
Ladies and Gentlemen, I resolved it all - I just needed to use $access_token = $session->getToken();. This helped me negate the call for code exchange which was causing OAuthException because Facebook has since changed their policy on the exchange code from being used more than once.
Now "App Secret Proof for Server API calls" is properly enabled under the App advanced settings tab as recommended by Facebook.
So the specific solution in complete:
$app_id = 'APPID'; $app_secret = 'APPSECRET';
FacebookSession::setDefaultApplication($app_id, $app_secret);
$redirect_url = "https://mydomain.com/login";
$helper = new FacebookRedirectLoginHelper($redirect_url);
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
} catch (Exception $ex) {
}
if (isset($session)) {
$access_token = $session->getToken();
$appsecret_proof = hash_hmac('sha256', $access_token, $app_secret);
$request = new FacebookRequest($session, 'GET', '/me', array("appsecret_proof" => $appsecret_proof));
$response = $request->execute();
$graphObject = $response->getGraphObject();
echo print_r($graphObject, 1);
} else {
echo 'Login';
}

facebook php sdk - catch if user didnt give permissions (authentication failed)

Documentation says:
"redirect_uri - (optional) The URL to redirect the user to once the login/authorization process is complete. The user will be redirected to the URL on both login success and failure, so you must check the error parameters in the URL as described in the authentication documentation. If this property is not specified, the user will be redirected to the current URL (i.e. the URL of the page where this method was called, typically the current URL in the user's browser)."
So there is a method to catch if user refused autnentication/permissions, but link to corresponding documentation doesnt exist anymore (https://developers.facebook.com/docs/authentication/).
For the simplicity, redirect_uri is same address as a starting php file, and the php code is as simple as:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'X',
'secret' => 'Y',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user) {
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'http://myapp.com/app'
);
$loginUrl = $facebook->getLoginUrl($params);
}
Anybody knows how to catch that information?
You can do following to check the permissions:
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
// Do the related task
$post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
} else {
// We don't have the permission
// Alert the user or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
It should be noted that in the newest PHP facebook SDK, there is no method ->api. There also seems to be an issue using this check (sometimes) to get permissions. When using the older SDK, sometimes (randomly by user it seemed) some users were getting "OAuthException: (#412) User has not installed the application" even though a check on the FB access token debugger showed proper permissions. After I updated to new SDK, and figured out the new way to get a simple data list of permissions, everything worked again.
It took me a lot of digging in the FB website to find this solution, so I paste it here to hopefully save somebody else a few hours. They real life saver was my discovery of the getDecodedBody method (a very hard to find trick in FB docs). My example just checks for publish_actions.
$fb = new Facebook\Facebook([
'app_id' => your_app_id,
'app_secret' => your_secret,
'default_graph_version' => 'v2.2',
]);
$badperms=true; //start by assume bad permissions
try {
$response = $fb->get('/me/permissions', $at);
$perms = $response->getDecodedBody();
if($badperms){
foreach($perms['data'] AS $perm){
if($perm['permission']=='publish_actions' && $perm['status']=='granted') $badperms=false;
}
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
log("MSG-received facebook Response exception!! ".$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
log("MSG-received facebook SDK exception!! ".$e->getMessage());
}
if($badperms) {
//do something like reflow auth
}
I just had the same issue, I didn't know how to treat the cancel action (both in facebook php api and google oauth2).
The solution is much easier than expected.
The response in case of permission not accepted (at all) comes with at least one parameter/variable: error in the URL.
In facebook that response looks like:
error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied
for google you only get the
error=access_denied
but it should be enough.
I'm just checking if error is set and if it's set I am redirecting the response to my login page.
I hope it will help someone because it's really not documented this step.
By the way:
version of facebook API: v5
version of google API oAuth2: 2.0 (i think - google doc is really a mess when it comes to finding the latest versions)

Creating new list on Etsy

I am trying to create a new listing on Etsy.
I used oauth to authenticate and got
OAUTH_CONSUMER_KEY
and
OAUTH_CONSUMER_SECRET
I check it with this code and I got return og all the seller data, so everything is ok with the OAuth.
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken("key","secret");
try {
$data = $oauth->fetch("http://openapi.etsy.com/v2/users/__SELF__", null, OAUTH_HTTP_METHOD_GET);
$json = $oauth->getLastResponse();
print_r(json_decode($json, true));
} catch (OAuthException $e) {
error_log($e->getMessage());
error_log(print_r($oauth->getLastResponse(), true));
error_log(print_r($oauth->getLastResponseInfo(), true));
exit;
}
I am trying to crate a new listings. First i managed to create a new listing through the api browser on the production. Now, i want to create a new listing through PHP. This is what i did, and it return my error:
This is my code:
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken("key","secret");
try {
$url = "http://openapi.etsy.com/v2/listings";
$params = array('description' => 'thisisdesc','materials' => 'yes','price'=>"5.99"
,'quantity'=>"2",'shipping_template_id'=>"52299",'shop_section_id'=>"1"
,'title'=>"thisistitle",'category_id'=>"i_did",'who_made'=>"5.99"
,'is_supply'=>"1",'when_made'=>"2010_2012");
$oauth->fetch($url, $params, OAUTH_HTTP_METHOD_POST);
print_r(json_decode($json, true));
} catch (OAuthException $e) {
print_r($e);
error_log($e->getMessage());
error_log(print_r($oauth->getLastResponse(), true));
error_log(print_r($oauth->getLastResponseInfo(), true));
exit;
}
I get the response of:
Invalid auth/bad request (got a 403, expected HTTP/1.1 20X or a redirect)
This method not accessible to restricted API key.
If you are still developing your application you can create listings without gaining full API access, so long as the shop is on your account. Make sure you parse in listings_w as a permission scope when making the first OAUTH request. I have altered the example provided by ETSY in the code below.
// instantiate the OAuth object
// OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET are constants holding your key and secret
// and are always used when instantiating the OAuth object
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
// make an API request for your temporary credentials
$req_token = $oauth->getRequestToken("https://openapi.etsy.com/v2/oaut/request_token?scope=email_r%20listings_r%20listings_w", 'oob');
print $req_token['login_url']."\n";`
Notice the scope=email_r%20listings_r%20listings_w;
Hope this helps
Aha, here's the answer. From an Etsy developer:
Your API was not yet approved for full API access. I've fixed that, so you should be able to use those methods now.
Hence, get in touch with the firm, and ask for your key to be approved.

Categories