Facebook edge.create - javascript

I have added the edge.create event and the event can be fired by the browser as well. But how can I check if the user has liked the page when they come back to the site?
<div id="fb-root"></div>
<script type="text/javascript">
<!--
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR_FACEBOOK_APP_ID', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
// OK
});
};

You are going to want to take a look at the signed_request documentation...
This signed request is facebooks method of validating that the user that made the request is indeed "who he/she says they are". It is encrypted and and uses your application secret to decode the values. Once you parse this signed request you will have the data you need.
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, '-_', '+/'));
}

If your question is about like for URL that you can get this information only for user who authorized your application and granted user_likes permission. To do so issue next FQL query:
SELECT user_id, url FROM url_like WHERE user_id = me() and url="URL_OF_PAGE"
If your page have an ID in OpenGraph (or you speak about Facebook Page), by querying Graph API for user's likes connection:
GET https://graph.facebook.com/me/likes/OPEN_GRAPH_OBJECT_ID
But if you speaking about Facebook Page and Application running in Page Tab, you don't need anything special to get this information since it will be passed within signed_request (sample php code using PHP-SDK):
$signedRequest = $facebook->getSignedRequest();
$data = $signedRequest['data'];
if ($data['page']['liked']){
// User is liked this Facebook Page
} else {
// User is not yet liked Facebook Page
}

Related

Cookie PHP LARAVEL

I have a cookie created in PHP with the jQuery method where the client enters a value in an input and this cookie is created with that Value while more values are created with a comma.
Example Creation cookie in jQuery:
<script type="text/javascript">
$(function () {
$("#btnAdd").click(function () {
if($('#addtokendelivery').val() === ''){
alert('Valor en Blanco');
}
else {
if ($.cookie('DeliveryToken')) {
$.cookie("DeliveryToken", $.cookie("DeliveryToken") + ',' + $("#addtokendelivery").val());
alert('Repartidores Agregados con TokenĀ“s: ' + $.cookie("DeliveryToken"));
} else{
$.cookie("DeliveryToken", $("#addtokendelivery").val());
alert('Repartidor Agregado con Token: ' + $.cookie("DeliveryToken"));
}
}
});
$("#btnRead").click(function () {
alert($.cookie("DeliveryToken"));
});
});
</script>
Example cookie in google chrome value:
DeliveryToken: value1,value2,value3
Example of variable to compare with in laravel:
$orderitemaddons32 = DB::table('users')->where('id', $id)->first();
$orderitemaddons32 = $orderitemaddons32->userdelivery_id;
//result variable dd laravel
"value1"
For example, if it detects that the value 1 is inside the cookie, it proceeds to display the page.
What I want is to verify in the laravel blade if the cookie matches the information of the variable that it creates in my function and to show the page, otherwise not to show it or to put a message that the information is not valid.
There are many ways to do what you want.
For having a condition before you proceed with a request or not, it's usual to use a middleware.
https://laravel.com/docs/8.x/middleware
From the middleware, you can continue with the request or to redirect the user to another page.
I guess your code could look like this in laravel:
$values = explode(',', $_COOKIE['DeliveryToken']);
if (in_array($orderitemaddons32, $values) {
//all good, proceed
// return $next($request);
} else {
/*
* return redirect()->route('home', [
* 'message' => 'The information is not valid'
* ]);
*/
}
Btw, I don't find it secure this kind of usage with cookies, I mean, setting them from javascript and not encrypting them and securing them in server side. One could easily change the value of cookie.
You could leave the cookies to laravel and thus use also the built-in functions.

How do I resend data from previous url after reCAPTCHA passed in the same page?

Data sent from this
www.example.com/modules/liaise/index.php?form_id=xxx
In normal condition, after submit, the page redirects to
www.example.com/modules/liaise/index.php
and sends mail.
Wantedly, I placed the reCAPTCHA in the same file (index.php).
Google captcha :
require_once "recaptchalib.php";
// your secret key
$secret = "secret key";
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
//send mail
} else {
echo '
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div id="html_element"></div>
<script>
var onloadCallback = function() {
grecaptcha.render("html_element", {
"sitekey" : "sitekey",
"callback" : correctCaptcha
});
};
var correctCaptcha = function(response) {
location.reload();
};
</script>';
}
Whenever I pass reCAPTCHA and page reloads, reCAPTCHA shows again.
I know data from previous page www.example.com/modules/liaise/index.php?form_id=xxx is still there by using
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
Is there any way by which I can resend data from previous url after reCAPTCHA is passed in the same page?
I am newbie in coding. Please be specific.
Thank you so much!
If your talking about re-sending your data as mail you can use something like this:
if (isset($_POST['form-input'])) {
// Send mail
}
and every time you reload the page and the Post data is not null or blank, it will run that code.
If you are wanting the reCAPTCHA to reload as success, I would say that's defeats the security of reCAPTCHA
Also I see that you have a typo esle should be else.

submitLoginForm() does not send the data to the authentication server - MobileFirst Cordova client

I am trying to write a cordova hybrid application test application on MobileFirst platform. In my challenge handler, I have included a code to send a login information to my authentication server using submitLoginForm() java script API.
I check using wireshark if any auth request to my authentication server is getting generated, but it does not.
Can you please help me identify the issue with my code?
I can see the alert until Inside handleChallenge3, but does not see the alert for Closing Challenge Handler.
One more thing, I am trying to use isCustomResponse() API just to see what kind of challenge/response is coming to my challenge handler, but it seems not to be getting triggered. Has this been deprecated in MobileFirst Platform 8?
Thanks
var LtpaAuthChallengeHandler = function(){
LtpaAuthChallengeHandler = WL.Client.createWLChallengeHandler("LtpaBasedSSO");
LtpaAuthChallengeHandler.isCustomResponse = function(transport) {
alert ("Inside isCustomResponse");
return true;
};
LtpaAuthChallengeHandler.loginResponse = function(response) {
alert ("Inside loginResponse");
LtpaAuthChallengeHandler.submitSuccess();
alert ("After loginResponse");
};
// handleFailure
LtpaAuthChallengeHandler.handleFailure = function(error) {
// WL.Logger.debug("Challenge Handler Failure!");
if(error.failure !== null && error.failure !== undefined){
alert(error.failure);
}
else {
alert("Unknown error");
}
};
LtpaAuthChallengeHandler.handleChallenge = function(challenge) {
alert ("Inside handleChallenge");
var msg = "";
alert ("Inside handleChallenge1");
var options = {
"headers" : {},
"parameters" : {
"username" : "admin",
"password" : "admin",
'login-form-type' : 'pwd'
}
};
alert ("Inside handleChallenge2");
var loginUrl = "<URI for forms based auth of auth server>";
alert ("Inside handleChallenge3");
LtpaAuthChallengeHandler.submitLoginForm (loginUrl, options, LtpaAuthChallengeHandler.loginResponse);
alert ("Closing Challenge Handler");
};
};
Once the credentials have been collected from the UI, use WLChallengeHandler's submitChallengeAnswer() to send an answer back to the security check.
isCustomResponse() is not applicable from MFP 8.0.
Refer to the Authentication and Security topic here.

javascript detect if the user liked a page [duplicate]

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.

Facebook Javascript, How to detect if user is a fan of my facebook page? While on my site?

I have the following JS code.
The code's purpose is to first get the users facebook id, and then using FQL check that id against my page ID and make sure the user is a fan.
The problem I am running into is that the only time the code actually works is if i login with my own personal facebook profile. I think its because my profile and the FB.init appid are somehow linked?
Can someone take a look at this code and show me where I am going wrong?
My goal again is to use JS to first get the users id (thus their thumbnail image), and then cross reference that against my own facebook page to check and see if they are a fan. If they are a facebook fan, then I will probably give them a coupon or something.
Thanks in advance.
<script src="http://connect.facebook.net/en_US/all.js"></script>
//Connect to facebook with my app id..
FB.init({
appId:'135445813195028',
cookie:false,
status:true,
xfbml:true
});
//Check to see if user is actually CONNECTED???
FB.getLoginStatus(function(response) {
if (response.session) {
// USER IS CONNECTED
FB.api('/me', function(user) {
if (user != null) {
var image = document.getElementById('imagez');
image.src = 'http://graph.facebook.com/' + user.id + '/picture?type=large';
var name = document.getElementById('name');
name.innerHTML = user.name;
FBID = user.id;
console.log('Facebook ID:' + FBID);
//assemble an FQL query to see if the guy is a fan of our page...
myquery = 'SELECT uid FROM page_fan WHERE page_id = 126923080686340 AND uid = ' + FBID;
console.log('query = ' + myquery);
///Run FQL Query to see if user is a fan
FB.api({
method: 'fql.query',
query: myquery
}, function(resp) {
if (resp.length) {
var IsFan = true;
alert('You are A fan!')
console.log('Visitor is a fan');
//show coupon code...
} else {
alert('Signed into facebook, but Not a fan!');
var IsFan = false;
console.log('Visitor is not a fan');
//show like button...
//once like is clicked then refresh the page...
}
});
//END Run FQL Query to see if user is a fan
}
});
//Figure out if they are a fan...
} else {
// USER IS NOT CONNECTED
alert('NO USER session, user is not logged into facebook!!!');
}
});
The FB.getLoginStatus check to see if the user is connected to your application .. not to facebook.
But when the user is not connected to your application, the .status property can tell you the reason of the fail (if the user is not logged-in at all, or just to your app).
So the structure you should use is
FB.getLoginStatus(function(response) {
if(response.session) {
alert('connected to Application');
} else {
// no user session available, someone you dont know
if(response.status == "notConnected") {
// But user is logged into facebook
alert("Not connected to Application, but is logged in to Facebook");
} else {
// User is not logged into facebook
alert('Not logged in to facebook');
}
}
});
But you cannot access the ID of a user that has not authorized your Application.
Not through Javascript API.

Categories