I'm trying to send bitcoin through Coinbase's API, and this is my code:
// create object to send as data
var transaction = {
to : correctusermail, // "my#email.com"
amount_string : amount, // "1.00"
amount_currency_iso : currency // "EUR"
};
// get correct auth key from user
var authq = new Parse.Query(Parse.User);
authq.get(objectid, {
success: function(userObject) {
correctauth = userObject.get("provider_access_token");
console.log(correctauth);
console.log(transaction);
// send post request
// make post request
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
access_token: correctauth,
transaction: transaction
},
success: function(httpResponse) {
response.success(120);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(111);
}
});
},
error: function(userObject, error) {
response.error(150);
}
});
As you can see I'm making sure that my correctauth var is correct by logging it, which works just fine.
All the other variables are correct, I've checked them. So what am I missing? It's probably very small.
From my understanding of the Coinbase API documentation, the access_token should always be part of the URL, e.g.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money?access_token='
+ correctauth,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
transaction: transaction
},
// ... etc ...
Related
I have gotten a token using bearer authentication using Ajax. I am unable to pass the token to another Ajax call to connect to another API. I set the alert, and the alert shows the token is passed through the sessionStorage. However, I get the following error. I listed the two Ajax calls below, the first one to get the bearer token, and the second one to use the token in another API call. What am I doing wrong?
POST https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/address/v1/addresses/resolve 401 (Unauthorized)
send # jquery-3.6.0.js:10109
ajax # jquery-3.6.0.js:9690
(anonymous) # Index:1245
dispatch # jquery-3.6.0.js:5430
elemData.handle # jquery-3.6.0.js:5234
Index:1301 {"readyState":4,"responseText":"{\"transactionId\": \"de3465a3-7b79-466b-98be-7a22f1d0a1a0\",\"errors\":[{\"code\":\"NOT.AUTHORIZED.ERROR\",\"message\":\"No access token provided. Please modify your request and try again.\"}]}","responseJSON":{"transactionId":"de3465a3-7b79-466b-98be-7a22f1d0a1a0","errors":[{"code":"NOT.AUTHORIZED.ERROR","message":"No access token provided. Please modify your request and try again."}]},"status":401,"statusText":"Unauthorized"}
$("#btnStartDiscount").click(function () {
$.ajax({
async: true,
crossDomain: true,
url: "https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/oauth/token", //pass your tenant
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
},
data: {
grant_type: "client_credentials",
client_id: "xxxxxxxxxxx", //Provide your app id
client_secret: "xxxxxxxxxxxxx", //Provide your client secret genereated from your app
},
success: function (response) {
console.log(response);
token = response.access_token;
console.log(token);
enterAddressFields();
document.FedExShip.tokenField.value = token;
sessionStorage.setItem("myToken", JSON.stringify(token));
let getToken = sessionStorage.getItem("myToken");
console.log(getToken);
alert("Connected Token " + getToken);
},
error: function (error) {
console.log(JSON.stringify(error));
},
});
});
$("#btnAddrValidate").click(function () {
/*FedEx address validation to validate street lines, city, state, postal code and country code*/
let getToken = sessionStorage.getItem("myToken");
$.ajax({
url: "https://cors-anywhere.herokuapp.com/https://apis-sandbox.fedex.com/address/v1/addresses/resolve", //post address
method: "POST",
headers: {
authorization: "'Bearer '+ getToken",
"x-locale": "en_US",
},
data: {
addressesToValidate: [
{
address: {
streetLines: ["7372 PARKRIDGE BLVD", "APT 286"],
city: "IRVING",
stateOrProvinceCode: "TX",
postalCode: "75063-8659",
countryCode: "US",
},
},
],
},
success: function (response) {
console.log(response);
token = response.access_token;
console.log(getToken);
alert("Successfully passed token " + token);
alert("Success");
/* enterAddressFields();*/
},
error: function (error) {
console.log(JSON.stringify(error));
/*alert(this.response);*/
/* alert("Failure");*/
alert("Failed to pass token " + getToken);
},
});
});
I stored the token value as localstorage.token also ,but the result was the same.
I'm dealing with Spotify's API but not succeed to automatically get a new access token.
function api() {
$.ajax({
type: 'POST',
url: 'https://accounts.spotify.com/api/token?grant_type=client_credentials',
headers: {
'Authorization': 'Basic myClientIdEncodedToBase64Format:myClientSecretEncodedToBase64Format'
},
success: function(data) {
console.log('Succes ->', data);
},
error: function(error) {
console.log('Error -> ', error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm getting a 400 error. If [i refer the doc][1], '400: Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information'.
What am i doing wrong here ?
Thanks !
Here my code. I add data :
function api() {
$.ajax({
type: 'POST',
url: 'https://accounts.spotify.com/api/token',
data: 'grant_type=client_credentials',
headers: {
'Authorization': 'Basic myClientIdAndMyClientSecretConvertedToBase64'
},
success: function(data) {
console.log('Succes ->', data);
},
error: function(error) {
console.log('Error -> ', error);
}
});
}
the overall code is a bit messy as I have been trying different things out and haven't gotten down to organizing them all. I am trying to send a PUT request to the /api/protected with the username and the new email to update the email. This is a protected route which needs the authtoken to access it which I have passed in. I am getting an unauthorized error.
function updateProfile(username, email, authToken, callback) {
const settings = {
url: '/api/protected',
data: {
username: `${username}`,
email: `${email}`,
headers: {
authorization: `Bearer ${authToken}`
},
},
dataType: 'json',
type: 'PUT',
success: callback,
error: error
};
$.ajax(settings);
}
This is the ajax request and now in the server side code:
app.put('/api/protected', jwtAuth, (req, res) => {
const updatedItem = User.update({username: req.body.username}, {$set:{email: req.body.email}})
return res.status(201).json({updatedItem});
});
If we look at the documentation, we see that the headers property should be on the settings sent to $.ajax, not within the data property. To remedy, simply move it out of the data property. For example:
function updateProfile(username, email, authToken, callback) {
const settings = {
url: '/api/protected',
data: {
username: `${username}`,
email: `${email}`,
},
headers: {
authorization: `Bearer ${authToken}`
},
dataType: 'json',
type: 'PUT',
success: callback,
error: error
};
$.ajax(settings);
}
Note that I've also cleaned up the indentation a bit to make it easier to see the correct placement.
Ext.Ajax.request({
url: 'Employee/Search',
method: 'POST',
headers: { "Content-Type":"application/json","Accept": "application/json","Authorization": "OAuth oauth_token=158ghhBtgf2586525hggfgdf" },
jsonData: {
"FirstName": txtFirstName.getValue()
},
success: function(response) {
},
failure: function(response) {
}
});
This is giving me 401 (Unauthorized Request)
I am using adal.js library by Microsoft, and using the following code:
window.acquireTokenCallback = function (error, token) {
if(error || !token) {
Ext.alert('ADALERROR', error || 'Token empty');
return;
}
// Apply token to all future Ajax requests.
Ext.Ajax.setDefaultHeaders({
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
});
// Load Settings from Server.
me.loadSettings();
};
I'm trying to use the ProductHunt API using jQuery. To use the ProductHunt API, you need to authenticate before you can access the data. I'm using the OAuth Authentication.
Here is the code that I have got.
// api key and secret
key = "api key goes here"
secret = "api secret goes here"
var base_url = "https://api.producthunt.com/v1/"
var token_url = base_url +"oauth/token"
var today_post_url = base_url + "posts"
function get_token(){
var token = '';
$.ajax({
url: token_url,
type: "POST",
async: false,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: {
"client_id": key,
"client_secret": secret,
"grant_type": 'client_credentials'
},
success: (function(res) {
token = res.access_token;
})
});
return (token);
}
function get_todays_posts() {
token = get_token();
console.log(token);
$.ajax({
url: today_post_url,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
success: (function(res){
return res;
})
})
}
But when I run get_todays_post(), I get a error message saying GET https://api.producthunt.com/v1/posts 401 (Unauthorized)