Facebook openID authentication for a company? - php

I have been implementing a Google/Facebook authentication system on my site. I use their respective service to authenticate the user, then use the results to instantiate sessions on my end. The Google one is running no problem, but for the Facebook one I have hit a snag.
I can authenticate users with no problem, but when trying to authenticate a company or other Facebook page type, it fails.
For instance, using the GraphAPI, I am able to retrieve the values shown in one of their examples https://graph.facebook.com/btaylor and store it properly.
But when I try to use the same system to authenticate a company ( https://graph.facebook.com/nike for instance), it fails since the objects are not part of the user results returned by the GraphAPI.
Normal stuff setting up the call:
$FBcookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
$user = json_decode(file_get_contents_curl('https://graph.facebook.com/me?access_token='.$FBcookie['access_token']));
And when storing results, it works fine as a user:
$_Fname =$user->first_name;
$_Lname =$user->last_name;
But trying to access the expected attributes seen at the Nike example above, nothing gets returned.
I even tried echoing out the object to see whats there:
print('<pre>');
print_r($user);
print('</pre>');
For the user, I see everything, for non-user (company, event or other page type), I see nothing.
Question is, has anyone seen what other objects we may need to query via the GraphAPI? The Facebook developer pages are all over the place and have no real concise tutorials on this.
Any help would be much appreciated ;)

Company/Page info on facebook is as follows:
$user->id;
$user->name;
$user->picture;
$user->link;
$user->likes;
$user->category;
$user->website;
$user->username;
$user->description;
$user->public_transit;
So $user->first_name; and $user->last_name; don't exist.
You could try something like this :
if(empty($user->first_name)&&empty($user->last_name)){
//probably company set $user->username;
}

Related

How to get the ID of the current Contact with PHP Mautic API?

As I couldn't find anything in the documentation I might have a general understanding issue. But what I want to achieve is getting the ID of the current Contact browsing the Site. To get user details I always have to know the ID, like documented here: https://developer.mautic.org/#contacts
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $settings['baseUrl']);
$contact = $contactApi->get(3);
Is there a way to the ID of the current Contact? I want to play highly customized content on the website and an entry point to get user details.
It's a REST API, so you should get a response in any case. What's the content of the response (eg. what contains $contact)? What's the HTTP code of the response? Error messages?
However... I'm not familiar with this particular API, but the principles are always the same
https://developer.mautic.org/?php#list-contacts
Without any query parameters it should give the full list of contacts. Each of the contact records should come with an ID for the details:
https://developer.mautic.org/?php#get-contact
As said, I'm not familiar with the API, so it could be that you get a contact list only from a higher entity, like a Company or so.
I can recommend Postman (https://www.postman.com/), a neat tool to make REST API requests while having full control over all the details.
Assuming that you're trying to get the details of the current logged in user.
You can use themautic.helper.user helper to do that as shown below:
<?php
$user = $this->get('mautic.helper.user')->getUser();
$firstName = $user->getFirstname();
$lastName = $user->getLastname();
$email = $user->getEmail();
$profile = $user->getProfile();
$role = $user->getRole()->getName();
if ($role->isAdmin()) {
// do something
}
Ref: https://developer.mautic.org/#services44
In order to do what you want here I do not think you actually need the API to get the user id. Mautic has dynamic content and as long as the user has a cookie dropped on his browser you can use Dynamic Content to say "Hi {contactfield=firstname}, welcome back.
You can actually call any custom field into the dynamic content slot.
Check out dynamic content which is found under the Components section in the left menu

Basic access authentication Header

I'm currently working on a REST client in PHP using Zend Framework and ran into a problem.
I currently have two dummy services that I'm testing with; one is 'noauth' which requires no authentication and just returns some JSON, the other is 'auth' which required authentication and returns more specific JSON. Accessing both directly from the web works without a problem, for example navigating to 'https://example.org/example/dummy/noauth' displays the JSON on the webpage and 'https://example.org/example/dummy/auth' displays a dialog box asking for the user to log in.
My goal is to be able to access those different services from my main web application. The first thing that is required is for the user to log on to this web app. Then they'll be able to call the different services from that web application. I was able to get the noauth working quite easily using this:
$base_url = 'https://example.org';
$client = new Zend_Rest_Client($base_url);
$endpoint = '/example/dummy/noauth';
$response = $client->restGet($endpoint);
But I am unable to get the 'auth' one working without it asking for the user's username and password every time. Currently, I'm using hard coded values for this, but eventually, it'll be the values that the user used to log in that are stored in the session. Here are some of the things I've tried:
$user = base64_encode('username:password');
$client->setHeaders('Authorization: Basic '.$user);
And also:
$client = new Zend_Http_Client();
$client->setAuth('username', 'password', Zend_Http_Client::AUTH_BASIC);
None of these seem to be working. Does anyone have any ideas on how to achieve what I need?
You have to call the getHttpClient() on the REST object, and then call the function you need that's normally in the Zend_Http_Client() after that.
Here's a quick example:
$client = new Zend_Rest_Client($base_url);
$client->getHttpClient()->setAuth($username, $password, Zend_Http_Client::AUTH_BASIC);
...
By doing this, it'll use the username and password in the variables not ask the user every time they want to access the page.

Twitter - Already have OAuth database, how do I know who the user is?

I've already got a database set up with a table that is successfully populated with the final (permanent?) OAuth User Token and OAuth User Secret. The thing I don't understand is how I'm supposed to know what the current user's ID is, especially when it's been 2 weeks since their last login. My app is authorized by all of its users, so theoretically Twitter can look at the list of authorized apps for the current user and share the Twitter User ID, right? Isn't there some good way of requesting (on behalf of the current user) what his ID is? I feel like the temporary tokens should be able to facilitate this somehow... If it helps, every user in my app is just a Twitter account with some extra info. I'm just looking for the best way to utilize the tokens and secrets that are in my database...
I'm using PHP (libraries: Codebird-PHP & tmhOAuth) so if you could show an example in PHP that'd be nice, but really I just want to know how I'm supposed to use this information that I'm storing.
Thanks!
I'm assuming you store the data together with some username or user id that identifies the users of your website and links them to their proper twitter id. In order to get the basic info of your user, after authorization, you have to use the endpoint https://api.twitter.com/1.1/account/verify_credentials.json with a GET.
The documentation for the 1.1 API can be found here.
This returns an array. You find the username uder "screen_name" and the user id under "id" or "id_string".
The question is a possible duplicate of Get current user's info from Twitter API, but I've added an answer because that discussion points to the deprecated API. The code you find there, nevertheless, is still useful (it appears to use Abraham William's library, but the steps are basically the same). Replace the classes and functions with those you have in Matt Harris' library. I don't know codebird, sorry!
EDIT: I am also providing a code sample (tested and working, although I have issues with tmhOAuth, so I use it occasionally only for myself. I have noticed that, when I try to post, it sometimes returns some weird error codes and I can't figure out why):
// Authentication page, with button. You have already connected to your database
$mywebsiteuser = $_SESSION['website_user_id'];
$query= "SELECT * FROM `table_where_you_store_twitter` WHERE website_user_id ='$mywebsiteuser'";
$sql= $mysqli->query($query) or die($mysqli->error.__LINE__); // or whatever else to check is the query fails.
if ($sql->num_rows != 0){
//etc. retrieve data and set the sessions.
// already got some credentials stored?
if ( isset($_SESSION['access_token']) ) {
$tmhOAuth->config['user_token'] = $_SESSION['access_token']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret'];
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1/account/verify_credentials'));
if ($code == 200) {
$resp = json_decode($tmhOAuth->response['response']);
echo $resp->screen_name;
echo $resp->id;
//Etc. Instead of printing them you it's a good idea to store them in the db.
} else {
outputError($tmhOAuth);
}
// we're being called back by Twitter
} elseif (isset($_REQUEST['oauth_verifier'])) {
$tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret'];
$code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array(
'oauth_verifier' => $_REQUEST['oauth_verifier']
));
if ($code == 200) {
//etc.
Anyhow, all in all, in order to get the info of a user you need them to authorize your app first. I check if I have something from my user with the user's session variables on my website, not through twitter. If I have nothing stored, I ask them to authorize the app. I hope this helps.
Access Token : 1274865264-QiVY50RGnmJz6AU9IPRxxiXfv4DYqo0nj6wg8hS
Access Token Secret : fZQnHSuSpwARicIdLqkqQLy1JeG9LxrbNIRKypWcGR
First part of Access Token is user id

How to store data from facebook to local variable?

Im using the SDK 3 by facebook, and to store the facebook id i am doing this:
$facebook_id = $user;
Which works a treat! However... i cannot access individual items in the array, like i remember with the previous SDK you could do:
$first_name = $me['first_name'];
However, i have tried that, and $user['first_name'] and stuff but getting no where! I cant find any documentation of this either on their dev website or on the internet :/
Many thanks.
Ian.
Seems like $user is just the Facebook User ID that you get through the authentication flow. If you want to get user info, you need to make a separate Graph call, like so:
$res = $facebook->api('/me');
$first_name = $res['first_name'];

Facebook Graph API Search without logged in user

I'm trying to issue a Facebook Graphp API search call for groups with a specific search term. The important fact is to search for groups not only beginning with the term but also to search for the term within the group name. So something like that.
FQL => SELECT * FROM groups WHERE groupname LIKE '%term%'
As far as i know this isn't possible in FQL. Therefore I have to use the Graph API search.
http://developers.facebook.com/docs/api#search
But I have to issue th call even if the user isn't logged in. Is this possible
or is there a possibility to log in a default user with some curl calls without user interaction (without displaying a form)?
If there is a simplier solution (for instance with FQL) please tell me.
I work with the graph API and not with the FQL so I'm not 100% sure on the differences etc etc... however a way I'd try is using the cURL script at http://developers.facebook.com/docs/authentication/#authenticating-users-in-a-web-application to get an auth token, then you must add the received auth token to the graph parameters as you can see on the site (a good way to test in the graph api is to click on the example likes or queries given while logged into facebook then copying the api code and breaking up the process like that [testing that you can get results you want from the query, testing that you can get your auth token then combining] so that you know what parts are 'problem' parts).
If that fails, scroll down to the "single sign-on with java-script" and have a look at the code they use to get the auth token from the facebook cookie, I notced you may be able to access that cookie from FQL.
I hope this was of some help! Please tell me if those ideas didn't work.
Jon
Using PHP-SDK 3.1.1, no auth or access_token needed. This sample assumes you have PHP-SDK installed on the page.
Use a form post the question to the page, arguments for get and post
are included. This will return the array from search https://graph.facebook.com/search?q=facebook&type=group
<?php
$q = urlencode($_GET['qs']);
if(!$_GET['qs']){
$q = urlencode($_POST['qs']);
if(!$_POST['qs']){
$q = "facebook";
}
}
$MEsearch = $facebook->api('/search?q='.$q.'&type=group');
foreach ($MEsearch as $key=>$value) {
$i=1;
foreach ($value as $fkey=>$fvalue) {
$i++;
if($fvalue[id]=="h"){
}else{
$groupname = $fvalue[name];
$groupid = $fvalue[id];
$groupversion = $fvalue[version];
echo $groupname. '<br />';
echo $groupid. '<br />';
echo $groupversion. '<br /><hr />';
}
};
};
?>
Sample Usage http://shawnsspace.com/plugins/photofeed.php Click Get Plugin at the bottom and use the search box to see this sample in action.

Categories