Fan-Gate, Like-Gate, show-to-connections, with javascript and like box? - javascript

I have a facebook likebox on my site (not an iframe app) where I need to create gated content. I understand the FB.Event.subscribe using edge.create and edge.remove but what I really need is to know if a user already likes the page not simply if they became a fan or stopped being a fan. Is there anything I can see as a callback maybe from the xfbml.render?
I am limited (by my company) to using front end languages, meaning javascript is really my only option at this point. I would gladly use the "signed_request" option but best I can tell that seems to be only accessible via server side languages.
Is there any way for me to determine whether someone already "Likes" a page using only javascript?

Yes, you can do this completely in javascript using the FB Javascript sdk.
function RunLikeCheck() {
var likeId = 'yourLikeIdHere';
FB.api({
method: 'fql.query',
query: 'SELECT uid FROM page_fan WHERE page_id = ' + likeId + ' AND uid = me()'
},
function (response) {
if (response.length == 1) {
$("#HasLiked").val('true');
$('#frmAllow').submit();
}
else {
$("#HasLiked").val('false');
$('#frmAllow').submit();
}
}
);
}
Now this is assuming that you already have the user logged in and have the correct permissions.

Here is some additional sample javascript code for implementing a like gate that does not require the FB.api call (but does require the user to re-like every time they visit the page).
http://linksy.me/viral-gate

Related

Automatically assign a customer to a specific customer group on sign-up - Bigcommerce

I've been told by BC support that this isn't possible, but I would be surprised if there really wasn't a way.
I need to be able to automatically assign a customer to a specific customer group when they create an account. My thought:
I would add an extra field to the sign-up form
Provide a user with a code (a string or number)
User enters code when creating new account
User hits submit
On form submit I would grab the value of the extra field:
var codeInput = document.getElementById('code-input').value;
I would then compare that value to a pre-defined string, and if there is a match, I would assign that customer to groupX (with a group id of 8):
if ( codeInput === "codeIGaveToTheUser" ) {
currentUserGroupID = 8;
}
Is it possible to assign a customer to a specific group on sign-up like this (or any other way)?
Any help is much appreciated.
Although using BigCommerce webhooks would ensure the highest success rate of executing your customer group assignment app, it requires quite a bit of setup on BigCommerce (creating a draft app, getting an oAuth key, jumping jacks, etc), and may be a bit of overkill for your requirements.
Here's an easier way, in my {mostly} humble opinion, that takes advantage of much of what you included in your original question. Any solution though will nonetheless require an external server to handle the customer group assignment through the BigCommerce API.
Within the BigCommerce control panel, add in the extra field to the user sign up form like you mentioned.
So as you can see, this new input field has been added natively to the default registration page:
So now, when a user creates an account on your site, the value for the Signup Code (the custom field created) will be directly accessible through the API for that customer's account. Take a look at what that JSON data looks like:
Okay, so this is nice and all, but how do we automate it?
To do so, we will have to let our external application know that a customer just registered. Furthermore, our external application will need some sort of reference to this newly created customer, so that it knows which customer to update the customer group for. Normally a BigCommerce webhook would notify us of all this, but since we aren't using a BigCommerce webhook, here's the alternative method to triggering the external script.
We will trigger our external application via the BigCommerce Registration Confirmation page - createaccount_thanks.html. This page is loaded immediately after a customer creates an account, so it is the perfect place to insert our trigger script.
Additionally, now that the customer is logged in, we can access the customer's email address via a BigCommerce Global system variable -%%GLOBAL_CurrentCustomerEmail%%.
We should make an HTTP request from this page to our external application along with the customer's email address. Specifically, we can make an XMLHttpRequest via JavaScript, or to be modern, we'll use Ajax via jQuery. This script should be inserted before the closing </body> tag on createaccount_thanks.html.
Example of POST request (although a GET would suffice as well):
<script>
$(function() {
$('.TitleHeading').text('One moment, we are finalizing your account. Please wait.').next().hide(); // Let the customer know they should wait a second before leaving this page.
//** Configure and Execute the HTTP POST Request! **//
$.ajax({
url: 'the_url_to_your_script.com/script.php',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({email:"%%GLOBAL_CurrentCustomerEmail%%"}),
success: function() {
// If the customer group assignment goes well, display page and proceed normally. This callback is only called if your script returns a 200 status code.
$('.TitleHeading').text('%%LNG_CreateAccountThanks%%').next().show();
},
error: function() {
// If the customer group assignment failed, you might want to tell your customer to contact you. This callback is called if your script returns any status except 200.
$('.TitleHeading').text('There was a problem creating your account').after('Please contact us at +1-123-456-7890 so that we can look into the matter. Please feel free to continue shopping in the meantime.');
}
});
});
</script>
Now finally, you just need to create your serverside application responsible for handling the request above, and updating the customer's customer group. You can use any language that you desire, and BigCommerce even offers several SDK's you can use to save mega development time. Just remember that you need to host it somewhere online, and then insert its URL to the JS script above.
PHP Example (quick & dirty):
git clone https://github.com/bigcommerce/bigcommerce-api-php.git
curl -sS https://getcomposer.org/installer | php && php composer.phar install
<?php
/**
* StackOverflow/BigCommerce :: Set Customer Group Example
* http://stackoverflow.com/questions/37201106/
*
* Automatically assigning a customer group.
*/
//--------------MAIN------------------------//
// Load Dependencies:
require ('bigcommerce-api-php/vendor/autoload.php');
use Bigcommerce\Api\Client as bc;
// Define BigCommerce API Credentials:
define('BC_PATH', 'https://store-abc123.mybigcommerce.com');
define('BC_USER', 'user');
define('BC_PASS', 'token');
// Load & Parse the Email From the Request Body;
$email = json_decode(file_get_contents('php://input'))->email;
// Execute Script if API Connection Good & Email Set:
if ($email && setConnection()) {
$customer = bc::getCollection('/customers?email=' .$email)[0]; //Load customer by email
$cgid = determineCustomerGroup($customer->form_fields[0]->value); //Determine the relevant customer group ID, via your own set string comparisons.
bc::updateCustomer($customer->id, array('customer_group_id' => $cgid)) ? http_send_status(200) : http_send_status(500); //Update the customer group.
} else {
http_send_status(500);
exit;
}
//-------------------------------------------------//
/**
* Sets & tests the API connection.
* #return bool true if the connection successful.
*/
function setConnection() {
try {
bc::configure(array(
'store_url' => BC_PATH,
'username' => BC_USER,
'api_key' => BC_PASS
));
} catch (Exception $e) {
return false;
}
return bc::getResource('/time') ? true : false; //Test Connection
}
/**
* Hard define the customer group & signup code associations here.
* #param string The code user used at signup.
* #return int The associated customergroup ID.
*/
function determineCustomerGroup($signupCode) {
switch ($signupCode) {
case 'test123':
return 1;
case 'codeIGaveToTheUser':
return 8;
default:
return 0;
}
}
So then you would do your customer group string comparisons directly in the serverside program. I'd recommend you rewrite your own BC API script as the one above in quality is really something along the lines of functional pseudo-code, but more so present to show the general idea. HTH
You would need to set up a server to listen for webhooks unless you wanted to do a cron job. We have some basic information on the developer portal, but I included more resources below. From there, you'd need to choose your server language of choice to listen for the webhooks once they been created, respond correctly (200 response if received), execute code based on this information, and then take action against the BC API.
So if you were looking for a code, you'd need to listen for the store/customer/created webhook, and have your code look for a custom field that contained the code. If it was present, then take action. Else, do nothing.
https://developer.github.com/webhooks/configuring/
http://coconut.co/how-to-create-webhooks
How do I receive Github Webhooks in Python

How to get Facebook user's friends' profile picture using Javascript SDK V2.0

I am creating a website using Facebook API V2.0 JavaScript SDK and I would like to display the profile pictures of the user's friends.
I have managed to display my profile picture using the graph API but I can't manage to get the ID of all my friends if I am logged in my app (I am an admin). If I have the ID, I'll be able to show their profile picture.
In the graph explorer, I have checked all permissions (User Data Permissions + Extended Permissions). I have noticed if I switch to API V1.0, I get friends permission which is exactly what I'd like.
Also, I have added a couple of permission to my app in Facebook developers > App details > App Center Listed Platforms > Configure app center permissions. (user_friends + friends_birthday + friends_religion_politics + friends_relationships + friends_relationship_details + friends_location + friends_photos + friends_about_me)
So far, my html looks like this :
<fb:login-button scope="public_profile,email,user_friends,read_friendlists" onlogin="checkLoginState();">
After loading the Facebook SDK, I have :
function getUserFriends() {
FB.api('me/friends?fields=first_name,gender,location,last_name', function (response) {
console.log('Got friends: ', response);
$("#friendslist").html('<img src="https://graph.facebook.com/'+ response.id+'/picture?type=large"/>');
});
}
However, the array which is suppose to contain all my friends info is empty (see image : http://www.screencast.com/t/W02GaOm3h)
If all you need is their image, this can be found in the "taggable_friends" scope. However, do note that this field is very limited (by design) and that you require additional review by Facebook in order to present it to the average user.
It contains:
A taggable id. This is an id with the express purpose of tagging; it cannot be used to identify the user or otherwise gather information from their profile.
A name. The user's first and last name.
A picture, with common related fields. Url, is_silhouette, height and width.
function getUserFriends() {
FB.api('me/taggable_friends', function (response) {
console.log('Got friends: ', response.data);
$("#friendslist").html('<img src="'+response.data[0].picture.data.url+'"/>');
// maybe an $.each as well
// var friendMarkup = '';
// $.each(response.data, function(e, v) {
// friendMarkup += '<img src="' + v.picture.data.url +'" alt="'+ v.name +' picture"/>';
// }
// $("#friendlist").html(friendMarkup);
});
}
Related reading:
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends
https://developers.facebook.com/docs/opengraph/using-actions/v2.0 - Tagging friends and Mentioning friends sections
A disclaimer: I've been battling with this issue for several days without really being able to mention-tag. My submission to use taggable_friends as a comprehensive, navigatable list for the user was rejected and I speculate (speculation ho!) it was because I did no actual tagging. I'll get back to this in a few days when I've clarified and re-submitted my request for a review on Facebook.
-- Edit --
It would seem the reason my initial submission was rejected was because I was using a special development url and did not point out clearly enough why it was not enough to use the url set under settings. This time I clearly pointed out and explained this reasoning in both the general description of my submission and in the step-by-step notes. In summary, be exceptionally clear in your submission about everything; your reasoning as to why you need this permission, how they can access it, etc. Just to make sure it isn't missed if skim-read.
It seems like in V2.0, Friends permission have dissapeared :
Facebook graph api explorer doesn't show 'Friends Data Permission' tab
https://developers.facebook.com/docs/facebook-login/permissions/v2.0

Can I relabel the person.noun for Profile object type in Facebook Open Graph?

I have created a Story using Open Graph and the object I want to use is called Service, which is really just a Profile but I want the text in the post to say 'service' rather than 'person' (which it does now). I have tried creating a custom object but it seems overly complicated for what I need so I have 2 questions:
Can I create a custom type that simply inherits from Profile that can be created in the same way (using the FB.api javascript method)? I don't want to have to use self-hosted types..
Can I simply re-label person.noun from 'person' to 'service' somehow? I can't see a way to do that..
My code to post the story is:
FB.login(function (response) {
if (response.authResponse) {
var strmessage = 'Some message';
var profileid = 'xxxxxxxxx;
var opts = {
profile: profileid,
message: strmessage,
no_feed_story: false,
'fb:explicitly_shared': true
};
FB.api('https://graph.facebook.com/me/mynamespace:myaction', 'post', opts, function (response) {
if (!response || response.error) {
Result("Your message has not been posted");
}
else {
//Message has been posted
Result("Your message has been posted");
}
});
You're going to have to do the custom object if you want a custom name. And, you're going to have to do it on the FB Developer site and go through the whole approval process and all that. And no, there is no way to do any sort of inherence on this.
FB's Open Graph is pretty simple if you use the built in actions and objects, but as soon as you go down the road of wanting custom names for stuff, you are going to have to go all in with it.
I finally put the time aside to implement a custom action and type. It wasn't the most intuitive process but I got there in the end and my app is now approved and doing exactly what I wanted it to do. I'm actually glad I put myself through this learning process as custom stories have great potential and I'm sure I'll find other applications for them in the future.

Removing someone from a user hash on navigating away from a page / page close

I'm building a Node.js / Socket.io project.
I have a hash of Users based on their websocket id. When a user makes the following request i'd like to add them to a group of users viewing that page.
app.get('/board/:id', function(req, res){}
I'd like to keep something like
Browsing = {
username : id,
username : id,
...
}
However i'm unsure how to remove a user lets say if they navigate off the page. Is there some kind of function that gets called upon page leave?
Partial Solution:The following seems to do the trick on Chrome:
$(window).unload(function(){
var username = $('#username').text();
var pid = currentProject;
var data = {
username: username,
id : pid
}
socket.emit('leaving-page', data);
})
... Is there some kind of function that gets called upon page
leave? ...
Yes, but it is not reliable.
The way the people keep track of who is online and who isn't, is usually like this:
Add the time when the user last refreshed/visited a page
set a limit to you consider them offline
You could intercept the event which corresponds to leaving a page. There are several ways to do it, have a look at the following links and let me know if any suits your needs and if I can answer any more explicit questions about them:
Intercept page exit event
Best way to detect when a user leaves a web page?
jquery unload
with the last link you could do something like this:
$(window).unload(function() {
//remove the user from your json object with delete json_object[key];
});
Hope this helps.
Since you're using Socket.io, the server will know when the user has left the page because the socket will be disconnected. Simply listen for the disconnect event.
io.sockets.on('connection', function (socket) {
...
socket.on('disconnect', function () {
// The user on `socket` has closed the page
});
});
Better yet, take advantage of namespaces and let Socket.io handle all of the connection/disconnection (it's doing it anyway -- no need to duplicate effort).
On the client,
socket = io.connect('http://example.com/pagename');
pagename need not point to a valid URL on your domain – it's just the namespace you'll use in the server code:
io.sockets.clients('pagename')
Gets you all of the clients currently connected to the pagename namespace.

JavaScript OAuth sign in with Twitter

I have to integrate Sign-in-with Twitter in my app as below.
https://dev.twitter.com/docs/auth/sign-twitter
It is browser based app developed in JavaScript
I have been refering google code java script OAuth, but im confused how to use oauth/authenticate and how to get the oauth_token
Can any one please help me out with some samples ?
Problem with this is that anyone who views your page can also now view your consumer key and secret which must be kept private.
Now, someone could write an app that uses your app credentials and do naughty and bad things to the point that twitter and users ban you, and there isnt anything you can do.
Twitter do state that every possible effort must be made to keep these values private to avoid this happening
Unfortunately, there is currently no way to use oAuth in Browser based JavaScript securely.
Check out the Twitter #Anywhere JSDK authComplete and signOut events and callbacks at https://dev.twitter.com/docs/anywhere/welcome#login-signup
twttr.anywhere(function (T) {
T.bind("authComplete", function (e, user) {
// triggered when auth completed successfully
});
T.bind("signOut", function (e) {
// triggered when user logs out
});
});
Use below code in consumer.js and select example provider in index.html drop down list
consumer.example =
{ consumerKey : "your_app_key"
, consumerSecret: "your_app_secret"
, serviceProvider:
{ signatureMethod : "HMAC-SHA1"
, requestTokenURL : "https://twitter.com/oauth/request_token"
, userAuthorizationURL: "https://twitter.com/oauth/authorize"
, accessTokenURL : "https://twitter.com/oauth/access_token"
, echoURL : "http://localhost/oauth-provider/echo"
}
};
Since I was searching for the same thing, trying not to use a custom PHP solution, I came across this very simple integration at http://www.fullondesign.co.uk/coding/2516-how-use-twitter-oauth-1-1-javascriptjquery.htm which uses a PHP proxy that accepts whatever twitter api call you'd like to retrieve from your javascript ..
I'm definitely taking a look at it

Categories