Is there a JavaScript API for sending notifications to Facebook users? - javascript

I am currently developing a Facebook application on a website that would need to send a notification to the app's users without using a user interface dialog. After reading some blogs I concluded that the option is available in example in PHP API only. I could only find this example:
http://developers.facebook.com/docs/channels/
Is there a JavaScript API to do this?
After some sort of more reading, I found out that FB.api could handle graph object apis and also the rest apis which are to be deprecated, and I got the following working:
FB.api('/1175241653/apprequests', 'post',
{ message: "This is a Good Request!!" },
function (response) {
if (!response || response.error) {
alert('Error occured , Request Failed :(( ');
} else {
alert('Request is sent successfully');
}
});
However, that id number 1175241653 does not work if the logged in user's id is not that id.
Therefore this would required the same functionaliy that Facebook uses to retrieve the ID of whomever signed into the application. Is there any way to do this?

Now , I got this working in all means and I'd like to share it with those who may deal with :))
lets say 1st as to do a single app request from ur application to any of facebook registered users in your application would be like this:
var data =
{
message: "Hey there, something good happened over here !",
access_token: "AAADdf39DLxgBANEwZA9ZCfZCSbtdfcZBtstWMMsW5JiZBjVW2Ucx234sedhHSZCm8aEABzvhWPBNWi1bTKwZBq0EcgZD"
}
FB.api('/68751034/apprequests',
'post',
data,
function (response) {
console.log(response);
if (!response || response.error) {
} else {
}
});
access_token should be provided as to authenticate the request from the application to the registered user.
If you do not know about access tokens, you can read about it over at the facebook site:
http://developers.facebook.com/docs/authentication/
Also, if you want to send batch requests to a set of users in one request call, there's a support page from the facebook site about that too:
http://developers.facebook.com/docs/reference/api/batch/
and here's a sample of what I mean :
var _batch = [];
for (var i = 0; i < _socialids.length; i++) {
_batch.push({
method: 'post',
relative_url: _socialids[i] + '/apprequests/?access_token=' + _accessTokens[i],
body: "message= This is a request sent to many users" });
}
if (_batch.length > 0) {
FB.api('/', 'POST', { batch: _batch }, function (res) {
// Do whatever when the batch request is sent
});
}

Related

About the facebook javascript sdk

I am a newbie in coding. When I called the below function to post on my wall. I always encouunter error occured alert box. I have search the web for few days still cannot find the result and the fix. The facebook documentation is really bad. Please help. I could call fb.ui, or fb.getloginstatus with no problem. But just have problem of calling the fb.api.
function postToWall() {
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
// alert('Error occured');
} else {
// alert('Post ID: ' + response.id);
}
});
FB.api('/me', function(response) {
// console.log(response);
});
}
The error message is-
An active access token must be used to query information about the current user.
The error is quite straight-forward. No user is currently logged-in to your application. You must call, FB.login first before making any API calls further.
After the login, the user will be in session and you wont see this error again.

FB.api('/photos') works outside of Facebook app, but not WITHIN the app

I am POSTING a photo the a users facebook using the JS SDK via FB.api("/photos","post",etc)...
I can successfully do this in a dedicated URL outside of the FB app. but when attempting to post within the app, I get this error:
Error occured:{"message":"An unknown error has occurred.","type":"OAuthException","code":1}
I have a valid access token each time. Can anyone help please?? thank you!
FB.api('/photos', 'post', {
message: 'Use the Sephora Framework app to transform pictures from your life into one extraordinary story. http://seph.me/SmcbkM',
access_token: Sephora.accessToken,
url: imgURL
}, function (response) {
if (!response || response.error) {
alert('Error occured:' + JSON.stringify(response.error));
} else {
FB.api('/'+response.id, function(response){
storeSubmission(response.images[1].source);
});
}
});
You have used the wrong end-point: /photos.
You have to specify the user-id or the current user in session to which profile you want to add the photo.
So the correct call is: /me/photos

Retrieving Temporary Access Token using jQuery OAUTH

I am attempting to make an API OAUTH2 call to Shopify to authenticate. When I go to my application, the first screen comes up. I press Install, and then it redirects me back to where I started. The problem is that when I get redirected, I cannnot seem to catch it in my jQuery ajax function and therefore I am unable to get the temporary token I need to create my permanent token from OAUTH. The 2nd image shows what is happening after I press install. My code so far is posed below. None of the console.log() functions are being called after I run the ajax call.
My application URL for my app is set to
http://localhost
and my application is running from
http://localhost/shippingcalculator.
I tested the calls in an external REST client program, and I managed to successfully get my access token, so it is not a problem with my credentials.
<!DOCTYPE html>
<script type="text/javascript">
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
console.log(window.location.search);
var results = regex.exec(window.location.search);
if (results == null) return "";
else return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getTemporaryToken(token) {
jso_configure({
"shopify": {
client_id: "67d7af798dd0a42e731af51ffa", //This is your API Key for your App
//redirect_uri: "", OPTIONAL - The URL that the merchant will be sent to once authentication is complete. Must be the same host as the Return URL specified in the application settings
authorization: "https://emard-ratke3131.myshopify.com/admin/oauth/authorize",
//In your case the authorization would be https://SHOP_NAME.myshopify.com/admin/oauth/authorize
scope: ["read_products"], //Set the scope to whatever you want to access from the API. Full list here: http://api.shopify.com/authentication.html
}
});
$.oajax({
url: "https://emard-ratke3131.myshopify.com/admin/oauth/authorize",
jso_provider: "shopify",
jso_scopes: ["read_products"],
jso_allowia: true,
success: function(data) {
//Use data and exchange temporary token for permanent one
if (jqXHR.status === 200) {
console.log("200");
}
if (jqXHR.status === 302) {
console.log("300");
}
console.log("Response (shopify):");
console.log(data);
},
error: function(e) {
console.log("Fail GET Request");
console.log(e);
},
complete: function(xmlHttp) {
// xmlHttp is a XMLHttpRquest object
console.log(xmlHttp.status);
}
});
console.log("Code: " + getParameterByName("code"));
}
}
$(document).ready(function() {
getTemporaryToken();
});
</script>
</head>
<body>
Hello World!
</body>
</html>
It's a pretty bad idea to do all of this client side, your API key will be in the clear for anyone to see and use. On top of that where will you store the token? There are also cross site scripting restrictions built into all browsers that will prevent JavaScript from making calls to sites other than the one the js is loaded from.
You should really do the authentication and make all your API calls from a server.

Should I handle CODE using Javascript SDK FB.login POP-UP or is it handled automatically to gain the access_token?

In the authentication flow documentation here it mentions the CODE which is returned upon oAuth authentication.
Is this required for the Javascript SDK or is this handled automatically in the background in this code?
By "is this required?" I mean, do I have to handle this code to verify the authenticity of the request, or does the JavaScript SDK use the code automatically to gain the access_token.
The documentation explains the client side flow, and how to get the access token using the 'code' so until now. I've been assuming that the SDK manages this automatically in the background, because it produces an access code as response.authResponse.accessToken.
FB.login(function(response) {
if (response.authResponse) {
// User is logged in to Facebook and accepted permissions
// Assign the variables required
var access_token = response.authResponse.accessToken;
var fb_uid = response.authResponse.userID;
alert(dump(response.authResponse));
// Construct data string to pass to create temporary session using PHP
var fbDataString = "uid=" + fb_uid + "&access_token=" + access_token;
// Call doLogin.php to log the user in
$.ajax({
type: "POST",
url: "ajax/doLogin.php",
data: fbDataString,
dataType: "json",
success: function(data) {
// Get JSON response
if (data.result == "failure")
{
alert(data.error_message);
window.location.reload();
return false;
}
else if (data.result == "success")
{
window.location.reload();
return true;
}
},
error: function() {
return false;
}
});
} else {
// user is not logged in and did not accept any permissions
return false;
}
}, {scope:'publish_stream,email'});
I would like to know, because I want to ensure that my code is secure.
From the documentation
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint at https://graph.facebook.com/oauth/access_token. The app secret is available from the Developer App and should not be shared with anyone or embedded in any code that you will distribute (you should use the client-side flow for these scenarios).
If you plan on using the FB.api function to make calls to their Graph API, then you need the code to get the access token. But if you only need to authenticate the user, then what you have will do that just fine.

Problem with Facebook Open Graph API call... need an active access token?

I'm using Facebook's open graph api along with the JavaScript SDK on my site. My goal is for a user to connect to my site and then after performing certain actions on my site publish a message to the users facebook stream. I have the facebook connect function working just fine. During the connect I request email, publish_stream, offline_access permissions. I think those are all I need for what I'm trying to do. Now when the user connects via facebook connect I do get and capture the facebook access token and secret though I don't know what to do with them.
According to Facebook's shoddy documentation for the JavaScript SDK... to do what I'm trying to do it says to use the following code:
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
I'm doing just that as a test and instead of alerting the response I'm stringifying the JSON response and writing to the console. Suffice it to say the stream publish fails and the response is this:
{"error":{"type":"OAuthException","message":"An active access token must be used to query information about the current user."}}
If the user is 'connected' to my site via facebook connect and accepted all the permissions I specified, don't I have a valid access token? Is the access token another parameter I have to pass to the api call?
Make sure you have all this in the page:
<BODY>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId : APP_ID, // the app ID you get when you register your app in http://www.facebook.com/developers/
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
if (FB.getSession() != null) {
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
</script>
The above code worked for me with the publish_stream permission. Make sure that the code is not running before the javascript api has received the access token. Run:
console.log(FB.getSession())
directly above the FB.api call to make sure you have an access_token.

Categories