Making a call to Stripe API (to pause payment collection) using plain fetch, getting 400 response code - node.js

I have this code:
import fetch from 'node-fetch';
test("y", async () => {
// const username = "rk_test_xyz"
const encoded = Buffer.from(`${username}:`, 'utf-8').toString('base64')
const params = new URLSearchParams();
params.append('pause_collection[behaviour]', 'void');
const response = await fetch('https://api.stripe.com/v1/subscriptions/sub_1LFkzDH2RPqITCMjvjz9RCOJ', {
method: 'POST',
body: params,
headers: {
'Authorization': `Basic ${encoded}`,
"Content-type": `application/x-www-form-urlencoded`
}
});
const status = response.status
console.log({status})
})
When I run it I get status code 400. What is wrong with this approach?

Simple spelling mistake. Should be behavior instead of behaviour.
And for anyone debugging Stripe API failures, the Stripe API dashboard gives good error messages on the Logs view at https://dashboard.stripe.com/test/logs

Related

Node.js? API Authentication problems

This is what my "dev" sent me. Someone help please
I'm trying my best, but their API doesn't respond to our methods. This authentication is the root of the problem. I'm right now using Axios(the most popular and only method for making API requests for web apps) but it's not accepting request
and then i told him i would ask for help*
You can ask this question- ` How do I make requests for creating order API in my express app? I've tried to make the request by getting my form data from my EJS form using the request.body. But still, it is saying error 400.
Here is his code:
app.post('/order-labels', checkAuthenticated, (req, res) => {
const data = JSON.stringify(req.body);
console.log(data)
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
})
by console.logging we are getting the data, but the API doesn't accepting
The API Docs are here.
you may need an account to view just put junk
The API calls for url encoded string.
const data = JSON.stringify(req.body);
console.log(data)
data = new URLSearchParams(Object.entries(data)).toString();
console.log(data); // now should be URL encoded
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
See if the API likes the new encoding?

POST to asp.net web api fails from nodejs but works from postman

Please I have been battling with this issue. I have some api controllers and they work well with postman but posting from nodejs using axios I have errors. Here's my axios code:
var postData = JSON.stringify(req.body);
var postdataToString = JSON.parse(postData);
postdataToString['grant_type'] = "password";
delete postdataToString['submit'];
var PostBody = JSON.stringify(postdataToString);
and
let response = axios({
method: 'POST',
url: url,
proxy: undefined,
data: PostBody,
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
headers:{'Accept': 'application/json'}
})
The error output from the console shows the json data is correct.
Here is a piece from the api code:
public async Task<IHttpActionResult> Register(UserModel userModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result = await _repo.RegisterUser(userModel);
the error is invalid request.
Thanks for your help

Getting LinkedIn access token through http request on node.js server

I am following the Authorization Code Flow (3-legged OAuth) documentation and I am now at step 3 where I need to use the authorization code in order to recieve an access token from LinkedIn. In the project I am using node.js, typescript and the node-fetch library. The following function creates a body with content type x-www--form-urlencoded since this is content type which LinkedIn require.
async function GetAccessToken(data: any) {
let body: string | Array<string> = new Array<string>();
for (let property in data) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(data[property]);
body.push(encodedKey + "=" + encodedValue);
}
body = body.join("&");
const response = await fetch("https://www.linkedin.com/oauth/v2/accessToken", {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: body
}).then((res: any) => {
console.log("Result", res);
});
return response;
}
I do not recieve any errors and the response status is 200 but the response values I recieve are:
size: 0,
timeout: 0,
and what LinkedIn promise is:
access_token
expires_in
When I post the url with my parameters using postman the request goes through and I recieve the correct data which indicates the problem lies within my request function and not my values.
Any help is appreciated!
You need add all headers from postman
const urlencoded = new URLSearchParams();
urlencoded.append("client_id", env.LINKEDIN_CLIENT_ID);
urlencoded.append("client_secret",env.LINKEDIN_CLIENT_SECRET);
urlencoded.append("grant_type", "authorization_code");
urlencoded.append("code", code);
urlencoded.append(
"redirect_uri",
"http://localhost:3000/api/auth/linkedin-custom"
);
const accessTokenPromise = await fetch(
"https://www.linkedin.com/oauth/v2/accessToken",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: urlencoded,
}
);

Angular consumes express web api , bad request

My angular app consumes a nodejs webapi :
var header = {
headers: new HttpHeaders()
.set('Authorization', `Bearer ${this.token}`)
}
var url="http://localhost:3000/user/deleteTodoFromUser/"+idUser+"/"+idTodo;
return this.http.put(url,"",header);
my api :
**router.put('/deleteTodoFromUser/:id/:idTodo', passport.authenticate('bearer'), (req, res) => {**
User.findByIdAndUpdate(req.params.id,{ $pull:{todos:{$in:[req.params.idTodo]}}},{new:true},(err, usr) => {
if (err) {
res.send(err);
}
if(usr)
{
res.send(usr);
}
else
{
res.status(400).send("bad request");
}
**My api works properly in postman **
** CORS are enabled **
in angular doesn't, it returns 400 (bad request )
let params = new HttpParams();
params = params.append('id', idUser);
params = params.append('idTodo', idTodo);
this.http.put(url, "", { headers: headers, params: params });
when I add params parameter in the request , It becomes like that
http://localhost:3000/user/deleteTodoFromUser/?id=5dfa958e98710030207952cc&idTodo=5dfa976ea4ea1d31f8919ee5
but the api waits the request like that :
http://localhost:3000/user/deleteTodoFromUser/5dfa958e98710030207952cc/5dfa976ea4ea1d31f8919ee5
the difference is my api waits the request id without id?= and idTodo?=
and I want it like that
400 Bad Request, Whatever the endpoint is expecting, it's not getting it.
Seems that there is an issue while passing params to your API or the token value sent to your API is invalid.
This is another way to send parameters to your API instead of Appending them to the URL
const headers = new HttpHeaders()
.set('Authorization', `Bearer ${this.token}`);
let params = new HttpParams();
params = params.append('id', idUser);
params = params.append('idTodo', idTodo);
this.http.put(url, "", { headers: headers, params: params });
If it's not the case try to make a call using real parameters value and a valid token that works in Postman in order to detect the root cause of the error that you are getting.

Making a POST request using puppeteer with JSON payload

I'm trying to make a POST request using puppeteer and send a JSON object in the request, however, I'm getting a timeout... if I'm trying to send a normal encoded form data that at least a get a reply from the server of invalid request...
here is the relevant part of the code
await page.setRequestInterception(true);
const request = {"mac": macAddress, "cmd": "block"};
page.on('request', interceptedRequest => {
var data = {
'method': 'POST',
'postData': request
};
interceptedRequest.continue(data);
});
const response = await page.goto(configuration.commandUrl);
let responseBody = await response.text();
I'm using the same code to make a GET request (without payload) and its working
postData needs to be encoded as form data (in the format key1=value1&key2=value2).
You can create the string on your own or use the build-in module querystring:
const querystring = require('querystring');
// ...
var data = {
'method': 'POST',
'postData': querystring.stringify(request)
};
In case you need to submit JSON data:
'postData': JSON.stringify(request)
If you are sending json, you need to add "content-type": "application/json". If you don't send it you can receive an empty response.
var data = {
method : 'POST',
postData: '{"test":"test_data"}',
headers: { ...interceptedRequest.headers(), "content-type": "application/json"}
};
interceptedRequest.continue(data);

Resources