How do I post on facebook groups using php sdk? - php

I want to post on my facebook groups. This is my code:
$access_token = $facebook->getAccessToken();
$info = $facebook->api( '/me/groups', 'GET', array( 'access_token=' => $access_token ) );
$count = count($info['data']);
print "<h2>Alege grupul(".$count.") in care vrei sa postezi:</h2><br>";
$i = 0;
foreach ($info['data'] as $group) {
$group_name = $group['name'];
$group_id = $group['id'];
echo "<input type='checkbox' value ='".$group_id."'> ".$group_name."<br>";
if ($i == 0){
$post_url = '/'.$group_id.'/feed';
$msg_body = array(
'message' => 'TEST',
);
$postResult = $facebook->api($post_url, 'post', $msg_body );
}
$i++;
}
This is the code from the login part:
$loginUrl = $facebook->getLoginUrl(array (
'scope' => 'publish_stream,user_groups,user_about_me,user_interests,friends_groups,friends_interests,friends_about_me',
'redirect_uri' => 'http://facebook.ebis-servicii.ro/mytest/test.php'
));
This is the link , where I am coding now. The result is an interesting error:
Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action thrown....
I'm a totally newbie to this, this is the first time I'm using fb php api, so my question is what am I doing wrong ? Why am I getting this ?

Related

How to add page links for multiple pages in Bing search api in php

I used the following code to include bing API in my web page. How can I add paging to this web search ?
Currently it shows only 1st 50 results and does not show the page links to other results. Also, how do I limit the results in one page to 20 ?
<?php
if (isset($_POST['submit']))
{
$acctKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$rootUri = 'https://api.datamarket.azure.com/Bing/Search';
$query = $_POST['searchText'];
$serviceOp ='Web';
$market ='en-us';
$query = urlencode("'$query'");
$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query";
$auth = base64_encode("$acctKey:$acctKey");
$data = array(
'http' => array(
'request_fulluri' => true,
'ignore_errors' => true,
'header' => "Authorization: Basic $auth"
)
);
$context = stream_context_create($data);
$response = file_get_contents($requestUri, 0, $context);
$response=json_decode($response);
echo "<pre>";
echo("<ol>");
foreach($response->d->results as $value)
{
$Ur = $value->Url;
echo '<li class="resultlistitem"><a href="{$Ur}"> '.$Ur. '
</a><br><p>';
echo($value->Description .'</li> </p>');
}
echo("</ol>");
echo "</pre>";
}
?>

Usage of facebook login + Laravel

Just implemented facebook login on my test site, and it seems too simple to be true?
I am using these two from GitHub
https://github.com/Lusitanian/PHPoAuthLib
https://github.com/artdarek/oauth-4-laravel
To implement this I added a button:
{{ link_to_action('UserController#loginWithFacebook', 'Facebook Login in', $parameters = array(), $attributes = array('class' => 'btn btn-primary fb-login-btn')); }}
And then modifiying the example login method to authorise the user after success:
public function loginWithFacebook() {
$code = Input::get( 'code' );
$fb = OAuth::consumer( 'Facebook' );
if ( !empty( $code ) ) {
$token = $fb->requestAccessToken( $code );
$result = json_decode( $fb->request( '/me' ), true );
// ADDED SECTION
$newUser = User::create(
array(
'email' => $result['email']
)
);
$user = User::find($newUser->id);
Auth::login($user);
return Redirect::to('/');
} else {
$url = $fb->getAuthorizationUri();
return Redirect::to( (string)$url );
}
}
This works, which has surprised me... is this really all it takes?
The question im asking really is would this be the way its intended to be used? The response is used to create a user, then log them in after with their ID.
I only use their email, since they only need to login using the facebook button. In the future I could prompt them to add a password so they don't always have to use facebook login but the basics of this is correct?
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode($fb->request( '/me?fields=id,name,first_name,last_name,email,photos' ), true);
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name']. $result['email'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
//echo('http://graph.facebook.com/'.$result['id'].'/picture?type=large<br>');
//dd($result);
$user = \User::where("email",$result['email'])->first();
if($user!=NULL){
$userxx = Sentry::findUserByLogin($result['email']);
Sentry::login($userxx, false);
return Redirect::to('Beşiktaş');
}
else
{
$k=str_random(8);
$user = Sentry::register(array(
'activated' => 1,
'facebook' => 1,
'password' => $k,
'email' => $result['email'],
'first_name' =>$result['first_name'],
'last_name' => $result['last_name'] ,
'avatar' => 'http://graph.facebook.com/'.$result['id'].'/picture?type=large',
));
Sentry::login($user, false);
return Redirect::to('Beşiktaş');
}
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}

Using Facebook SDK to extract you friends info (more than just name or ID)

i am using FB SDK v.3.2.3 , and i'm trying to retrieve the events that my friends are going to. So far, my code can retrieve the list of friends who are using my app. The documentation on FB tells the event can be pulled out by using "me/events", but since i want my friend's event to be pulled, i used "me/friends/event" or "me/friends?fields=event", but it still does not work. Someone has an idea about it? Below is my code --
<pre>
require_once('facebook.php');
$config = array(
'appId' => 'xxx',
'secret' => 'xxx'
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
echo "<pre>";
print_r($user_profile);
echo "</pre>";
$dost = $facebook->api('/me/friends','GET');
foreach ($dost as $friend) {
echo "<pre>";
print_r($friend);
echo "</pre>";
}
echo '<br><a href=' . $facebook->destroySession() . '>Logout</a>';
} catch(FacebookApiException $e) { }
} else {
$params = array(
'scope' => 'public_profile, user_friends, email',
'redirect_url' => 'http://xxxxx.com',
'auto_logout_link' => 'true',
'show_faces' => 'true'
);
$login_url = $facebook->getLoginUrl($params);
echo 'Please login.';
}
Try it:
//...
$dost = $facebook->api('/me/friends','GET');
foreach ($dost["data"] as $value) {
$friend_id = $value['id'];
$events = $facebook->api('/'.$friend_id.'/events');
print_r($events);
}
//...
Facebook changed the privacy policy for friends - your friends also need to give permission to your app

FB Developer: Uncaught OAuthException: (#120) Invalid album id

i'm trying to post photos on a fanpage and I get this error:
Fatal error: Uncaught OAuthException: (#120) Invalid album id thrown in /home/eyikmdnu/public_html/jack/facebook-sdk/base_facebook.php on line 1264
This is the code of the page (obv the token, the secret etc are not the "original"
require_once("../facebook-sdk/facebook.php");
define("APP_ID", "*****");
define("APP_SECRET", "********");
$fanpage_token = "*******";
$user_access_token = "********";
$config = array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'fileUpload' => true // optional
);
$facebook = new Facebook($config);
//pagina = 358226040977616
//album id = 402459486554271
//$access_token = $_POST['access_token'];
//echo $access_token;
$facebook->setAccessToken($fanpage_token);
echo "Access Token Settato <br>\n";
$facebook->setFileUploadSupport(true);
echo "setFileUploadSupport(true) settato <br>\n";
$img_url = "images/jack.png";
//$img_url = $_POST['url'];
echo "$img_url = $img_url <br>\n";
$page_id = "358226040977616";
$album_id = "402459486554271";
echo "Page id: $page_id <br>\n";
echo "Album id: $album_id <br>\n";
$real_img_url = realpath($img_url);
echo "Real img url: $real_img_url <br>\n";
$args = array(
'message' => 'message to write in legend',
'image' => "#" . $img_url,
'aid' => $album_id,
'no_story' => 1,
'access_token' => $fanpage_token
);
echo "<br>\n";
print_r($args);
echo "<br>\n";
$photo = $facebook->api("/".$album_id."/photos", 'post', $args);
print_r($photo);
Need help! :O
I solved, the problem is that I should use the access_token of the page, that is not static, well I have to look in my /profile/accounts
$params = array('access_token' => $access_token);
$accounts = $facebook->api('/giacomo.torricelli/accounts', 'GET', $params);
foreach($accounts['data'] as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
$fanpage_token = $account['access_token'];
}
}
Thanks

Fatal error: Call to undefined method stdClass::stream_publish()

Well I am trying to post on facebook's wall but I get this error:
Fatal error: Call to undefined method stdClass::stream_publish()
The code I am trying is this
<?php
define('FB_APIKEY', '<Your Api Key>');
define('FB_SECRET', '<Secret>');
define('FB_SESSION', '<Session>');
require_once('facebook.php');
echo "post on wall";
echo "<br/>";
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
$message = '';
$attachment = array(
'name' => $_POST["name"],
'href' => $_POST["href"],
'description' => $_POST["description"],
'media' => array(array('type' => 'image',
'src' => $_POST["src"],
'href' => $_POST["href"])));
$action_links = array( array('text' => 'Visit Us', 'href' => '<link to some place here>'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
$target_id = "<Target Id>";
$session_key = FB_SESSION;
if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id)) {
echo "Added on FB Wall";
}
} catch(Exception $e) {
echo $e . "<br />";
}
?>
Well, as it is written in the error message there is no method "stream_publish" in $facebook->api_client.
Consult the manual of the library you are using to connect to the facebook.
If $facebook->api_client is not an object, then the line:
$facebook->api_client->session_key = FB_SESSION;
Will make php silently cast $facebook->api_client to an object of type stdClass. Which, later on down the code, will cause the Fatal error: Call to undefined method stdClass::stream_publish() that you are getting.
Try changing:
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
to catch for when api_client is false (or, perhaps, not an object):
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
if (!( $facebook->api_client )) {
//throw error
echo 'Need to sort this bit out';
exit;
}
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
And then, if that does throw an error, you'd need to investigate why $facebook->api_client is null.

Categories