I am using facebook app that can publish message on users wall , My Error Message :
Fatal error: Call to protected method BaseFacebook::getUserAccessToken() from context '' in /home/tillaf/public_html/facebook/login_facebook2.php on line 61
My file :
<?php
require_once("facebook.php");
#session_start();
$app_id = "********";
$app_secret = "*********";
$my_url = "http://t.****.net/**/login.php/";
///
$config = array();
$config['appId'] = '408682199198463';
$config['secret'] = 'd5b3c0ddfbd673dd94494f28524c1a84';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
///
////
////
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=user_birthday,read_stream,publish_stream,email,user_status,offline_access";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
else{
$user_id = $facebook->getUser();
echo $user_id;
echo "<br/>";
////////// Get Access Token
/*
$app_token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&grant_type=client_credentials";
$response = file_get_contents($app_token_url);
$params = null;
parse_str($response, $params);
echo("This app's access token is: " . $params['access_token']);
*/
///-------------
$user_access_token = $facebook->getUserAccessToken();
////////
////// Start publish on wall
//$facebook->getAccessTokenFromCode($_GET['code']);
$message='ssss';
$link='http://www.google.com';
$name='Samilox';
$caption='s';
$description='Descrption...';
$facebook->api("/me/feed",'POST',
array( 'access_token' =>$user_access_token,
'message' => 'Hello World!',
'link' => 'www.example.com'
)
);
///
}
?>
Sorry For Code :) because i am trying many solutions before i post this question .
Please Can anyone help ?
Thanks in advance
I fixed it use :
//// Add AccessToken for curren session
function getAccessToken() {
if ($this->accessToken !== null) {
return $this->accessToken;
}
$this->setAccessToken($this->getApplicationAccessToken());
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
$this->setAccessToken($user_access_token);
}
return $this->accessToken;
}
function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
////
Related
I'm using facebook sdk 5.0. when i run this code error like "Invalid appsecret_proof provided in the API argument". how can i config appsecret_proof to this. and what is the appsecret_proof? Please help me..! :-(
session_start();
$_SESSION['facebook_access_token'] = '*************************';
require_once './sdk/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '**********',
'app_secret' => '************',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} 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;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
$oAuth2Client = $fb->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
if (isset($_GET['code'])) {
header('Location: ./');
}
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email', $accessToken);
$profile = $profile_request->getGraphNode()->asArray();
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo $profile_request->getGraphUser()->getName();
}
I am trying to develop a fb app that should send the news feed to a website;
I managed to subscribe using the app_id and app_secret but i don't get the news feed;
public function actionSubscription() {
$app_id = '691036934243090';
$app_secret = 'ca6e828f41c638dba4fb0864f7d9f6e8';
$app_url = 'http://www.ghidul-comercial.ro';
$fields = 'feed';
$verify_token = 'blabla';
// Fetching an App Token
$app_token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
. $app_id . '&client_secret=' . $app_secret
. '&grant_type=client_credentials';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $app_token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
parse_str($res, $token);
if (isset($token['access_token'])) {
// Let's register a callback
$params = array(
'object'
=> 'page',
'fields'
=> $fields,
'callback_url'
// This is the endpoint that will be called when
// a User updates the location field
=> $app_url . '/index.php/site/api',
'verify_token'
=> $verify_token,
);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'
. $app_id . '/subscriptions?access_token='
. $token['access_token']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$res = curl_exec($ch);
if ($res && $res != 'null') {
print_r($res);
}
// Fetch list of all callbacks
curl_setopt($ch, CURLOPT_POST, 0);
$res = curl_exec($ch);
}
if ($res && $res != 'null') {
print_r($res);
}
curl_close($ch);
error_log('test');
}
This is how i intend to catch the feed:
public function actionApi() {
$data = new Data();
$data->info = '1';
$data->save(false);
$method = $_SERVER['REQUEST_METHOD'];
$data = new Data();
$data->info = $method;
$data->save(false);
$rawdata1 = file_get_contents('php://input');
$rawdata2 = json_decode($HTTP_RAW_POST_DATA,true);
$rawdata2 = json_decode(file_get_contents('php://input'),true);
$data = new Data();
$data->info = $rawdata1;
$data->save(false);
if ($method == 'GET' && isset($_GET['hub_mode']) && $_GET['hub_mode'] == 'subscribe' && isset($_GET['hub_verify_token']) && $_GET['hub_verify_token'] == 'blabla') {
echo $_GET['hub_challenge'];
exit;
} elseif ($method == 'POST') {
$post = file_get_contents("php://input");
$data = new Data();
$data->info = $post;
$data->save(false);
}
$data = new Data();
$data->info = '2';
$data->save(false);
}
go to link click Get Access Token , select by click everything from the 3 tabs , click get acccess token , then paste your group id ; also at your feed field and click submit.
That's all ! this will work
i'm struggling really hard to implement Facebook connect into my codeigniter application - I have one issue right now. After downloading the PHP SDK from here: https://github.com/facebook/php-sdk/ I copied the /src files into my CI libraries (as everyone do : )).
Now I want to authenticate my users using this method:
https://developers.facebook.com/docs/authentication/server-side/
My controller is here (I think the problem is at the end, but pasted full file, cause i'm not sure):
<?php
class Fb25 extends CI_Controller {
function index()
{
$app_id = "MY APP ID";
$app_secret = "MY SECRET KEY";
$site_url = "http://devlocalhost.com/";
$this->load->library('facebook',array('appId' => $app_id, 'secret' => $app_secret));
$user = $this->facebook->getUser();
$data['user'] = $user;
if($user){
$data['user_profile'] = $this->facebook->api('/me');
$user_profile = $data['user_profile'];
} else{
$user = NULL;
}
if($user){
// Get logout URL
$data['logoutUrl'] = $this->facebook->getLogoutUrl(array(
'next' => 'http://devlocalhost.com/', // URL to which to redirect the user after logging out
));
}else{
// Get login URL
$data['loginUrl'] = $this->facebook->getLoginUrl(array(
'scope' => 'email', // Permissions to request from the user
'redirect_uri' => 'http://devlocalhost.com/fb25/good', // URL to redirect the user to once the login/authorization process is complete.
));
}
if($user){
// Save your method calls into an array
$data['queries'] = array(
array('method' => 'GET', 'relative_url' => '/'.$user),
array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'),
);
// POST your queries to the batch endpoint on the graph.
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.
$data['user_info'] = json_decode($batchResponse[0]['body'], TRUE);
$data['feed'] = json_decode($batchResponse[1]['body'], TRUE);
$data['friends_list'] = json_decode($batchResponse[2]['body'], TRUE);
$data['photos'] = json_decode($batchResponse[3]['body'], TRUE);
}
echo 'user_info: '.$data['user_info'];
print_r($data);
$this->load->view('fb25_view', $data);
}
public function good(){
$app_id = "MY APP ID";
$app_secret = "MY SECRET KEY";
$site_url = "http://devlocalhost.com/";
echo '<br/><br/>SESJA:<br/>';
print_r($_SESSION);
echo '<br/><br/>GET:<br/>';
print_r($_GET);
echo '<br/><br/>REQUEST:<br/>';
print_r($_REQUEST);
echo '<br/><br/>najs<br/><br/>';
session_start();
$code = $_GET["code"];
//######IMO PROBLEM IS SOMEWHERE HERE:
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
}
?>
My problem is: I'm pressing the login button and gets into facebook to authenticate myself, clicking "go to app" and want to go back into my website - it says:
Message: file_get_contents(https://graph.facebook.com/oauth/access_token? client_id=487560264592073&redirect_uri=http%3A%2F%2Fdevlocalhost.com%2F&client_secret=mysecretcode&code=AQAgnmNWwDub9yaRB6Vf73gg8Xvwo8KhIM077lB67_bu1Z3rAvyk3Ckl54qK7hh9o3VkG0rFIBTfRXwtrSBFVWEpqYfm1o7e5CQg3jVctq-EE1ZxWrgWrfesLpQ2oF3wlmEMb5o6ORobGmibT06kqe5f2N0ch4kSYBJ4SiTcdV-612fGOJHGcipeyU_GJJ0Jvsg)
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
UPDATE
Look here, please:
I added function into your controller:
public function link(){
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
$my_url="http://devlocal.pl";
echo 'user_id';
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=myclientid&redirect_uri=" . urlencode($my_url)
. "&client_secret=mysecretcode&code=" . $_GET['code'];
redirect($token_url);
}
To get my access token - without access token I can't get my username..
I made your loginbyfacebook function redirecting into link function. And it doesn't show the fb username.
When I'm redirecting to my token_url It shows:
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
Follow these steps:
1.Put the facebook php sdk in library folder
2.create facebook config with app detail
3.Inherit facebook class in fb_connect
4.add these function in controller then it will work like charm.
fb_connect.php
<?php
include(APPPATH.'libraries/facebook/facebook.php');
class Fb_connect extends Facebook{
//declare public variables
public $user = NULL;
public $user_id = FALSE;
public $fb = FALSE;
public $fbSession = FALSE;
public $appkey = 0;
//constructor method.
public function __construct()
{
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
parent::__construct($config);
$this->user_id = $this->getUser(); // New code
$me = null;
if ($this->user_id) {
try {
$me = $this->api('/me');
$this->user = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
} // end class
Controller function
function loginByFacebook(){
$this->load->library('fb_connect');
$param = array(
'scope' =>'email,user_location,user_birthday,offline_access',
'redirect_uri' => base_url()
);
redirect($this->fb_connect->getLoginUrl($param));
}
function facebook() {
if (!$this->fb_connect->user_id) {
} else {
$fb_uid = $this->fb_connect->user_id;
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
}
}
In this way
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
Small problem here
I want to make a small fb app which show different views for page admin and users, page admin can add html to the app and include the app in their page (somewhat like the old fbml app).
but the problem is when i'm authenticating the app it is jumping from page tab to its app page.
i need to acces the following things
[page] => stdClass Object
(
[id] => FAN_PAGE_ID
[liked] => 1
[admin] =>
)
for this i need to be in fb page tab while authenticating. How ? :(
i am posting my current code here.
please help me.
ob_start();
$app_id = "----------";
$app_secret = "-----------------";
include_once 'src/facebook.php';
$my_url = "http://apps.facebook.com/-----beta/index.php";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
session_start();
$code = $_REQUEST["code"];
//echo $code . "</br>";
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&display=popup&scope=manage_pages,email&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
//echo $_REQUEST['signed_request'];echo "<hr>";
//var_dump($user);
$signedRequest = $facebook->getSignedRequest();
$appData = array();
if (!empty($signedRequest) && !empty($signedRequest['page'])) {
$appData = json_decode($signedRequest['page'], true);
}
var_dump($appData); echo "<hr>";
var_dump(parse_signed_request($_REQUEST['signed_request'] , $app_secret));
echo("<hr>Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
I am using this script in the tab:
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
return null;
}
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
$signed_request = $_REQUEST['signed_request'];
$secret = $app_secret;
$getdata = parse_signed_request($signed_request, $secret);
$fanpage = $getdata['page'];
$page_id = $fanpage['id']; // GET THE PAGE ID
$is_fan = $fanpage['liked']; // 0 if its not fan, 1 if its fan
$is_admin = $fanpage['admin']; //1 if user is admin of page. 0 if not
if($page_id){
//if app is tab
if($is_admin){
//if user is admin
}
if($is_fan){
//I am fan
}else{
// I am not a fan
}
}
When I use the following code, $user_profile = $facebook->api('/me'); will show the info for me, the admin user, but when I switch to a test user the permissions dialog never displays for the test user to add the app and $user_profile doesn't get defined.
I can't seem to find one example of code that seems to do everything properly in terms of making sure the app is authorized and the user is authenticated. I see from the old FB developer forums that a lot of people seem to be having the same issue with the newer procedures.
Here's the code:
<?php
$appId = "myid";
$secret = "mysecret";
$canvasurl = "http://www.example.com/myappname/";
$canvas = "http://apps.facebook.com/myappname/";
$scope = "user_website,email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,manage_pages,offline_access";
require_once "facebook.php";
$facebook = new facebook(array(
'appId' => $appId,
'secret' => $secret
)
);
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
$user = null;
}
if (!$user) {
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => $scope,
'redirect_uri' => $canvas
)
);
echo <<<LU
<script type="text/javascript">
top.location.href = $loginUrl;
</script>
LU;
}
}
print_r($user_profile);
?>
Thanks.
I will post my code
<?php
$fbconfig['appid' ] = "";
$fbconfig['secret'] = "";
$fbconfig['baseUrl'] = "";
$fbconfig['appBaseUrl'] = "";
$user = null;
try{
include_once "src/facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'user_status,publish_stream,user_photos'
)
);
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
?>