Extend Facebook Access Token javascript - javascript

I've already had a look around and i can't seem to find an answer to this, I'm needing my access token to last longer than the 2 hours that it currently does. unless you are able to suggest another method of getting a json result. Thanks
Heres my code
//first define a function
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'https://graph.facebook.com/v2.3/147733805246675?fields=posts&access_token=CAACEdEose0cBALZA1JuPZCO5MW3WZAX2ERa3RJ7PA5QKawTRGH9Yg0tdv4ENVJeZAqFchh9mNJuHu75gKv6QkHj63ezAZBGUm1OnpHWurJM4Aa0J71hFsCr27ZCSz43IuYs7QoBomtHVJCiex6ZBRZAovNybDf5XhfyaPNt5CHhvAhnoSZAXFO8q8c2na1ndztlp1zY2ftvsc9QVZCboEwdLAQnZA4zejYvM7kZD',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.posts.data.length; i++) {
var section = json.posts.data[i].message;
$("#tableid").append("<tr><td style='width:70px'><img id='theImg' src='img/fb.png'/></td><td><b>" + section +
"</b></td></tr>");
}
},
error: function(error) {
console.log(error);
}
});

The Javascript SDK will handle all token-related logic for you. Why do you want to have a long-lived token in the browser?
You should use the Javascript SDK and the features it provides. The only use-case to generate long-lived tokens yourself is if you want to make API calls from your server.
Since extending and token involves sending over your App Secret, you should not do that in the browser; your app secret should only be on your server.

Related

POST javascript response to Caspio Table

i am trying to Post the player ID from onesignal to a caspio table. I have read dozens of forums etc and cant seem to get it right. Any Ideas? Custom is the Existing parameter for username on this page that i want sent along with the user id.
OneSignal.push(function() {
OneSignal.on('subscriptionChange', function (isSubscribed) {
if (isSubscribed) {
OneSignal.getUserId(function(userId) {
$.post(https://xxxxxxxx.caspio.com/rest/v1/tables/User_ID_Test/rows,( User_ID = 'userId' User_Name = '[#custom]' ), function (data));
});
}
});
Before doing a POST call to Caspio API, you must generate an access token. I will share an AJAX solution which may represent security issues due to you are exposing your secret and client keys, also every call would generate a new token but it could be useful for any non tech user looking for an easy solution.
If you want a more robust solution, I could recommend the following service: Caspio API Library
At this point in time, v2 of Caspio API has been released so I am using this latest version of Caspio Rest API. The steps to run a POST call to Caspio service are these:
Include jQuery in your web page head section or in your caspio datapage header. Do not include it in both as it may cause conflicts and it could increase the loading time of your page. Help to include jQuery in your project
Generate an access token from Caspio API.
Caspio Documentation / $.post() jQuery Documentation
Run the POST call. Full Caspio API documentation
Complete code is shown bellow
<script>
var cbIntegrationId = "<your-integration-id>"; //Required
var clientId = "<your-client-id>"; //Required
var clientSecret = "<your-client-secret>"; //Required
var tableName = "<table-name>"; //Required
//Get access token
$.post(
"https://" + cbIntegrationId + ".caspio.com/oauth/token",
{
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret
},
function(cbAuth){
//Run POST call
$.ajax({
url: "https://" + cbIntegrationId + ".caspio.com/rest/v2/tables/" + tableName + "/records?response=rows",
type: 'POST',
data: '{"<field1>": "<value-to-be-inserted>", "<field2>": "<value-to-be-inserted>"}', //Define record values
headers: {
"Authorization": "Bearer " + cbAuth.access_token, //Extracts the access token from the initial authorization call
"Content-Type": "application/json", //Required, otherwise 415 error is returned
"Accept": "application/json"
},
dataType: 'json',
success: function (data) {
console.log(data.Result); //Check the console to view the new added row
},
error: function(data) {
console.log(data.responseJSON); //Check the console to view error message if any
}
});
}
);
</script>
I strongly recommend taking a look at this article. Please read about Permissions for your API profile(s)

How to get all the repositories for a particular user?

I am trying the extract the various repository names for a particular user and populate a combobox on a html page. I am able to extract only one repository name. How can I get all the names? The code I have so far:
$.ajax({
url:"https://api.bitbucket.org/2.0/repositories/abc",
username: "palld#bdbd.in",
password: "abcdef123456",
success: function(data){
console.log(data);
},
error: function(){
console.log("Connection did not go through");
},
type: 'GET'
});
Writing similar code in Java and python worked and I was able to see all the repository names. Any help would be appreciated.
The result is as below:
Edit:
It appears that Bitbucket will send you some data even when you are not authenticated to their API. I suspect that there is no authentication request sent to you by the API and jQuery simply does not send the username and password when not asked for.
This code explicitly send the authentication data to the API:
var reposUsername = "OWNER_OF_REPOS";
var authUsername = "YOUR_USERNAME";
var authPassword = "YOUR_PASSWORD";
$.ajax({
url:"https://api.bitbucket.org/2.0/repositories/" + reposUsername,
success: function(data){
console.log(data);
},
error: function(){
console.log("Connection did not go through");
},
type: 'GET',
headers: {
'Authorization': "Basic " + btoa(authUsername + ":" + authPassword)
}
});
(I'm 100% sure that this code works as I've tested it a few minutes ago with my own Bitbucket account).
Note: please be aware that storing your credentials in the code is something you should not do, so think twice before you release your code/application the the public.
Obsolete answer:
Just look at the documentation Bitbucket provides to you (although, the example response looks kind of weird).
Assuming your data object is already a JSON parsed object, you should be able to access your respositiories like this (Edit: code adjusted the the provided screenshot):
data.values
Parse the JSON response. If it works from Python or Java then it must be something to do with the way you are handling the response in JavaScript. Perhaps you are not parsing it, which you need to do to convert it into a proper JSON object containing all the elements you want.
success: function(data){
console.log(JSON.parse(data));
},

JSONP - "Uncaught SyntaxError: Unexpected token"

before I explain my issue I would like to mention that I'm a naive on jsonp. This is actually my very first attempt to work with JSONP.
Im using jquery ajax call to pullback data from a website.
my jquery code is below
$.fn.checkTPS = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function() {
var api_key = 'asdfasfsadfsadfsad';
var format = 'json';
var username = 'dame#example.co.uk';
var self = $(this);
var selfValue;
var feedback = $('.tps-feedback');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()) {
selfValue = self.val();
if (selfValue.length > 9){
$.ajax({
url: 'https://www.selectabase.co.uk/api/v1/tps/' + selfValue + '/',
type: 'get',
dataType: 'jsonp',
data: {
format: format,
username: username,
api_key: api_key
},
success: function(data) {
console.log(data);
},
error: function() {
},
jsonp: 'jsonp'
});
}
}
},3000);
}
});
});
};
I want to accommodate a service from selectabase.co.uk, according to them this is how I should use the service https://www.selectabase.co.uk/api/v1/tps/[number]/?format=json&username=[username]&api_key=[api key]
when I send request using ajax I get this error Uncaught SyntaxError: Unexpected token : and when clicked this opens up
{"ctps": false, "number": "1452500705", "resource_uri": "/api/v1/tps/01452500705/", "tps": false} by the way this I want but don't know what's this error is unexpected token :
I've copied the following link from inspect element tab (you can see the image below) I think this is the call that has been generated by json https://www.selectabase.co.uk/api/v1/tps/01452500705/?jsonp=jQuery17102731868715648129_14120077325500&format=json&username=dame40example.co.uk&api_key=asdfasfsadfsadfsad&_=14120077325500
I copied the link below from inspect element > source tab in chrome.. I think I should add an image to describe properly where this json data and link I've copied from.
I hope I've manage to convey my message across... please help if you have any Idea what do i need to add... Regards
The format=json in your query string should probably be format=jsonp. The server is replying with JSON, but you're expecting a JSONP response. But I don't know that they support format=jsonp, it's just a guess.
Alternately, if that server supports CORS and allows requests from your origin, you could handle JSON instead (just remove dataType: "json" from your ajax call). Beware that that would require that the user be using a browser that properly supports CORS, which IE8 and IE9 don't. (They support CORS, but not via the normal XMLHttpRequest object, and this is a browser inconsistency that jQuery doesn't smooth over for you. If you search, though, you can find "plugins" or similar that will handle it.)

Salesforce OAuth with REST API using Javascript

I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.

How do I extract a foursquare access_token saved to DOM as a link so I can use it for API calls?

Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried:
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token : checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Browsers natively implement a global function JSON.parse(), and if for some reason that doesn't work you can use jQuery's parseJSON() function.
Here's how it works. Let's say your JSON object has the following format:
{
Status: "Success",
Resource: {
Name: "Person's Name",
URL: "http://blahblahblah.com/extrastuffhere?querystuff=here"}}
Then you can access the "URL" element by using JSON.parse() like so:
var url = JSON.parse(json).Resource.URL;
(I'm unfamiliar with Foursquare but it should look similar, and you can do console.log(json) to see its structure.)
So your code might look something like this:
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
var parsed = JSON.parse(json);
console.log(parsed);
access_token = parsed.access_token;
});
});
Hope that helps!

Categories