How is a plugin like facebook login plugin build up? - javascript

How does the plugin communicate with the facebook server without exposing too much information.
I would like to know how I can build myself a plugin that would communicate between the website it's installed on and my website.
My knowledge is limited to HTML5, CSS3, PHP5, Javascript and some Jquery.
I realise that there could be alot of ways, I was just wandering if you could point me in the right direction, or give me an idea. (: thanks in advance!

Take a look at the easyXDM framework, which allows you to do this quite easily, and if you have a chance, read Third Party JavaScript, which explains what you want to do in detail.
Some years ago, I wrote about this topic on scriptjunkie, it's as relevant now as then (although more browsers support postMessage now).

Create an application on developers.facebook.com
Download the facebook SDK for PHP since this is what you know (https://developers.facebook.com/docs/reference/php)
Read their guideline on how to implement login (it is easy and helpful)
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
This is a sample PHP function that you can build on:
function facebook_login()
{
$user = new user();
// Call Facebook API
if (!class_exists('FacebookApiException')) {
require_once ('facebook.php');
}
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$me = $facebook->api('/me'); //user
$uid = $facebook->getUser();
}
catch(FacebookApiException $e) {
echo error_log($e);
return;
}
}
// redirect user to facebook login page if empty data or fresh login requires
if (!$fbuser) {
$loginUrl = $facebook - getLoginUrl(array(
'redirect_uri' => $_SERVER["HTTP_REFERER"],
false
));
$logout = $facebook->getLoginUrl();
echo $loginUrl;
return;
}
// user details
$user->name = $me['name'];
$user->email = $me['email'];
$user->fbid = $uid;
// Check user id in your database
$user->selectbyfbid();
if ($user->database->rows > 0) {
// User exist, Show welcome back message
// User is now connected, log him in
}
else {
// User is new, Show connected message and store info in our Database
// Insert user into Database.
$user->insert_fb();
}
$_SESSION["access_token"] = $facebook->getAccessToken();
login_user($user);
}
In your HTML:
<a href="#" onclick="LoadingAnimate();">
<div class="fb-login-button"
onlogin="javascript:CallAfterLogin();"
data-width="600" data-max-rows="1"
data-show-faces="false"
scope="publish_stream,email,publish_actions,offline_access">
JavaScript code:
function CallAfterLogin(){
FB.login(function(response) {
if (response.status === "connected")
{
LoadingAnimate(); //show a waiting gif or whatever
FB.api('/me', function(data) {
if(data.email == null)
{
//Facbeook user email is empty, you can check something like this.
ResetAnimate();
}else{
AjaxResponse();
}
});
}
});
}
function AjaxResponse()
{
var myData = 'connect=1&action=fb_login';
jQuery.ajax({
type: "POST",
url: "/process_user.php",
dataType:"html",
data:myData,
cache: false,
success:function(response){
if(target.length > 1)
window.location.href = target;
else
location.reload();
},
error:function (xhr, ajaxOptions, thrownError){
//$("#results").html('<fieldset style="color:red;">'+thrownError+'</fieldset>'); //Error
}
});
}
I hope this helps you start!

Related

How to embed yammer private messages on my website?

I know how to embed a feed which has a certain ID. I already did it. Now I'd like to implement the following functionality: If a user receives a private message, it will appear on an embedded feed. The best option in my opinion would be to embed the whole "chat window", but I didn't find a single code sample on the web. How can I do that?
You cannot really embed private messages like you can with feeds, because Yammer's REST APIs (incl. private messages) require authentication via OAuth 2.0. That means you have to create a Yammer API application which will ask your users to log in and allow you to access their messages. The overall concept of that described in their documentation here and here.
Yammer provides several SDKs you can use, one of them is the Javascript SDK. I pieced togehter a simple example of how you can ask users to log in and then it will display their private messages. Mind you, this is a very simple solution, I just tested it on a single one-to-one conversation.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" data-app-id="YOUR-APP-CLIENT-ID" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
</head>
<body>
<span id="yammer-login"></span>
<div id="messages"></div>
<script>
yam.connect.loginButton('#yammer-login', function (resp) {
if (resp.authResponse) {
document.getElementById('yammer-login').innerHTML = 'Welcome to Yammer!';
}
});
var msgdiv = document.querySelector("#messages");
yam.getLoginStatus(
function(response) {
if (response.authResponse) {
console.log("logged in");
var myId = response.authResponse.user_id;
yam.platform.request({
url: "messages/private.json",
method: "GET",
success: function (response) {
console.log("The request was successful.");
var usernames = {};
response.references.forEach(function(ref){
if(ref.type === "user") {
usernames[ref.id] = ref.full_name;
}
});
response.messages.forEach(function(message){
var msg = document.createElement("span");
msg.innerHTML = usernames[message.sender_id] + ": " + message.body.parsed + "<br/>";
msgdiv.appendChild(msg);
})
},
error: function (response) {
console.log("There was an error with the request.");
console.dir(private);
}
});
}
else {
console.log("not logged in")
}
}
);
</script>
</body>
</html>
The response from the messages/private.json API endpoint is a JSON file that you can go through. It includes information about the message and the users involved in the conversation.

How can make automatic logout in php

I make web with login/logout.
If any link or button pressed on web I call ajax function to check login and if time expired logout user. In logout function I update my database.
But If I close browser or page user is not logged out and database is not updated. How can I add event listener for it.
PHP FILE
if (isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch ($action) {
case "checkLogin":
echo isLogged();
break;
case "logout":
logout();
break;
//and more
}
}
function isLogged() {
$data = array(
"login" => 0,
"username" => "null"
);
if(isset($_SESSION["user"]) && isset($_SESSION["start"])) {
$session_start = $_SESSION["start"];
//more then 600 sec
if(time() - $session_start < 600){
$data = array(
"login" => 1,
"username" => $_SESSION["user"]
);
}else{
logout();
}
}
return json_encode($data);
}
function logout(){
if(isset($_SESSION["user"])) {
$connection = connectToDB();
if($connection != null) {
$nickname = $_SESSION["user"];
$time = date("Y-m-d H:i:s");
$sql_statement = "UPDATE users SET is_login='0',last_login='$time' WHERE username='$nickname';";
$connection->query($sql_statement);
}
session_destroy();
}
}
There's no surefire way to "listen" for the user closing your window or, as #Taplar pointed out, powering off their computer. Using the technique of storing the login time within the session described in this question, you can run a cron or other kind of background task checking the database for sessions that are due to expire, and then expire them there.
You can add unload listener with async - false, so browser will wait while request is not finished:
$(window).unload(function() {
$.ajax({
type: 'GET',
url: '/logout',
async: false
});
});
Note that browser will "hang" during request, and it can confuse user

Javascript check if user already liked facebook page or not

In my website, when the visitor visit my web, if they have not liked my facebook page yet, i want to show Iframe like box.
I have seen many code in the web as well as in stackoverflow, but it seem doesn't work well. Here is my javascript code:
$(document).ready(function(){
FB.init({
appId : 'IDAPP',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "PAGE_ID";
var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid =" + user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
alert(rows);
if (rows.length == 1 && rows[0].uid == user_id) {
alert("like");
} else {
alert("not like");
}
});
} else if (response.status === 'not_authorized') {
alert("not authorized");
} else {
alert("not login");
}
});
});
Request with login or not login or not_authorize it work well, but when check for page is like or note, it doesn't run anything.
FQL is deprecated, and you would need to authorize a user with the user_likes permission - after that, it´s just a call to the /me/likes endpoint. You will not get that permission approved for like gating, because that´s not allowed. And you will not get it approved for "please like my page" overlays/iframes either :) - because the user does not benefit from that overlay in any way, it is only annoying.
There is only one possible way:
Subscribe to the like event: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
In the event callback, store a cookie so next time the user visits your page you don´t show the overlay/iframe anymore
Problem is, you don´t get the information if the liked or unliked something. And the user could just clear his cookies, so you can never be sure. My advice: don´t annoy your users with it.

retriving user information through Paypal Javascript login button

i have integrated paypal login button (javascript button) and when i am clicking on it its getting to the paypal site for authentication.
following is my code for paypal button
<span id="paypal"></span>
<script src="https://www.paypalobjects.com/js/external/api.js"></script>
<script>
var url = document.URL;
paypal.use( ["login"], function(login) {
login.render ({
"appid": "***",
"authend": "sandbox",
"scopes": "profile email address phone https://uri.paypal.com/services/paypalattributes",
"containerid": "paypal",
"locale": "en-us",
"returnurl": "http://stereotribes.dev/login"
});
});
</script>
after successful authentication its redirecting me to my server url again.
now my question is how to receive user information after authentication done.
i have searched around paypal site but i am not getting the clear idea to retrieve user informatoin.
can anybody help me in this?
Thanks in advance
Take a look at Instant Payment Notification (IPN). It will POST transaction data to a listener script you have configured on your server immediately when transactions happen, so you can automate tasks like updating your database, sending email notifications, etc. in real-time.
If you need data available on your return URL you can use Payment Data Transfer (PDT), which is very similar to IPN. The only thing about that is if people don't make it back to your return URL for some reason then that code will never run, so it's not recommended that you do any database updates, email notifications, or anything like that from your return URL.
Again, IPN will be triggered regardless of whether they make it back, so you can rest assured that code will run as expected.
After wasting 1 day i came up with the following code(solution), hope it may save someone's time ...
in my return url ("http://stereotribes.dev/login") i have written following code ...
if($_REQUEST['code']) {
$model->getPaypalEmail($_REQUEST['code']);
}
$_REQUEST['code'] (token) will be send by paypal and same code we have send back via curl to confirm identity...
public function getPaypalEmail($code){
if($code){
$strGetCodePaypalLoginDetails = $code;
if ($strGetCodePaypalLoginDetails != '') {
// Change this curl_init url according to your environment.
$ch = curl_init("https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice");
$flag_result = 1;
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => 'client_id=********&client_secret=*****&grant_type=authorization_code&code=' . $strGetCodePaypalLoginDetails,
CURLOPT_RETURNTRANSFER => 1
)
);
$arrResponse = curl_exec($ch);
if ($arrResponse === false) {
$arrResponseToken = 'Curl error: ' . curl_error($ch);
$flag_result = 0;
} else {
//Operation completed without any errors
$arrResponse = json_decode($arrResponse);
$strAccess_Token = $arrResponse->{'access_token'};
// Change this curl_init url according to your environment.
$chToken = curl_init("https://api.sandbox.paypal.com/v1/identity/openidconnect/userinfo/?schema=openid&access_token=" . $strAccess_Token);
curl_setopt_array($chToken, array(
CURLOPT_RETURNTRANSFER => 1
)
);
$arrResponseToken = curl_exec($chToken);
if ($arrResponseToken === false) {
$arrResponseToken = 'Curl error: ' . curl_error($chToken);
$flag_result = 0;
}
}
}
$arrResponseToken = json_decode($arrResponseToken, true);
print_r($arrResponseToken); //here you will get info from paypal
}
}

How to check if a user likes my Facebook Page or URL using Facebook's API

I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

Categories

Resources