I am getting the response below when trying to upload a file to soundcloud using the soundcloud php api.
The requested URL responded with HTTP code 0.
When trying to upload a file through the api.
It will get my data fine but not upload here is my full codeignitor controller.
I have tried all the suggested option to add the CURLOPT_SSL_VERIFYPEER, false but this doesnt seem to work for me can someone confirm it is working so i can narrow it down to my server.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
* Soundcloud Controller
*/
class Soundcloud extends CI_Controller {
/**
* Constructor
*/
function __construct()
{
parent::__construct();
require APPPATH.'/libraries/php-soundcloud-master/Services/Soundcloud.php';
$this->soundcloud = new Services_Soundcloud('api key', 'api key', 'redirect uri');
}
function index(){
$authorizeUrl = $this->soundcloud->getAuthorizeUrl();
// Redirect to authorize url
echo 'Connect with SoundCloud';
}
function getme(){
$url = $_SERVER['DOCUMENT_ROOT'] . '/' . APPPATH . 'libraries/php-soundcloud-master/test/test.mp3';
try {
$accessToken = $this->soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
/*
$this->soundcloud->setCurlOptions(array(
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
*/
try {
$me = json_decode($this->soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
// this will print out all my data fine
echo "<pre>";
print_r($me);
echo "</pre>";
$track_data = array(
//'track[sharing]' => 'private',
'track[title]' => 'Testing API',
//'track[tags]' => null,
'track[asset_data]' => '#' . $url
);
// perform the actual upload to soundcloud.
try {
$response = json_decode(
$this->soundcloud->post('tracks', $track_data),
true
);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
show_error($e->getMessage());
}
}
}
Related
I'm trying to implement facebook login for my website using facebook PHP-SDK with codeigniter by following this example: https://shareurcodes.com/blog/facebook%20php%20sdk%20v5%20with%20codeigniter
From what I have seen from other questions on this subject I checked for given answers/common mistakes but http://localhost/fbcallback is already in my app's Valid OAuth redirect URIs and putting/removing '/' from the end of the url is not helping.
I created two controllers the first one: fblogin.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Fblogin extends CI_Controller{
public function index(){
require_once '{path}/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','user_location','user_birthday','publish_actions'];
// For more permissions like user location etc you need to send your application for review
$loginUrl = $helper->getLoginUrl('http://localhost/fbcallback', $permissions);
header("location: ".$loginUrl);
}
}
second one: fbcallback.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Fbcallback extends CI_Controller{
public function index(){
require_once '{path}/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
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;
}
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?fields=id,name,email,first_name,last_name,birthday,location,gender', $accessToken);
// print_r($response);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'ERROR: Graph ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'ERROR: validation fails ' . $e->getMessage();
exit;
}
// User Information Retrieval begins................................................
$me = $response->getGraphUser();
$location = $me->getProperty('location');
echo "Full Name: ".$me->getProperty('name')."<br>";
echo "First Name: ".$me->getProperty('first_name')."<br>";
echo "Last Name: ".$me->getProperty('last_name')."<br>";
echo "Gender: ".$me->getProperty('gender')."<br>";
echo "Email: ".$me->getProperty('email')."<br>";
echo "location: ".$location['name']."<br>";
echo "Birthday: ".$me->getProperty('birthday')->format('d/m/Y')."<br>";
echo "Facebook ID: <a href='https://www.facebook.com/".$me->getProperty('id')."' target='_blank'>".$me->getProperty('id')."</a>"."<br>";
$profileid = $me->getProperty('id');
echo "</br><img src='//graph.facebook.com/$profileid/picture?type=large'> ";
echo "</br></br>Access Token : </br>".$accessToken;
}
}
When I go to http://localhost/fblogin it asks for necessary permissions (email, user location, user birthday , publish actions) but after I give the permissions and redirected to http://localhost/fbcallback I get the following error:
Graph returned an error: Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request.
While I was playing around i realised if I change $loginUrl variables in
vendor/facebook/graph-sdk/src/Facebook/Authentication/OAuth2Client.php to http://localhost/fbcallback as shown below everything works as intended. So I suspected maybe there is a problem while passing the $loginUrl parameter, and traced my code but couldn't find anything problematic.
public function getAuthorizationUrl($loginUrl, $state, array $scope = [], array $params = [], $separator = '&')
{
$params += [
'client_id' => $this->app->getId(),
'state' => $state,
'response_type' => 'code',
'sdk' => 'php-sdk-' . Facebook::VERSION,
'redirect_uri' => 'http://localhost/fbcallback', //instead of {$redirectUrl}
'scope' => implode(',', $scope)
];
What really got me confused is if I change DocumentRoot of my server and copy the above two controllers with the facebook-sdk library everything works just fine again in the new directory. So maybe there is a conflict with one of the files in the current directory? I searched for it but couldn't find anything that may conflict.
Thanks in advance!
The getAccessToken method of the FacebookRedirectLoginHelper generates the API request URL to exchange the code for a token, that includes the redirect_uri parameter.
If this is not explicitly specified as parameter when you call the method, it is determined internally and falls back to the current script URL/route.
So this works without specifying the redirect URI as long as you handle generation of the login URL and processing of the resulting code parameter under the same route resp. under the same script URL; but if those two are different, then you need to specify it when calling getAccessToken.
I recently upgraded to the latest version of the facebook SDK and I'm having issues logging users in. I generate the login link just fine, but when facebook sends the user back to my site with the token, I get this error:
fb sdk error: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
I tried to do some trouble shooting. I printed out everything in the session data and everything in the GET request. I see that the GET has a state parameter and the session data has a FBRLH_state parameter. They both have the same value. So how is it telling me that the parameter is missing?
I've tried some suggestions I've seen on other questions (ie, starting the session), but nothing seems to work.
Any help would be greatly appreciated! I'm using the php-graph-sdk-5.5. My facebook connect file is below
if(!class_exists('facebook')){
class facebook{
private $db = null;
private $fb = null;
private $token = null;
private $DEV = null;
private $sdk_error = null;
private $api_error = null;
private $verbose = false;
private $graph_user = null;
private $db_helper = null;
private $errors = null;
public function __construct($db,
$fb_id = FB_APP_ID,
$fb_secret = FB_APP_SECRET,
$fb_version = FB_DEFAULT_GRAPH_VERSION){
if($this->verbose) echo '<pre>';
if($this->verbose) echo 'starting construction'.PHP_EOL;
$this->db = $db;
if(!$this->fb){
$this->log[] = 'no connect found. building..'.PHP_EOL;
$this->fb = new Facebook\Facebook(array(
'app_id' => $fb_id,
'app_secret' => $fb_secret,
'default_graph_version' => $fb_version));
if(!$this->fb){
die('facebook initialization failure');
}
$this->log[] = 'finished building new connection'.PHP_EOL;
}
}
public function get_login_url($callback_uri, $permissions = ['email','user_birthday']){
global $_DEV,$_config;
$helper = $this->fb->getRedirectLoginHelper();
$callback_host = ($_DEV ? $_config['dev_domain'] : $_config['live_domain']);
$callback_url = 'https://'.$callback_host.$callback_uri;
return $helper->getLoginUrl($callback_url, $permissions);
}
public function catch_token(){
if($this->token){
$this->log[] = 'already have token.'.PHP_EOL;
return $this->token;
} else if(!$this->fb){
$this->log[] = $this->error[] = 'no facebook connection in catch token()';
}
$this->log[] = 'starting catch token routine.'.PHP_EOL;
//$_SESSION['state']=$_GET['state'];
echo '<pre>' . var_export($_SESSION, true) . '</pre>';
echo '<BR><BR><pre>' . var_export($_GET, true) . '</pre>';
$helper = $this->fb->getRedirectLoginHelper();
$this->token = $helper->getAccessToken();
$this->log[] = 'caught token: '.$this->token;
$string_token = $this->token.PHP_EOL;
//die($string_token);
try {
$helper = $this->fb->getRedirectLoginHelper();
$this->token = $helper->getAccessToken();
$this->log[] = 'caught token: '.$this->token;
$string_token = $this->token.PHP_EOL;
return $this->user_flush();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$this->log[] = $this->errors[] = 'fb api error: ' . $e->getMessage();
return null;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$this->log[] = $this->errors[] = 'fb sdk error: ' . $e->getMessage();
return null;
} catch(Exception $e){
$this->log[] = $this->errors[] = 'unknown error: '.$e->getMessage();
return null;
}
}
public function get_token(){
$this->log[] = 'get token called.'.PHP_EOL;
if($this->token){
$this->log[] = 'token found in object'.PHP_EOL;
//echo '<pre>';
//die(debug_print_backtrace());
return $this->token;
} else {
$this->log[] = $this->errors[] = 'token not found in object.'.PHP_EOL;
return null;
}
}
public function get_user($override = false){
$fields = array(
'first_name',
'last_name',
'email',
'id',
'picture',
'birthday',
'gender',);
$fields = implode(',',$fields);
if($this->graph_user === null){
if($this->fb && $this->get_token()){
try {
// Returns a Facebook\FacebookResponse object
$resp_url = '/me?fields='.$fields.'&debug=all';
$this->log[] = $resp_url;
$response = $this->fb->get($resp_url, $this->get_token());
$this->graph_user = $response->getGraphUser();
return $this->graph_user;
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$this->api_error = 'fb api error: ' . $e->getMessage();
$this->errors[] = $this->api_error;
return null;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$this->sdk_error = 'fb sdk error: ' . $e->getMessage();
$this->errors[] = $this->sdk_error;
return null;
}
} else {
$this->sdk_error = "get_user(): fb connection or token not set. are you logged in?";
$this->errors[] = $this->sdk_error;
//echo '<pre>';
//debug_print_backtrace();
//die('token: '.$this->token);
return null;
}
} else {
$this->sdk_error = "get_user(): graph_user already set";
$this->errors[] = $this->sdk_error;
return $this->graph_user;
}
}
public function get_user_first_name(){
return $this->get_user()['first_name'];
}
public function get_user_last_name(){
return $this->get_user()['last_name'];
}
public function get_user_id(){
return $this->get_user()['id'];
}
public function get_user_email(){
return $this->get_user()['email'];
}
public function get_user_picture(){
return $this->get_user()['picture']['url'];
}
public function get_user_birthday(){
return $this->get_user()['birthday'];
}
public function user_flush(){
//this is the command function.
// runs the basic functionality of this class
// by adding this user to the database if they're not there
// and logging them in if they are.
$this->graph_user = $this->get_user();
//$this->log['graph_user_at_user_flush'] = $this->graph_user;
$this->build_user();
$this->log['GRAPH_USER'] = $this->get_user();
$this->log['user_input_array#user_flush'] = $this->user_input;
if($return = $this->user->fb_register()){
//die(print_r(debug_backtrace(),true));
//$this->log['success return'] = '. '.$return;
return $return;
} else {
//die('<pre>'.print_r(debug_backtrace(),true));
$this->log['fb_register_fail'] = array('fb_register() (also login) failed.',$this->user->get_errors());
return null;
}
}
public function build_user(){
$this->user_input['first_name'] = $this->get_user_first_name();
//$this->user_input['last_name'] = $this->get_user_last_name();
$this->user_input['facebook_id'] = $this->get_user_id();
$this->user_input['email'] = $this->get_user_email();
$this->user_input['image_url'] = $this->get_user_picture();
$this->user_input['birthday'] = $this->get_user_birthday();
if($this->verbose)
print_r($this->user_input);
$this->user = new user($this->user_input,$this->db);
}
public function logout(){
unset($_SESSION['fb_id']);
unset($this->token);
unset($this->fb);
}
public function get_errors(){
return array_unique($this->errors);
}
public function get_log(){
return array_unique($this->log);
}
}
}
//finally, create the connection.
if(!isset($fb))
$fb = new facebook($db);
This might be kinda late but I hope it helps others.
I had this problem for a while and I've searched around and have seen a lot of different solutions, many of which disable the CSRF check. So after everything I've read, this is what worked for me.
For what I understand, you get this error when your redirect URL doesn't match the one you have setup on your app settings so my issue was fixed every easily but I have also seen people have issues by not having their session started properly, so I will cover both issues.
Step 1: Ensure your session has started when it needs to.
for example: fb-config.php
session_start();
include_once 'path/to/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => 'your_app_id',
'app_secret' => 'your_secret_app_id',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
if your facebook callback code is on another file aside from the config, then start the session on that file too.
for example: fb-callback.php
session_start();
include_once 'path/to/fb-config.php';
try {
$accessToken = $helper->getAccessToken();
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
echo "Response Exception: " . $e->getMessage();
exit();
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
echo "SDK Exception: " . $e->getMessage();
exit();
}
/** THE REST OF YOUR CALLBACK CODE **/
Now, what solved my actual issue.
Step 3: Set up your redirect URL in your app settings.
In your Facebook Login app settings, go to the Valid OAuth redirect URIs where you should have added the url that points to your fb-callback.php file.
http://example.com/fb-callback.php
AND ALSO
http://www.example.com/fb-callback.php
then setup your redirect url as follows.
$redirectURL = "http://".$_SERVER['SERVER_NAME']."/fb-callback.php";
$permissions = ['email'];
$fLoginURL = $helper->getLoginUrl($redirectURL, $permissions);
Why both with and without www and why use SERVER_NAME?
because your Valid OAuth redirect URI needs to match your redirect url in your code and if in you app settings you only set your OAuth redirect as http://example.com/fb-callback.php and set up your $redirectURL as http://example.com/fb-bacllback.php to make it match but the user entered your site as http://www.example.com then the user will get the Facebook SDK error: Cross-site request forgery validation failed. Required param “state” missing from persistent data because the URL the user is at, doesn't EXACTLY match what you have setup. Why? I have no freaking idea.
My approach makes it so if the user enters your site as http://example.com or http://www.example.com, it will always match what you setup in your app settings. why? because $_SERVER['SERVER_NAME'] will return the domain with or without the www depending on how the user entered the url in the browser.
This are my findings and this is about the only thing that worked for me without removing the CSRF check and so far, no issues.
I hope this helps.
fb sdk error: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
It has something to do with that you are going through the routine of calling getRedirectLoginHelper and $helper->getAccessToken() twice - once "on their own", and then again inside a try-catch block (copy&paste mistake, or unfortunate debug attempt maybe?)
I'm a bit too lazy to go check the SDK source right now, but I think it deliberately unsets the state parameter inside the session after the code was exchanged for a token, as part of making the whole process more secure - so that when you call getAccessToken a second time, it fails.
If anyone still with this proglem just add a session_start() at the begining of the callback file.
Well I faced the same error today and I got my solution from tutorials point
In your callback file, just add this line and you're good to go
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
I know I'm late to the party, but I faced this error, and I don't believe my solution was covered in the above responses, so here it goes:
One reason this error may arise is if you submit the same URL login request to Facebook more than once. For example, a user may impatiently click on a login button more than once, triggering multiple submissions of the URL. In my case, the solution was to intercept all clicks after the first with a JavaScript function.
Change version to v2.10 Check graph you are using in configuration php file
// Call Facebook API
Both the things didn't work for me for v14.
Adding that small code just before $helper = $fb->getRedirectLoginHelper(); worked.
Here's the code that actually worked -
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
Still got this error after clicking login..
SDK Exception: Cross-site request forgery validation failed. Required
param "state" missing from persistent data.
I'll just follow and read the previous topic and comments above. And double check URL of Valid OAuth redirect URI.
Here's what id done. Well appreciated if you can share some thoughts and correct me..
create-acc.php
///FACEBOOK SIGNUP
session_start();
include_once 'config-facebook.php';
try {
$accessToken = $helper->getAccessToken();
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
echo "Response Exception: " . $e->getMessage();
exit();
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
echo "SDK Exception: " . $e->getMessage();
exit();
}
$redirectURL = "http://".$_SERVER['SERVER_NAME']."/create-acc.php";
$permissions = ['email'];
$fLoginURL = $helper->getLoginUrl($redirectURL, $permissions);
$facebook_button ='
<div style="background-color:white; color:#4b5563; cursor:pointer;" class="inline-flex border-2 py-1.5 px-5 rounded text-lg border-gray-300">
<div style="margin-top:5px;">
<img style="width:25px;" src="./assets/apps/facebook-logo-2019.png"/>
</div>
<b>Sign up with Facebook</b>
</div>
';
config-facebook.php
include_once 'Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '**************',
'app_secret' => '*************',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
I'm literally new on this programming and still learning. So if you help it really save my time and learn on provided codes.And if I tried to add some callback codes to get a data, it looks like this on my work
create-acc.php add ons callback codes
///FACEBOOK SIGNUP
session_start();
include_once 'config-facebook.php';
if (isset($accessToken))
{
if (!isset($_SESSION['facebook_access_token']))
{
//get short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
//OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
//Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
//setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else
{
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
if (isset($_GET['code']))
{
header('Location: ./');
}
try {
$fb_response = $fb->get('/me?fields=name,first_name,last_name,email');
$fb_response_picture = $fb->get('/me/picture?redirect=false&height=200');
$fb_user = $fb_response->getGraphUser();
$picture = $fb_response_picture->getGraphUser();
$_SESSION['fb_user_id'] = $fb_user->getProperty('id');
$_SESSION['fb_user_name'] = $fb_user->getProperty('name');
$_SESSION['fb_user_email'] = $fb_user->getProperty('email');
$_SESSION['fb_user_pic'] = $picture['url'];
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Facebook API Error: ' . $e->getMessage();
session_destroy();
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK Error: ' . $e->getMessage();
exit;
}
}
else
{
$redirectURL = "http://".$_SERVER['SERVER_NAME']."/create-acc.php";
$permissions = ['email'];
$fLoginURL = $helper->getLoginUrl($redirectURL, $permissions);
$facebook_button ='
<div style="background-color:white; color:#4b5563; cursor:pointer;" class="inline-flex border-2 py-1.5 px-5 rounded text-lg border-gray-300">
<div style="margin-top:5px;">
<img style="width:25px;" src="./assets/apps/facebook-logo-2019.png"/>
</div>
<b>Sign up with Facebook</b>
</div>
';
}
and the config-facebook.php
session_start();
include_once 'Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '************',
'app_secret' => '************',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
try {
if(isset($_SESSION['facebook_access_token']))
{$accessToken = $_SESSION['facebook_access_token'];}
else
{$accessToken = $helper->getAccessToken();}
} catch(FacebookResponseException $e) {
echo 'Facebook API Error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK Error: ' . $e->getMessage();
exit;
}
and the result here
Fatal error: Uncaught Facebook\Exceptions\FacebookSDKException: Cross-site request forgery validation failed. Required param "state" missing from persistent data. in /www/wwwroot/fruitask.com/Facebook/Helpers/FacebookRedirectLoginHelper.php:244 Stack trace: #0 /www/wwwroot/fruitask.com/Facebook/Helpers/FacebookRedirectLoginHelper.php(221): Facebook\Helpers\FacebookRedirectLoginHelper->validateCsrf() #1 /www/wwwroot/fruitask.com/config-facebook.php(20): Facebook\Helpers\FacebookRedirectLoginHelper->getAccessToken() #2 /www/wwwroot/fruitask.com/create-acc.php(162): include_once('/www/wwwroot/fr...') #3 {main} thrown in /www/wwwroot/fruitask.com/Facebook/Helpers/FacebookRedirectLoginHelper.php on line 244
Please do share some thoughts or any alternative way I can implement Facebook login on my website using PHP. Thanks in advance
This is my controller and it's working fine.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('session');
}
function index(){
$this->load->view("welcome_message");
}
function fblogin(){
$fb = new Facebook\Facebook([
'app_id' => '213234637467346734',
'app_secret' => '7346762476374673647',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','user_location','user_birthday','publish_actions'];
// For more permissions like user location etc you need to send your application for review
$loginUrl = $helper->getLoginUrl('http://localhost/facebooklogin/welcome/fbcallback', $permissions);
header("location: ".$loginUrl);
}
function fbcallback(){
$fb = new Facebook\Facebook([
'app_id' => '1767865763452676',
'app_secret' => '2454f5b88ea788b407297f39400b796b',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$this->session->set_userdata('state',$_GET['state']);
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;
}
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?fields=id,name,email,first_name,last_name,birthday,location,gender', $accessToken);
// print_r($response);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'ERROR: Graph ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'ERROR: validation fails ' . $e->getMessage();
exit;
}
// User Information Retrieval begins................................................
$data['me'] = $response->getGraphUser();
$data['accessToken'] =$accessToken;
$this->load->view("home",$data);
}
}
When I refresh the home page its give me this error
Facebook SDK returned an error: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
Here I changed the app_id and app_secret for security reason.and i also load the session library in autload file
I have solve the problem.I just add this code in try block where i get the access token
if(!$this->session->userdata('token')){
$accessToken = $helper->getAccessToken();
$this->session->set_userdata('token',$accessToken);
}
else{
$accessToken = $this->session->userdata('token');
}
My facebook php sdk getLogoutUrl is not working when i click on my logout url.
it takes me back to my given redirect url but it does not destroy my facebook session i can still see my var_dump($fb_data) array on my page and logout url.
Here is my code i am using codeigniter
My lib_login library function facebook code
public function facebook()
{
$facebook_default_scope = explode(',', $this->ci->config->item("facebook_default_scope"));
$facebook_app_id = $this->ci->config->item("facebook_app_id");
$facebook_api_secret = $this->ci->config->item("facebook_api_secret");
// init app with app id and secret
FacebookSession::setDefaultApplication($facebook_app_id, $facebook_api_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper(site_url('login/facebook'));
// see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
// create new session from saved access_token
$session = new FacebookSession($_SESSION['fb_token']);
// validate the access_token to make sure it's still valid
try {
if (!$session->validate()) {
$session = null;
}
} catch (Exception $e) {
// catch any exceptions
$session = null;
}
}
if (!isset($session) || $session === null) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
// handle this better in production code
print_r($ex);
} catch(Exception $ex) {
// When validation fails or other local issues
// handle this better in production code
print_r($ex);
}
}
// see if we have a session
if (isset($session)) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession($session->getToken());
// graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me?fields=id,name,accounts{access_token,category,name,id,perms},permissions');
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
$logoutUrl = site_url('login');
$fb_data = array(
'me' => $graphObject,
'loginUrl' => $helper->getLoginUrl($facebook_default_scope),
'logoutUrl' => $helper->getLogoutUrl($session,$logoutUrl),
);
$this->ci->session->set_userdata('fb_data', $fb_data);
} else {
$fb_data = array(
'me' => null,
'loginUrl' => $helper->getLoginUrl($facebook_default_scope),
'logoutUrl' => $helper->getLogoutUrl($session,$logoutUrl),
);
$this->ci->session->set_userdata('fb_data', $fb_data);
}
return $fb_data;
}
Here is my function of my controller
public function facebook()
{
$fb_data = $this->lib_login->facebook();
if (isset($fb_data['me'])) {
echo "<pre>";
var_dump($fb_data);
echo "</pre>";
echo 'logout';
} else {
echo 'Login';
}
}
When ever i login to my account using this code then the logout url and $fb_data array appears on my page but when i logout and refresh my page it is still their.Can some one tell what i am doing wrong here.
Try something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'lib_login'));
$this->fb_data = $this->lib_login->facebook();
}
/**
* facebook login
*
* #return void
* #author appleboy
**/
public function facebook()
{
// check login data
if (isset($this->fb_data['me'])) {
var_dump($this->fb_data);
} else {
echo 'Login';
}
}
public function logout()
{
if ( isset($this->fb_data['me']) ) {
$this->session->unset_userdata('fb_data');
}
redirect('login/facebook', 'refresh');
}
}
/* End of file login.php */
/* Location: ./application/controllers/login.php */
Here is a simple query from the linkedIn documentation that works:
$groupData = $this->linkedin->fetch('GET', "/v1/groups/{id}/posts");
It returns 10 records. But the moment I attach the count and start parameters like this:
$groupData = $this->linkedin->fetch('GET', "/v1/groups/{id}/posts?count=20&start=0");
I get this error:
A PHP Error was encountered
Severity: Warning
Message: file_get_contents(https://api.linkedin.com/v1/groups/{id}/posts&count=20&start=0?oauth2_access_token=xxxxx8&format=json): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
Filename: libraries/Linkedin.php
Line Number: 85
Here is my complete code:
class Auth extends CI_Controller {
function __construct() {
parent:: __construct();
$this->load->library('linkedin'); // load library
session_name('linkedin');
session_start();
}
// linkedin login script
function index() {
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
// load any error view here
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
$this->linkedin->getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
$this->linkedin->getAuthorizationCode();
}
}
// this is where I am fetching linkedIn data
$groupData = $this->linkedin->fetch('GET', "/v1/groups/{id}/posts?count=20&start=0");
// this is where I am sending the data to the idea model to be saved
if ($groupData) {
var_dump($groupData); exit();
// foreach ($groupData->values as $data) {
// var_dump($data->creator->firstName); exit();
// }
$this->load->model('idea_model');
$this->idea_model->store_ideas($groupData);
} else {
// linked return an empty array of profile data
}
}
}
The linkedIn library is the code sample given by linkedIn in their documentation:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* CodeIgniter Linked API Class
*
*
* #package CodeIgniter
* #subpackage Libraries
* #category Libraries
* #author Muhamamd Hafeez
*/
class Linkedin {
function __construct(){
}
public function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
public function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
public function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
}
/* End of file Linked.php */
/* Location: ./application/libraries/linkedin.php */
Please help me fix this. What am I doing wrong?
The problem is that your parameter list has 2 two ?'s. I would change the fetch method to take an optional $params parameter:
public function fetch($method, $resource, $params = array(), $body = '') {
// Cast, just in case
$params = (array)$params;
// Add mandatory parameters
$params['oauth2_access_token'] = $_SESSION['access_token'];
$params['format'] = 'json';
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
And call it like so:
$groupData = $this->linkedin->fetch('GET', "/v1/groups/{id}/posts", array("count" => 20, "start" => 0));