i have implemented a payment system with stripe but when i connect with server then the server is crashed. Please answer the problem. I have created this code for payment system for my website.
My client site code-
useEffect(() => {
fetch('http://localhost:5000/create-payment-intent', {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${localStorage.getItem('accessToken')}`
},
body: JSON.stringify({ price })
})
.then(res => res.json())
.then(data => {
console.log(data);
if (data?.clientSecret) {
setClientSecret(data.clientSecret);
}
})
}, [clientSecret, price])
my server site code-
app.post('/create-payment-intent', verifyJWT, async (req, res) => {
const service = req.body;
const price = service.price;
amount = price * 100;
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: 'us',
payment_method_types: ['card']
});
res.send({ clientSecret: paymentIntent.client_secret })
})
error is coming-
rawType: 'invalid_request_error',
code: 'parameter_invalid_integer',
doc_url: 'https://stripe.com/docs/error-codes/parameter-invalid-integer',
param: 'amount',
detail: undefined,
headers: {
server: 'nginx',
date: 'Sun, 24 Jul 2022 12:43:34 GMT',
'content-type': 'application/json',
'content-length': '240',
connection: 'keep-alive',
'access-control-allow-credentials': 'true',
'access-control-allow-methods': 'GET, POST, HEAD, OPTIONS, DELETE',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'Request-Id, Stripe-Manage-Version, X-Stripe-External-Auth-Required, X-Stripe-Privileged-Session-Required',
'access-control-max-age': '300',
'cache-control': 'no-cache, no-store',
'idempotency-key': 'f17b3002-4ad7-4765-9442-3395630c3c3b',
'original-request': 'req_7sXCHThynqnGhE',
'request-id': 'req_7sXCHThynqnGhE',
'stripe-version': '2020-08-27',
'strict-transport-security': 'max-age=31556926; includeSubDomains; preload'
},
From the error message, it means that the amount sent in the PaymentIntent Create request was not an integer.
I'd suggest logging into Stripe dashboard and search the request ID req_7sXCHThynqnGhE in the search bar at the top to check amount value that you sent to Stripe.
Apart from amount value, the currency value in the request was also incorrect. It should be a three-letter ISO currency code in lowercase such as "usd".
Related
I am developing KaiOS application with web push notification capability.
While following code works on Chrome and current Mozilla it fails on KaiOS.
NodeJS code:
const push = require('web-push');
const vapidKeys = {
publicKey: 'PUBLIC_KEY',
privateKey: 'PRIVATE_KEY',
};
push.setVapidDetails(
'valid#email.com',
vapidKeys.publicKey,
vapidKeys.privateKey
);
const pushSub = {
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU',
keys: {
auth: 'AUTH',
p256dh: 'P256dH',
},
};
KaiOS:
failed to send notification WebPushError: Received unexpected response code
at IncomingMessage.<anonymous> (/node_modules/web-push/src/web-push-lib.js:347:20)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
statusCode: 401,
headers: {
date: 'Thu, 25 Feb 2021 15:35:19 GMT',
'content-length': '15',
'content-type': 'text/plain; charset=utf-8',
connection: 'close'
},
body: '{"errno":"109"}',
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU-72vZJFv0avzqAZAdWd7FSwZBINZ8AvsEkxAU2J3AFcs0e4aEUIYxi8aSzCCn8ihUgof_nfLGyR8VBprtzgZEABf14rSb9RgGgwxQip6f2792pS0BcUawcerZbNstCotDYTXdNZ7jQvegfDHUEHvril1KeEeaMoi4nGk'
}
But on Mozilla (with appropriate key changes) it response is successful. Same on Chrome.
notification response: {
statusCode: 201,
body: '',
headers: {
'access-control-allow-headers': 'content-encoding,encryption,crypto-key,ttl,encryption-key,content-type,authorization',
'access-control-allow-methods': 'POST',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'location,www-authenticate',
'content-type': 'text/html; charset=UTF-8',
date: 'Wed, 24 Feb 2021 20:38:35 GMT',
location: 'https://updates.push.services.mozilla.com/m/gAAAAABgNrlLgRnDfpaVmZjc6eqnAxoXkaYkTT4nKCTI1ZIBt62hfu2l3XvGr0F8HfvW54etByCQNSX89ubyBjd2VtXOTPqfsiC4-iDBWol9q9GRwiBSgjFc2M5-avDmrRpq9eCAsxlgGCzp2sRYRqvVDAQBHa8GznLzKmDE87rWZM6ItMiLS8PN0jqiSZFYMlqooeCK53QN',
server: 'nginx',
'strict-transport-security': 'max-age=31536000;includeSubDomains',
ttl: '2419200',
'content-length': '0',
connection: 'Close'
}
}
Here is client service worker code:
self.addEventListener('push', (event) => {
console.log('push event', event);
const title = event.data.text();
event.waitUntil(self.registration.showNotification(title));
});
Any ideas, what could be a problem?
push.sendNotification(pushSub, 'hello my name is me', {
contentEncoding: 'aesgcm'
})
.then(function (res) {
console.log('notification response: ', res);
})
.catch(function (err) {
console.error('failed to send notification', err);
});
https://github.com/web-push-libs/web-push/issues/603
This server push.kaiostech.com require authorization. It allows access from KaiOS device only.
Get request sent from POSTMAN works but when sent from browser fails.
At the backend req.body is undefined even after using bodyparser middleware.
The same requet when sent from the POSTMAN works.
This is the axios call from the frontend.
await axios.get(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});
This is the backend auth handler
const isAuthenticated = (req,res,next)=>{
const accesstoken = req.body.accesstoken;
console.log(req.body);
if(!accesstoken)
{
res.json({msg:"No token provided"});
}
else
{
jwt.verify(accesstoken,process.env.ACCESS_TOKEN_SECRETE,(err,decoded)=>{
if(err)
{
res.json({msg:"Invalid token"});
}
else
next();
});
}
}
These are the cors options
app.use(cors({
origin:["http://localhost:3000","http://192.168.0.86:3000"],
optionsSuccessStatus:200,
credentials:true,
allowHeaders:["Content-Type"]
}));
The method signature you are using for axios.get applies to axios.post where the second parameter is the request body. This doesn't hold true for axios.get. You can pass query paramters as second argument of axios.get. Postman is allowing you to make GET requests with body and the server is okay with that but it isn't advised to do so. For your use case of authentication, use POST.
I guess, you meant to do axios.post:
await axios.post(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});
Http token request description(Doc)
URL: https://demo.tld/connect/token
HTTP Verb: POST
HTTP Headers:
Authorization: Basic base64encode(clientId:clientSecret)
Content-Type: multipart/form-data
HTTP Body:
grant_type: client_credentials
My requested code:
try {
let endCodeOfAuth = 'Basic ' + new Buffer(clientId + ':' + clientSecret).toString('base64');
HTTP.post("https://demo.tld/connect/token", {
headers: {
'Authorization': endCodeOfAuth,
'Content-Type': 'multipart/form-data'
},
content: 'grant_type:client_credentials'
}, (error, res) => {
if (res) console.log("2. res", res );
else console.log("1. error", error);
});
return true;
} catch (error) {
return false;
}
Response:
statusCode: 500,
content: '',
headers: {
server: 'Kestrel',
'x-powered-by': 'ASP.NET',
date: 'Mon, 01 Jun 2020 11:54:59 GMT',
connection: 'close',
'content-length': '0'
},
data: null
}
I am trying to authenticate a user for login. However, I don't manage to send a response header.
Login function
// POST /users/login
router.post('/users/login', async (req, res) => {
try {
const body = _.pick(req.body, ['email', 'password']);
const user = await User.findByCredentials(body.email, body.password);
const token = await user.generateAuthToken();
req.session['token'] = 'Bearer ' + token;
req.session['user'] = user;
// the following line does not seem to work properly
res.header('Authorization', 'Bearer ' + token).send(user);
} catch (err) {
res.status(401).json({ message: "Nutzerdaten sind nicht korrekt" });
}
});
Axios plugin
$axios.onResponse(res => {
console.log(res.headers) // does not return an authorization header
if (res.headers.authorization) {
store.commit('auth/SET_TOKEN', res.headers.authorization)
}
return res
})
console.log(res.headers)
'x-powered-by': 'Express',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'content-type': 'application/json; charset=utf-8',
'content-length': '2',
etag: 'W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"',
date: 'Tue, 30 Jul 2019 12:35:00 GMT',
connection: 'keep-alive'
I would be very thankful for any kind of help!
I am trying to implement the legacy call to FCM server where the response is unexpected. There it shows the Parsing Error which is not traceable for me as of now. I am posting the code snippet below. Please help me out if anything is missing or coded in wrong manner.
var request = require('request');
let message = {
"to": atoken,
"data": {
title: "My first push notification",
body: "Hello World!!!"
}
};
// //let message = req.body.message;
let key = "AIzaSyA1zIxVFJ3F7-_-XXXXXXXXXXXXXXXXXXX";
request({
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-type': 'application/json',
'Authorization': 'key=' + key
},
postData: JSON.stringify(message)
},
function (error, response, body) {
if (error) {
console.error('upload failed:', error);
res.status(500).json({ error: true, data: { message: error.message } });
} else {
let data = response;
console.log('Upload successful! Server responded with:',
data.toJSON());
//res.status(200).json(response);
}
});
The response coming is:
body:
'JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.\n',
headers:
{ 'content-type': 'text/plain; charset=UTF-8',
date: 'Tue, 16 Apr 2019 06:34:05 GMT',
expires: 'Tue, 16 Apr 2019 06:34:05 GMT',
'cache-control': 'private, max-age=0',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block',
server: 'GSE',
'alt-svc': 'quic=":443"; ma=2592000; v="46,44,43,39"',
'accept-ranges': 'none',
vary: 'Accept-Encoding',
connection: 'close' },
request:
{ uri:
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'fcm.googleapis.com',
port: 443,
hostname: 'fcm.googleapis.com',
hash: null,
search: null,
query: null,
pathname: '/fcm/send',
path: '/fcm/send',
href: 'https://fcm.googleapis.com/fcm/send' },
method: 'POST',
headers:
{ 'Content-type': 'application/json',
Authorization: 'key=AIzaSyA1zIxVFJ3F7-_-hrIbTHTehNRmTUwG8Z0',
'content-length': 0 } } }
Try changing postData: JSON.stringify(message) in request.post() to body: JSON.stringify(message).