PHP Facebook SDK, Get Albums - php

I know there are tons of questions about facebook and php sdk, grabbing and taking some infos. but i got different question.
imagine that i already did everything.
authorized user by fb javascript sdk + php and ajax, stored basic infos in database and forgot facebook. now my user can login with my database with facebook information.
in my database i have:
id user_fb say_smth access register mail limitTime count
notice there is user_fb, which is facebook id.
when user logs in, i create session and get it with jquery/ajax/json parse
// Cache hit
// $start = microtime(true);
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT fb_id, email, password FROM sp_signup WHERE email = '{$email}' AND password = '{$passw}' LIMIT 1");
$check_row = $res->num_rows;
$check_array = $res->fetch_assoc();
$res->free();
if ($check_row == 0)
{
print json_encode( array("status" => "user does not exists", "code" => 10) );
} else {
if ( ! isset($_SESSION) )
{
session_start();
$_SESSION[ "dh_user_fb" ] = $check_array["fb_id"];
print json_encode( array("status" => "", "code" => 4, "session" => $_SESSION[ "dh_user_fb" ]) );
} else {
print json_encode( array("status" => "", "code" => 4, "session" => null) );
}
} // endcode
and jquery ajax success method
var gotJson = jQuery.parseJSON(jsonR);
var code = gotJson['code'];
var status = gotJson['status'];
var session = gotJson['session'];
if ( session == null ){
if ( code == 11 ){
$("#email_try").html(status).fadeIn(600);
$("#email_try").html(status).fadeOut(2200);
} else if ( code == 12 || code == 10 ) {
$("#passw_try").html(status).fadeIn(600);
$("#passw_try").html(status).fadeOut(2200);
} else {
//
}
}
so when user enters, there is $_SESSION["fb_id"];
I need to get logged in users photo albums by php and copy it on my local ftp or take src from facebook. it is not neccessery.
i'm only interested, if there is any chance to do this without access tokens and logins and so on, i want to do this only by fb_id;
Thanks...

you can't get it directly without calling api.
get user permission to access his photos
$loginLink = $facebook->getLoginUrl(array(
'scope' => 'user_photos,user_photo_video_tags'
));
then use this api to get user photos :
$photos = $facebook->api('/me/photos?access_token=' . $token);

Related

Wordpress Admin Login programmatically

Im trying to create a small widget that gets the authenticated user from the actual web app, which is in python/django(hosted on example.com), and sets headers across subdomains(*.example.com). The users. The users logged in on example.com should be able to use WordPress(hosted on blog.example.com) without again having to register/login to wordpress.
Here I am trying to autologin(without password for WordPress) those users on WordPress so they can write blogs.
I have written a small shortcode that does the above thing. Though the user is logged in, the /wp-admin still redirects to the login page. Below is the shortcode I wrote:
<?php
echo "STARTED";
$url = "https://app.example.com/api/user_profile/?my=1";
$arguments = array(
'method' => 'GET',
'cookies' => $_COOKIE
);
$response = wp_remote_get($url, $arguments );
if ( !is_wp_error( $response ) ) {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
$final_user = array();
$userID;
$email;
$username;
foreach ( $data as $datapoint ) {
$email = $datapoint->email;
$username = $datapoint->username;
}
$user_exists = get_user_by("email", $datapoint->email);
if (!$user_exists){
$user_info = array();
$new_user_id = wp_create_user($datapoint->username, $datapoint->username, $datapoint->email);
$final_user = get_user_by("id", $new_user_id);
} else {
$final_user = $user_exists;
}
// Login the user now
foreach ( $final_user as $fuser ) {
$userID = $final_user->ID;
}
echo "<br/>uerID - ";
echo $userID;
$user = get_user_by("login",$username);
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID);
do_action( 'wp_login', $user->username, $user );
echo "<br/> inside done";
} else {
echo "Something went wrong";
}
echo "<br/>-----------done"
?>
Im not sure what is wrong with the above code. I want the user to access /wp-admin so they can write posts if they are loggedin on our webapp. We are making an API request to our web app from our wordpress(protected private API for our use only) to get authenticated users on our app.
This is the first time wrote PHP code, so it's not production ready (will write the optimal code later).
Any help would be very appreciated. Please do let me know if there is anything more I need to provide.

Laravel webapp login from iOS with Facebook SDK

i have a webapp working with Laravel.
i have some users registered in my webapp.
users who dont want to create a account can use Facebook/Google+ login.
to make Facebook/Google+ connection, i used a oAuth2 connexion with :
oauth-4-laravel
on the iOS application, users can login using username and password but they can login too with Facebook/Google+ using FB/G+ SDK.
my questions is, how to login on my webapp users from iOS who are connected by Facebook/Google+.
artdarek/oauth-4-laravel require a "code" given by the social network, and i dont know how to get it on iOS.
here the code for users who want to connect to the webapp by web browser :
public function loginWithFacebook() {
// 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' ), true );
// $message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
// dd($result);
if (User::where('fb_id','=', $result['id'])->count() == 0) {
$user = new User;
$user->firstname = $result['first_name'];
$user->lastname = $result['last_name'];
$user->username = $result['email'];
$user->email = $result['email'];
$user->fb_id = $result['id'];
$user->yearofbirth = substr($result['birthday'],6,9);
$user->fk_role=3;
if ($result['gender'] == 'male') {
$user->sex = 1;
}
else{
$user->sex = 0;
}
$user->save();
}
else{
$user = User::where('fb_id','=', $result['id'])->first();
}
Auth::login($user);
Userslog::log('desktop_facebook_login');
return Redirect::to('/')->with('message', 'Logged in with Facebook');
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
i finally find a solution in the issues of oauth-4-laravel on github,
i just have to use iOS AccessToken and connect the user to the webapp using this token.
here the code laravel code to use the Token ;)
use OAuth\OAuth2\Token\StdOAuth2Token;
$token_interface = new StdOAuth2Token(Input::get( 'token' ));
$network = OAuth::consumer( 'Facebook' );
$network->getStorage()->storeAccessToken('Facebook', $token_interface);
$result = json_decode( $network->request( '/me' ), true );
$fb_id = $result['id'];
To Resume,
the best way is ; to login with Facebook/Google+ on iOS,
when login finish with success, get the AccessToken and send to the webapp.And then the webapp use you token to login again the user to Facebook/Google+ and finally , the user is verified and you can login it to laravel webapp.
have a nice day.
I'm quite in the same situation here.
With the solution you provide, how are you preventing other applications to send their own AccessToken and access your Laravel application?
I assume you send the token via a POST request from you iOS app to a certain endpoint of your Laravel app, therefore any developper knowing this endpoint could pretend to be logged on your mobile application, no?

Twitter OAuth Error 220

I have an application that Authenticates a user using OAuth and gets all of the permissions needed to post an update for a twitter user but when i try to actually do the post I get this response:
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 220 [message] => Your credentials do not allow access to this resource. ) ) )
here is my code for the authentication when they first link twitter:
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken(TWITTER_CALLBACK_URL);
// Saving them into the session
$_SESSION['twitter_oauth_token'] = $request_token['oauth_token'];
$_SESSION['twitter_oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// Remember to adds script for error handling and reporting but for now kill the script
die('Something wrong happened.');
}
And here is what happend when they get to the callback:
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['twitter_oauth_token']) && !empty($_SESSION['twitter_oauth_token_secret'])){
// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth(TWITTER_KEY, TWITTER_SECRET, $_SESSION['twitter_oauth_token'], $_SESSION['twitter_oauth_token_secret']);
// Let's request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// Save it in a session var
$_SESSION['access_token'] = $access_token;
// Let's get the user's info
$user_info = $twitteroauth->get('account/verify_credentials');
if(isset($user_info->error)){
// Something's wrong, go back to square 1
header('Location: networks.php?connect=2');
} else {
// Let's find the user by its ID
$query = mysql_query("SELECT * FROM connected_accounts WHERE oauth_provider = 'twitter' AND oauth_uid = ". $user_info->id);
$result = mysql_fetch_array($query);
// If not, let's add it to the database
if(empty($result)){
$query = mysql_query("INSERT INTO connected_accounts (user_id, account_id, oauth_provider, acct_usr_id, oauth_uid, username, token, secret) VALUES ('".${'User'}['id']."', '2', 'twitter', ".$user_info->id.", ".$user_info->id.", '".$user_info->screen_name."', '".$access_token['oauth_token']."', '".$access_token['oauth_token_secret']."')");
$query = mysql_query("SELECT * FROM connected_accounts WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
// Update the tokens
$query = mysql_query("UPDATE connected_accounts SET token = '".$access_token['oauth_token']."', secret = '".$access_token['oauth_token_secret']."' WHERE oauth_provider = 'twitter' AND oauth_uid = ".$user_info->id);
}
$_SESSION['id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['oauth_uid'] = $result['oauth_uid'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token'] = $result['token'];
$_SESSION['oauth_secret'] = $result['secret'];
header('Location: manage_accounts.php');
}
} else {
// Something's missing, go back to square 1
header('Location: networks.php?connect=2');
}
// Get our permenant token
$response = $twitter_client->getAccessToken($_GET['oauth_verifier']);
// If we did not receive a permenant token, notify the user
if (!$response['oauth_token']) {
$message = '<center><div class="error">An error occurred while linking your Twitter account. Please try again later.</div></center>';
// Otherwise
} else {
// Update our info
mysql_query('UPDATE `connected_accounts` SET `token` = "'.$response['oauth_token'].'", `acct_usr_id` = "'.$response['user_id'].'", `secret` = "'.$response['oauth_token_secret'].'" WHERE `account_id` = 2 AND `user_id` = '.${'User'}['id']) or die(mysql_error());
// Send the user to the post page
header('Location: manage_accounts.php'); exit;
}
I am using the Library from https://github.com/abraham/twitteroauth
Everything used to work just fine but now it isn't working.
It seems that it has something to do with application only authentication but I am using OAuth which is supposed to allow posting to statuses/update

Laravel Facebook-Login / missing email

I am trying to create a Facebook-Login in my Laravel application. However, the array I get with all the user information does not contain the users email even though I already ask for permission to receive the email.
This is my code:
Route::get('login/fb', function() {
$facebook = new Facebook(Config::get('facebook'));
$params = array(
'redirect_uri' => url('/login/fb/callback'),
'scope' => 'email',
);
return Redirect::to($facebook->getLoginUrl($params));
});
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$me = $facebook->api('/me');
return $me;
Returning $me gives me all the important user information besides the email address.
Is there any way to fix this?
Any help would be much appreciated.
Thanks.
There are instances that facebook will not return an email. This can be because the user has not set a primary email, or their email has not been validated. In this case, your logic should check to see if an email was returned, if not, use their facebook email. FacebookUsername#facebook.com
//I used with sentry
// 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 );
}

"Register With Twitter" Button - How to

I have just recently created a "Register With Facebook" button for our website, and I am attempting to achieve the same thing with Twitter.
However I am having difficulty finding precise step by step instructions for accomplishing the task with Twitter.
What I did with Facebook was:
// (1) - Create new Facebook object:
$facebook = new Facebook(array(
'appId' => $this->config->item('facebook_app_id'),
'secret' => $this->config->item('facebook_app_secret')
));
// (2) - Get all fields relating to logged-in user:
$facebook_user = $facebook->getUser();
// (3) - Retrieve all fields which we need to register a user on OUR website:
if ($facebook_user){//if logged in to Facebook:
$facebook_user_profile = $facebook->api('/me');
$fb_email = $facebook_user_profile["email"];
$fb_first_name = $facebook_user_profile["first_name"];
$fb_last_name = $facebook_user_profile["last_name"];
// ...
}
QUESTION 1:
How do I achieve the same thing with Twitter?
QUESTION 2:
I have created an app (https://dev.twitter.com/apps/new) and now have the 4 codes (Consumer key, Consumer secret, Access token, Access token secret), I have no idea what these codes are, but do I need these 4 codes for the task at hand?
Any suggestions or online resources would be great...
Download tmhOauth class https://github.com/themattharris/tmhOAuth
$settings['consumer_key'] = 'your_key';
$settings['consumer_secret']= 'your_secret';
parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
require 'twitter/tmhoauth.php';
require 'twitter/tmhUtilities.php';
$this->_twitter = new Tmhoauth($settings);
if ( isset($_SESSION['access_token']) ) { //if already logged
$this->_twitter->config['user_token'] = $_SESSION['access_token']['oauth_token'];
$this->_twitter->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret'];
$code = $this->_twitter->request('GET', $this->_twitter->url('1/account/verify_credentials'));
if ($code == 200) {
// save user data
}
} elseif (isset($_REQUEST['oauth_verifier'])) { // we're being called back by Twitter
$code = $this->_twitter->request('POST', $this->_twitter->url('oauth/access_token', ''), array(
'oauth_verifier' => $_REQUEST['oauth_verifier'],
'oauth_token' => $_REQUEST['oauth_token']
));
if ($code == 200) {
$_SESSION['access_token'] = $this->_twitter->extract_params($this->_twitter->response['response']);
// save user data
}
} else{ // login url for your "connect with twitter" button
$here = tmhUtilities::php_self();
$callback = isset($_REQUEST['oob']) ? 'oob' : $here;
$params = array( 'oauth_callback' => $callback );
$code = $this->_twitter->request('POST', $this->_twitter->url('oauth/request_token', ''), $params);
if ($code == 200) {
$test_this = $this->_twitter->extract_params($this->_twitter->response['response']);
$_SESSION['oauth'] = $test_this;
$method = isset($_REQUEST['authenticate']) ? 'authenticate' : 'authorize';
$force = isset($_REQUEST['force']) ? '&force_login=1' : '';
$authurl = $this->_twitter->url("oauth/{$method}", '') . "?oauth_token={$test_this['oauth_token']}{$force}";
$this->_loginUrl = $authurl;
}
}
User's email address cannot be retrieved with twitter api.

Categories