I am using facebook apis to post on my testing account using php. The following code does the job for me and it works. If I log in with my account I can see the post, but if I use another account the post does not show. I have modified the privacy setting to public but still. I went to facebook's documentation,but I couldn't really find something to solve my problem. Can anyone help???
Thanks in advanced
function fb_post($post, $msg, $url, $pic) {
$temp_array = queryFBTable($post);
if (count($temp_array) == 0) return;
// initialize Facebook class using your own Facebook App credentials
// see: https://developers.facebook.com/docs/php/gettingstarted/#install
$config = array();
$config['appId'] = 'xxxxxxxxxxx';
$config['secret'] = 'xxxxxxxxxxxxxxxx';
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
// define your POST parameters (replace with your own values)
// see: https://developers.facebook.com/docs/facebook-login/access-tokens/
$params = array();
if(isset($temp_array['AccessToken'])) {
$params['access_token'] = $temp_array['AccessToken'];
}
if(isset($msg)) {
$params['message'] = $msg;
}
if(isset($url)) {
$params['link'] = $url;
}
if(isset($pic)) {
$params['picture'] = $pic;
}
//"name" => "yooo",
//"caption" => "www.pontikis.net",
//"description" => "Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
// post to Facebook
// see: https://developers.facebook.com/docs/reference/php/facebook-api/
try {
//tim .. 1471145939793099
// van .. 1491737127730006
// mc .. 796523467054680
$ret = $fb->api("/".$temp_array['userID']."/feed", 'POST', $params);
echo "<br>Successfully posted to Facebook account ".$post.". <br/>";
}
catch(Exception $e) {
echo $e->getMessage();
}
}
Related
Is there some limitation with Fat Free Framework when we try to output the page into facebook tab?
I already try it with this below code, and unfortunately in the facebook tab iframe always empty blank page.
<?php
$f3=require('app/lib/base.php');
require_once 'app/lib/fb/facebook.php';
$f3->route('GET /',
function() {
echo 'Hello';
}
);
$f3->route('GET /landing',
function() {
$app_id = 'xxxx';
$secret_key = 'yyyy';
$page_id = 'zzzz';
$config = array(
'appId' => $app_id,
'secret' => $secret_key
);
$fb = new Facebook($config);
$fbdata = $fb->getSignedRequest();
$fbInPage = false;
if(!empty($fbdata) && is_array($fbdata)
&& !empty($fbdata['page']) && is_array($fbdata['page'])
&& !empty($fbdata['page']['id'])
) {
$fbInPage = $fbdata['page']['id'];
}
// Check if user not in fb tab
if(!$fbInPage) {
// Redirect to facebook tab
echo '<script>window.location.href="https://www.facebook.com/'.
$page_id.
'?sk=app_'.
$app_id.
'"</script>';
exit;
}
// Get User ID
$user = $fb->getUser();
// Check if user not connected to facebook
if ($user) {
try {
$user_data = $fb->api("/me");
} catch (FacebookApiException $e) {
$user_data = null;
}
} else {
// Asking permission for email and user_likes
$fb_login_url = $fb->getLoginUrl(array(
'scope' => 'email, user_likes'
));
echo '<script>top.location.href = "'.$fb_login_url.'"</script>';
exit;
}
}
);
$f3->run();
First when user try to access GET /landing it will redirect to facebook tab and show the page GET /. But somehow it always return empty page, already inspect it with firebug on firefox and there is no error, on the response tab always shows Reload the page to get source for: https://localhost/f3-fb/. Already try it with my office framework and works perfectly.
If anybody ever get this problem please advise.
The problem is in XFRAME, on default F3 set the XFRAME value as SAME-ORIGIN, based on this doc, developer must overload the value with ALLOW-FROM uri.
Here is the full code for index.php:
<?php
$f3=require('app/lib/base.php');
require_once 'app/lib/fb/facebook.php';
$f3->set('XFRAME', 'ALLOW-FROM https://localhost/f3-fb/');
$f3->route('POST /',
function() {
echo 'Hello';
}
);
$f3->route('GET /landing',
function() {
$app_id = 'xxxx';
$secret_key = 'yyyy';
$page_id = 'zzzz';
$config = array(
'appId' => $app_id,
'secret' => $secret_key
);
$fb = new Facebook($config);
$fbdata = $fb->getSignedRequest();
$fbInPage = false;
if(!empty($fbdata) && is_array($fbdata)
&& !empty($fbdata['page']) && is_array($fbdata['page'])
&& !empty($fbdata['page']['id'])
) {
$fbInPage = $fbdata['page']['id'];
}
// Check if user not in fb tab
if(!$fbInPage) {
// Redirect to facebook tab
echo '<script>window.location.href="https://www.facebook.com/'.
$page_id.
'?sk=app_'.
$app_id.
'"</script>';
exit;
}
// Get User ID
$user = $fb->getUser();
// Check if user not connected to facebook
if ($user) {
try {
$user_data = $fb->api("/me");
} catch (FacebookApiException $e) {
$user_data = null;
}
} else {
// Asking permission for email and user_likes
$fb_login_url = $fb->getLoginUrl(array(
'scope' => 'email, user_likes'
));
echo '<script>top.location.href = "'.$fb_login_url.'"</script>';
exit;
}
}
);
$f3->run();
Add the config $f3->set('XFRAME', 'ALLOW-FROM https://localhost/f3-fb/'); to allow this url inside on facebook iframe.
And always use POST for the route inside the facebook iframe (still don't know why must using that with F3, but it will occur the error and asking for POST route)
Users on my website can login to Twitter and post their status on my website and twitter at once. I'm using https://github.com/abraham/twitteroauth to connect to Twitter. Login and posting is performed on different pages of website.
This is login script:
public function loginTwitter() {
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret']
);
$request_token = $twitter->getRequestToken($this->link('//User:connectFromTwitter'));
// Saving to session (Nette Framework)
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitterSession->oauth_request_token = $token = $request_token['oauth_token'];
$twitterSession->oauth_request_token_secret = $request_token['oauth_token_secret'];
if ($twitter->http_code == 200) {
$requestLink = $twitter->getAuthorizeURL($token);
$this->redirectUrl($requestLink);
} else {
echo 'Error';
}
}
This is callback script (posting works right after user has been logged in):
public function twitterOauth() {
// $_GET parameter oauth_verifier
$oauthVerifier = $this->getParam('oauth_verifier');
// Session section
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->oauth_request_token,
$twitterSession->oauth_request_token_secret
);
$access_token = $twitter->getAccessToken($oauthVerifier);
$twitterSession->access_token = $access_token;
$user_info = $twitter->get('account/verify_credentials');
// Saving to DB to be able to post without login
$tm = new TwitterUserManager();
if (!$tm->isInDatabase($this->getUser()->getId())) {
$tu = new TwitterUser();
$tu->setUser($this->loggedUser);
$tu->setOauthProvider('twitter');
$tu->setOauthUid("'".$user_info->id."'");
$tu->setUsername("'".$user_info->screen_name."'");
$tu->setOauthToken("'".$access_token['oauth_token']."'"); // Saving the access token for further posting
$tu->setOauthSecret("'".$access_token['oauth_token_secret']."'");
$tm->persist($tu);
}
$twitter->post('statuses/update', array('status' => 'Hello ' . date('d.m.Y H:i:s'))); // <== HERE IT WORKS
$this->redirect('User:socialConnect'); // Redirect to another page
}
This is posting function (User posts from any page):
public function postToTwitter() {
$twitterSession = $this->getContext()->session->getSection('twitter');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->access_token['oauth_token'],
$twitterSession->access_token['oauth_token_secret']
);
return $twitter->post('statuses/update', array('status' => 'Hello' . date('d.m.Y H:i:s')));
}
When I use posting function I get this error:
stdClass(2) {
request => "/1/statuses/update.json" (23)
error => "Could not authenticate you." (27)
}
Thanks for help in advance.
EDIT: Solution:
Use this to connect to Twitter (save all info into DB):
http://framework.zend.com/manual/1.12/en/zend.oauth.introduction.html
Use this to post from any page:
http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
Nice example:
http://www.joeyrivera.com/2010/twitter-api-oauth-authentication-and-zend_oauth-tutorial/
I always used the Zend-Framework-Component: http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
I think it's simple and I could confirm, that it works. You just have to read through the tutorial (see link above).
Im really struggling w/ the OAuth for Khan Academy. This is for my class website (Im a teacher) and I want to pull in user data on particular students. If I could do the OAUTH I would be fine. Im using PHP.
There seems to be many librarys out there, I have been playing w/ Google Oauth (located here http://code.google.com/p/oauth-php/source/browse/trunk/example/client/twolegged.php)
I can formulate the token request fine, although when I call it in the script, it seems like it tries to redirect to another page and gets blocked there.
http://myonlinegrades.com/prealg/khan/oauth-php/example/client/twoleggedtest.php
Im really struggling - Id love any help you might offer.
Code below:
<?php
include_once "../../library/OAuthStore.php";
include_once "../../library/OAuthRequester.php";
// Test of the OAuthStore2Leg
// uses http://term.ie/oauth/example/
$key = '*********';//'<your app's API key>';
$secret = '***********';//'<your app's secret>';
$callBack = "http://myonlinegrades.com/prealg/test2.php5";
$url = 'http://www.khanacademy.org/api/auth/request_token';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "GET";
//$params = null;
$params = array(oauth_consumer_key => $key,oauth_callback=>$callBack);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method, $params);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response != 'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo 'Error! $response ' . $response;
}
else
{
}
var_dump($response);
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
?>
Not sure this is what you're looking for, but I put together a simple example of doing oAuth with Khan Academy using the Temboo SDK: take a look at https://github.com/matthewflaming/temboo-experiments/tree/master/KhanAcademyOauth
(Full disclosure: I work at Temboo)
I just managed to connect to the facebook PHP api. Facebook API tutorial seems really bad or at least poorly organized.
I realised I can get the logged in user's name with: <?php print_r($user_profile[name]); ?> since it's beforehand set as $user_profile = $facebook->api('/me'); . How do I print another user's name who is not logged in, knowing his UID, for example '2222'
How do I fetch user info, specifically name and UID?
Thanks
What user do you want to fetch ? You can fetch current user with /me. Before using the Facebook PHP API , you need to understand about Facebook graph api. It explain everything about Facebook api access url. So, you can call the graph URL in Facebook PHP SDK.
You can check sample source code from
https://github.com/facebook/php-sdk/
require './facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
<script>
FB.init({appId: <?php echo FACEBOOK_APP_ID;?>, status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.logout', function(response) {});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
FB.api('/me', function(response) {
if(response.id!='undefined')
{
window.location='Fbaccess.php?first_name='+response.first_name+'&last_name='+response.last_name+'&email='+response.email;
}
else
{
window.location='login.php';
}
});
} else {
// The user has logged out, and the cookie has been cleared
}
});
</script>
php code ....
<?php
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
if(isset($cookie))
{
$first_name = json_decode(#file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->first_name;
$last_name = json_decode(#file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->last_name;
}
?>
function get_facebook_cookie($app_id, $application_secret)
{
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value)
{
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
i think this much code is available for you to get facebook name and user id ....
on this url you will find whole response
https://graph.facebook.com/me?access_token=' .$cookie['access_token']
In your api call, replace the '/me' with '/2222'
Is it possible to check if a user already likes my facebook fanpage from my website with Javascript or PHP?
EDIT: I need a solution, so the user doesn't need to authenticate / allow some persmissions first
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APP_ID',
'secret' => 'APP_SECRET',
));
$user = $facebook->getUser();
$page_id = "123456789";
$page_name = $facebook->api("/".$page_id)['name'];
$page_link = $facebook->api("/".$page_id)['link'];
if ($user) {
try {
$likes = $facebook->api("/me/likes/".$page_id);
if( !empty($likes['data']) )
echo "I like!";
else
echo "not a fan!";
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_likes'
));
}
// rest of code here
?>
The simplest way would be to call the Graph API to get the /me/likes connections (note you have to require the user_likes permission). Then go through each and compare id with the ID of your page.
Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebook object set up (see Usage section in the aforementioned page), the following code can be used to find out if the user is fan of Daft Punk:
$our_page_id = '22476490672'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
if( $page['id'] === $our_page_id ) {
$user_is_fan = true;
break;
}
}
Now, you can further work with the $user_is_fan variable.
In JavaScript, the code would be very similar. Using the official JavaScript SDK's method FB.api (again, assuming you have taken of the authentication):
FB.api('/me/likes?fields=id', function(response) {
var our_page_id = '22476490672';
var user_is_fan = false;
var likes_count = response.data.length;
for(i = 0; i < likes_count; i++) {
if(response.data[i].id === our_page_id) {
user_is_fan = true;
break;
}
}
});
Note that here we're using an asynchronous request and callback, so the code using the user_is_fan variable must be inside the function.
In case you are OK with user giving the permissions, for a PHP based website it can be done this way easily:
1- Create a new Facebook app here.
2 - Download Facebook PHP SDK from here. Extract the files and place it in the same folder with the file in which you will paste the code given below!
3 - Get your Facebook Page ID using this tool.
4 - Generate Facebook like box code for your page from here.
After 1, 2, 3 and 4 steps are complete, you can check if user has liked a page or not with the following code:
<?php
require('facebook.php');
$config = array(
'appId' => 'your facebook app id',
'secret' => 'your facebook app secret code',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if (isset($user_id)) {
try {
$likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');
if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
{
echo 'Thank you for liking our fan page!';
}
else {
echo 'You have not liked our fan page! Like it now:';
?>
<iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fchillopedia&width&height=290&colorscheme=light&show_faces=true&header=true&stream=false&show_border=true&appId=1392604484339363" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:290px;" allowTransparency="true"></iframe> //replace this with your own Facebook like box code
<?php
}
} catch (FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please click here to login into your Facebook account.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please lick here to login into your Facebook account';
}
?>
The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display the likebox if user hasn't liked your fan page.
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID_WITHIN_QUOTES', //Change this to your app id
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
$has_liked = $data["page"]["liked"];
now check the $has_liked param to see if user likes ur page or not!
seems like "/me/likes/[page_id]" doesn't always return the record even there is one.
recently I request by "/me/likes/[page_id]", it will return 0,
but if I request without page_id, but grab a bunch of record by "/me/likes/", and you will see the page_id is actually there, can't figure why.
when checking with graph.facebook.com/[page_id], only suspicious thing is its "can_post" is false, and others which "/me/likes/[page_id]" do works, is true.
but looping is not good in this situation, especially some crazy people has millions of likes.
is there any kinda privacy setting related to the page_id owner account would cause the problem?