Authenticating bigcommerce using zapier and javascript - javascript

I am trying to authenticate using javascript through Zapier but I am unable to authenticate. I am using the following code:
var auth = 'Basic **************';
var url = 'https://www.*****.com/api/v2/customers?email=mel****.com';
$.ajax({
url : url,
method : 'GET',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
crossDomain: true,
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
},
success: function(result) {
alert('done');
console.log(result);
},
error: function (request, textStatus, errorThrown) {
console.log(request.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
However I keep receiving a 401 unauthenticated user error. I have tried running it from an https site but can't get it to work. Any pointers would be greatly appreciated.

You need to base64 encode your username:password credentials.
var auth = 'Basic ' +window.btoa('username:password');

Related

Calling Mirth 'client api' services from jquery

I have a .Net website, hosted on an intranet web server. On the .Net site I have a basic jquery ajax call to our mirth machine. I'm trying to hit the client apis that are provided with the base install of mirth.
We are running mirth 3.9.1, with a default mirth.properties page, so the CORS settings should be correct.
I've tried a variety of settings in mirth.properties (and restarted mcservice between changes) and a variety of $.ajax settings, but cannot seem to find the right mix.
According to this answer: (https://stackoverflow.com/a/47096927/505829), I should be able to use basic authentication, but even if I have to make two calls, I'm ok with that, I just need something that works. Though one call would be preferred.
Here is the ajax call
$.ajax
({
type: "GET",
url: "https://ngmaintst01:8443/api/channels",
dataType: 'json',
// username: username,
// password: password,
// crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
},
xhrFields: {
withCredentials: true
},
// headers: {
// "Authorization": "Basic " + btoa(username + ":" + password)
// },
success: function () {
alert('success');
}
});
Here is the mirth properties:
# CORS headers
server.api.accesscontrolalloworigin = *
server.api.accesscontrolallowcredentials = false
server.api.accesscontrolallowmethods = GET, POST, DELETE, PUT
server.api.accesscontrolallowheaders = Content-Type
server.api.accesscontrolexposeheaders =
server.api.accesscontrolmaxage =
If I take the one call aproach, illistrated above, in chromes dev console I get:
(failed)net::ERR_FAILED
If I take a two call approach (below), the first call is successful (code 200), and the second gets the same error as the single call approach '(failed)net::ERR_FAILED', This time it appears the second call does NOT go out with the cookie session data, which is why a single call approach may be ideal.
$.ajax({
type: 'POST',
url: 'https://' + APPLIANCE+':8443/api/users/_login',
contentType: 'application/x-www-form-urlencoded',
dataType: 'xml',
data: { username: username, password: password },
success: function (data, textStatus, jqXHR) {
//alert(textStatus);
$.ajax({
type: 'GET',
url: 'https://' + APPLIANCE + ':8443/api/channels/' + channelid + '/statistics',
dataType: 'xml',
crossDomain: true,
xhrFields: { withCredentials: true },
//data: data,
//success: function(data, textStatus, jqXHR){ alert(textStatus); },
//error: function(jqXHR, textStatus, errorThrown){ alert(textStatus);}
});
},
error: function (jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
I was able to get this working with some help from the mirth folks on slack. There is a "problem" in that, as far as I know, it will only support one web server. So I either need to have both my test and prod site on this one server, or no test.
Alternatively, I will just use a proxy back end service to circumvent cors altogether. So my local js will call my local proxy server, and forward the request on to mirths api.
Still, for posterity, here is how to get cors to work.
(One possible feature for mirth to implement would be dynamic accesscontrolalloworigin, where you provide an 'access list' of domains, and so long as the request is coming from one of those domains, it spits out, dynamically, that servers name. This would enable me to have multiple servers calling these apis. ala Access-Control-Allow-Origin Multiple Origin Domains?)
# CORS headers
server.api.accesscontrolalloworigin = https://MyDomainServer
server.api.accesscontrolallowcredentials = true
server.api.accesscontrolallowmethods = GET,HEAD,OPTIONS,POST,PUT
server.api.accesscontrolallowheaders = Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization
server.api.accesscontrolexposeheaders =
server.api.accesscontrolmaxage =
$.ajax
({
type: "GET",
url: "https://MirthAppliance:8443/api/channels",
dataType: 'json',
xhrFields: {
withCredentials: true
},
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
success: function () {
//alert('success');
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
// alert('Error - ' + errorMessage);
}
});

error 500 in ajax call when call to the server, but in localhost works

I have a js when i do a ajax call to one server. When i call to this service using localhost, works. But when i call to this service using the server where i upload it, its ERROR 500. The call return a json.
$.ajax({
url: "https://www.example.com/example",
dataType: "json",
data: {
'data': xml,
'message': message,
'customer_id': customer_id,
'subscr_id': subscr_id
},
type: 'POST',
success: function (devol) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("no ha entrado");
}
});
Try to update your code below:
var model = {
'data': xml,
'message': message,
'customer_id': customer_id,
'subscr_id': subscr_id
};
$.ajax({
url: "https://www.example.com/example",
type: 'POST',
dataType: 'json',
data: JSON.stringify(model),
//headers: { 'authorization': `Bearer ${token}` },
async: false,
processData: false,
contentType: "application/json",
error: function (err) {
},
success: function (data) {
}
});
It might be because of CORS (Cross-Origin Resource Sharing)... Usually, you cannot make calls to other domains from the browser unless the other domain you are making calls allows CORS to all sites or specific sites.
enter link description here

Getting undefined in callback function in cross domain ajax post

I'm trying to make ajax post request to my flask app and get the answer in the callback function. Unfortunately I got undefined value instead of a json.
Will appreciate any help!
My server-side code:
application = Flask(__name__)
CORS(application)
...
#application.route('/get_forecast', methods=['POST', 'GET'])
def get_forecast():
if request.method == 'POST':
print('in post')
predictions = {}
predictions['data'] = calc_forecast(request.get_json()["data"])
print(predictions)
return jsonify(predictions)
my client-side code:
$.ajax({
type: "POST",
url: "http://localhost:5000/get_forecast",
data: JSON.stringify(markers),
dataType: 'json',
crossDomain: true,
contentType: "application/json",
done: function(resp, status){
console.log('done')
console.log(resp)
console.log(status)
console.log('=====')
}(),
fail: function(xhr, ajaxOptions, thrownError){
console.log('fail');
console.log(thrownError)
}()
});
Here's what I got in the flask terminal:
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [02/Dec/2018 12:59:53] "OPTIONS /get_forecast HTTP/1.1" 200 -
in post
{'data': [10.15451836569513, 56.578480707072714, 12.435548873275337]}
127.0.0.1 - - [02/Dec/2018 12:59:53] "POST /get_forecast HTTP/1.1" 200 -
Here's what I got in the chrome console:
demo.html:228 done
demo.html:229 undefined
demo.html:230 undefined
demo.html:231 =====
demo.html:234 fail
demo.html:235 undefined
If you look at the examples over at http://api.jquery.com/jQuery.ajax/ they look quite a bit different from your call to $.ajax. I adjusted your code to better resemble the examples. Maybe this helps?
$.ajax({
type: "POST",
url: "http://localhost:5000/get_forecast",
data: JSON.stringify(markers),
dataType: 'json',
crossDomain: true,
contentType: "application/json"
})
.done(function (data, textStatus, jqXHR) {
console.log('done');
console.log(data);
console.log(textStatus);
console.log('=====');
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log('fail');
console.log(textStatus);
});
I think, you were looking for success and error settings.
Update: Yes, I'm pretty sure, your settings done and fail are wrong. You want to use success and error.
Also, have a look at https://stackoverflow.com/a/10931891/1621041
This means, your code could also look like this, if you want to put everything into the settings of the $.ajax call:
$.ajax({
type: "POST",
url: "http://localhost:5000/get_forecast",
data: JSON.stringify(markers),
dataType: 'json',
crossDomain: true,
contentType: "application/json",
success: function (data, textStatus, jqXHR) {
console.log('done');
console.log(data);
console.log(textStatus);
console.log('=====');
},
error: function (jqXHR, textStatus, errorThrown ) {
console.log('fail');
console.log(errorThrown);
}
});

AJAX GMAIL API Call Authorization error

I'm new to the GMail API and am trying to make an AJAX call to retrieve mails.
My code is:
$.ajax({
beforeSend: function (request)
{
request.setRequestHeader("authorization", "Bearer xxxxxxxxxxxxxxxxx.apps.googleusercontent.com");
},
url: 'https://www.googleapis.com/gmail/v1/users/me/messages?key=xxxxxxxxxxxxxxxxxx',
dataType: 'json',
cache: false,
success: function(data) {
// this.setState({Emails: data});
console.log("Mail thread"+data);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
The response is a 401 error. On examining the request, I find the following query parameter appended to the request URL getting sent:
&_=1470236511985
So the request URL appears like this.
https://www.googleapis.com/gmail/v1/users/me/messages?key=xxxxxxxxxxxxxxxxxx&_=1470236511985
Is the appended query parameter causing the 401 error or am I using the authorization header incorrectly? How can I resolve this.
Thanks in advance.
For testing purposes, you can go to the OAuth 2.0 Playground and get an access token with the Gmail API scopes. Just use this access token in a query parameter named access_token:
var accessToken = 'ya29...';
$.ajax({
url: 'https://www.googleapis.com/gmail/v1/users/me/messages?access_token=' + accessToken,
dataType: 'json',
success: function(data) {
console.log(data.messages);
}
}

Convert a cURL API call to Ajax

curl --basic --user {username}:{password} https://www.blueworkslive.com/api/Auth
I have tried to write something like this but it won't work! I keep getting error 400
$.ajax({
url: "https://www.blueworkslive.com/api/Auth",
type: "GET", //This is what you should chage
dataType: "jsonp",
username: "admin", // Most SAP web services require credentials
password: "admin",
processData: false,
contentType: "application/json; charset=utf-8",
success: function () {
alert("success");
console.log("success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error");
console.log(xhr.responseText);
alert(xhr.status);
alert(xhr.responseText);
},
});
And this as well:
{$(document).ready(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.blueworkslive.com/api/Auth?version=20091212", false);
xhr.setRequestHeader("Authorization", "Basic " + btoa("username.com:password"));
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin: *");
xhr.send("");
alert(xhr.status);
alert(xhr.responseText);
});}
Error: Origin is not allowed by Access-Control-Allow-Origin. I assumed the error was caused due to me running the script from a local server (since the origin was set to null by default) so I deployed it on a app development server so that I had a public origin.The same error occurred for the new origin - even though the origin now was not null anymore but the server provided origin!
$(document).ready(function(){
$(function (){
$.ajax({
url: 'https://www.blueworkslive.com/api/Auth', // url checked ...// error 400 not found url
data: {
//data
username:username,
email:email
},
dataType: 'json',
success: function(data)
{
//result success
}
});
});
});

Categories

Resources