I am attempting to use the POST statuses/update Twitter API call. I'm new to this so please bear with me :). As outlined in this doc I've been trying to set up headers to use application only authentication.
What I have tried so far is as follows:
$(".tweet-later").on("click", function(event){
$.ajax({
url: "https://api.twitter.com/1.1/statuses/update.json",
data: { status: "Testing"},
type: "POST",
dataType: 'json',
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Rm5DVHpIc2M2ejRpeDRQRDRdfdsjprbjB5TENzeEZQNnhza2NFMzB6dnJMbnI2aENlRUZSczdOZUtWZUhaREhXSFVCY3dQWA==');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
},
success: function(data) { alert('Tweeted!'); },
error:function(exception){alert('Exeption:'+exception);}
});
});
I keep receiving an error: "Authentication Failed".All help is very much appreciated.
Thank you very much in advance.
What you're trying to do is impossible.
As it says in the documentation:
When issuing requests using application-only auth, there is no concept of a “current user.” Therefore, endpoints such as POST statuses / update will not function with application-only auth. See using OAuth for more information for issuing requests on behalf of a user.
Related
I am trying to access a NetSuite restlet using jQuery. Here is my code for that:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
dataType: "json",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
When I check the "Network" tab in Chrome/FF it's giving me the following 401 response:
XMLHttpRequest cannot load https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.tracksandtires.com' is therefore not allowed access. The response had HTTP status code 401.
Am I not formatting the Authorization part correctly? I can't find any documentation on accessing a NetSuite Restlet via jQuery so I'm sort of shooting blind here. Should I just use vanilla javascript and not jQuery? Any help would be much appreciated!
Try using jsonp like this:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
crossDomain: true,
dataType: "jsonp",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
More info:
How does Access-Control-Allow-Origin header work?
Basically don't
Although #adolfo-garza 's answer does show JSONP correctly you gain nothing by using a Restlet and you give up a login that can never be used for something sensitive. Basically you've put one of your Netsuite credentials out on the public internet. Nothing good can come of this.
This is one of the use cases for Suitelets. You create a Suitelet that has public access (available without login; audience all roles) and then you don't need authentication (though there are ways to rely on shopping session or checkout session authentication if you need filtering information by customer).
If you are just trying to test a real Restlet Use Case then you should use Node or some non-browser based application to do that.
I'm pretty new on using APIs and I am having a problem with Instagram's new api.
For a dislike function, the documentation states to use a delete method, but I keep getting an error: XMLHttpRequest cannot load URL. Response for preflight has invalid HTTP status code 405.
Funny thing is that when I try the exact same thing with curl, it works.
For example, this is a working method: curl -X DELETE https://api.instagram.com/v1/media/{media-id}/likes?access_token=ACCESS_TOKEN
But if I try to use it with javascript
if( user_has_liked ){
$.ajax({
crossDomain: true,
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'DELETE',
success: function(data){
response = data.data;
document.getElementById(photoId).className = "fa fa-heart-o";
document.getElementById(photoId).onClick = function(){
subscribe(photoId, false);
}
}
});
}
All I get is a 405 error.
I've tried enabling CORS but it seem to work either
I would be really grateful if anybody could give me a hand on this.
Many thanks!
I solved this issue sending a request utilizing the POST method and "delete" like a parameter. Then it is looking like this:
$.ajax({
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'POST',
data: {_method: 'delete'},
success: function(data){
console.log(data);
}
});
Font: http://laravel.io/forum/02-20-2014-sending-a-delete-request-via-ajax
I'm using a jquery ajax call to a recurly API endpoint, but I get cross-origin errors. From my understanding, this is because Recurly only returns results as XML... when I use JSONP to get around cross-origin errors, I get an error because it receives the XML data but expects JSONP. Pretty obvious. But I'm trying to understand how exactly can one use this API at all via AJAX calls. I've been successfully able to access the API with PHP, but unfortunately, for this project, I can't use any client-side code.
Even if I find some sort of middle-code solution to get the XML and convert it to JSON for my side to accept, I need to utilize the API for POST requests (creating accounts, subscriptions, etc.) so I would like to understand how to utilize the API properly.
Here is an example of my code:
$.ajax({
url: "http://[DOMAIN].recurly.com/v2/accounts",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + window.btoa("[API KEY]"));
},
crossDomain: true,
type: "GET",
accepts: "application/xml",
dataType: "application/xml; charset=utf-8",
success: function (data) {
console.log("SUCCESS:", data);
},
error: function(e){
console.log("ERROR:", e);
}});
Anyone with Recurly API experience have any tips/advice?
From https://docs.recurly.com/api/recurlyjs/jsonp_endpoints
$.ajax({
dataType: 'jsonp',
url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}',
data: {
currency: 'USD',
},
success: function (data) {
// do stuff
},
}
You should not use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems.
Look at the JSONP endpoints that Byaxy linked to.
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.
I have checked many post and tried every logic that were mentioned in various blogs and posts. But I am unable to perform a cross domain ajax call to an IIS server. Please anybody advice what else I should look into or configure it to get working. All your help is greatly appreciated.
Here is my ajax call:
var url = "http://mydomain .com/myauthorizeservice";
var jsonParam = JSON.stringify({ username: 'user007', password: 'pass007' });
$.ajax({
type: "POST",
url: url,
crossDomain: true,
data: jsonParam,
success: fnSuccess,
error: fnError,
dataType: "json",
contentType: "application/json"
});
function fnSuccess() {
alert("Success");
}
function fnError() {
alert("Error");
}
My config in the root web.config:-
Error:-
Access Denied.
I really struggled a lot to make this thing work. Here some points that also matters and restrict the cross domain calls-
Note: I am using WCF REST service. and configurations are for IIS 7.5.
1: Make sure your OPTIONSVerbHandler looks like-
2: Make sure you have the correct ordering in HandlerMappings-
Rest settings and the way to perform ajax call is mentioned in the question.
Happy coding!