How to terminate My function, it is working but never ending - node.js

I use the api mangopay for my app. The function to transfered worked but it never end until I refresh my page. I have no error code, the function still working but we can't get the message: 'the money is transfered'
Maybe I forgot something on my function ?
transfertMangoReferent: (req, res) => {
Serveur.findOne(
{ email: req.body.email },
"mangoWallet abonne",
(err, user) => {
if (user.abonne === true) {
api.Transfers.create(
{
AuthorId: req.user.mangoID,
DebitedFunds: {
Currency: "EUR",
Amount: req.body.amount * 100,
},
Fees: {
Currency: "EUR",
Amount: req.body.amount * 100 * 0.15,
},
DebitedWalletId: req.user.mangoWalletReferent,
CreditedWalletId: user.mangoWallet,
Tag: "Versement du pot Commun",
},
(model) => {
(error) => {
if (error) {
res.status(500).json({
message: "An error has occured with MANGO users",
});
}else{
res.json(model)
}
};
}
);
} else {
api.Transfers.create(
{
AuthorId: req.user.mangoID,
DebitedFunds: {
Currency: "EUR",
Amount: req.body.amount * 100,
},
Fees: {
Currency: "EUR",
Amount: req.body.amount * 100 * 0.25,
},
DebitedWalletId: req.user.mangoWalletReferent,
CreditedWalletId: user.mangoWallet,
Tag: "Versement du pot Commun",
},
(model) => {
(error) => {
if (error) {
res.status(500).json({
message: "An error has occured with MANGO users",
});
} else {
res.json(model)
}
};
}
);
}
}
);
},
On my network when i click to my button validate i have just the code 200
I can give you also my fetch in a react js
<Button
className="CollectButton"
type="submit"
onClick={() => {
const headers = new Headers({
"Content-Type": "application/json",
Authorization: "bearer " + localStorage.getItem("token"),
});
const data = {
email: element.serveurMail,
amount: this.state.referent.amount,
};
const options = {
method: "POST",
headers: headers,
body: JSON.stringify(data),
};
fetch("https://back-end.osc-fr1.scalingo.io/serveur/referentTransfert", options)
.then((response) => {
return response;
})
.then(
(data) => {
console.log(data);
},
(error) => {
console.log(error);
}
);
}}
>
Envoyez
</Button>

Related

Store Json object in mongoDb with fetch request

I have a User model and trying to add education field to mongoDB as json object as follows,
User model
education: {
"school": String,
"years":Number
},
Client
//add Education section
const updateEducation = async (e) => {
e.preventDefault();
await fetch(`http://localhost:5000/api/user/updateEducation`, {
method: "PUT",
headers: { "Content-Type": "application/JSON", token: accessToken },
body: JSON.stringify({ userid: userid, educationSchool: educationSchool,
educationYearText: EducationYear}),
})
.then((res) => res.json())
.then((data) => {
console.log("User education is:", data.education +""+data.educationYear);
});
};
Server
const updateEducation = async (req, res) => {
try {
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$set: {
'education.school': req.body.educationSchool,
'education.years': req.body.educationYearText,
},
}
);
if (!user) {
res.status(404).json("user not exist");
}
res
.status(200)
.json({
education: user.education.School,
educationYear: user.education.years,
});
} catch (error) {
res.status(500).send({ error: error.message });
}
};
When im hitting this endpoint in postman http://localhost:5000/api/user/updateEducation
{
"userid":"63bbe4df75dca5aac7576e47",
"educationSchool":"Test college",
"educationYearText":"2018"
}
Im getting {
"error": "Plan executor error during findAndModify :: caused by :: Cannot create field 'school' in element {education: []}"
}
Whats wrong?
You should $push into an array:
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$push: {
education: {
school: req.body.educationSchool,
years: req.body.educationYearText,
}
},
},
{ new: true }
);

Recaptcha v3 Invalid Input Response

I'm having a problem when trying to apply recaptcha into my web app.
Basically, it's returning the error message: "invalid-input-response"
What could I be doing wrong?
Stack:
#nuxtjs/recaptcha 1.1.1
express-recaptcha 5.1.0
nuxt 2.15.8
node 16.15.9
Here is my configuration on front, I don't have certain about the recaptcha mode, if I should use base or enterprise.
nuxt.config.js
modules: [
'#nuxtjs/recaptcha',
],
recaptcha: {
hideBadge: true,
mode: 'base',
siteKey: 'MY_SITE_KEY',
version: 3,
size: 'normal',
},
On index I don't know if has any problem here
Based on docs, it's only do that
On my action I'm sending the token alongside my data on that format
{
token: 'asdadsadadasdas',
review: {...}
}
index.vue
async mounted() {
try {
await this.$recaptcha.init()
} catch (e) {
console.log(e);
}
},
methods: {
...mapActions({
getProduct: "getProduct",
postReview: "postReview",
}),
async submit() {
const postReviewToken = await this.$recaptcha.execute('postReview')
try {
await this.postReview({
token: postReviewToken,
productId: this.$route.params.productId,
review: {
title: this.review.title,
content: this.review.content,
},
});
this.getProduct({ productId: this.$route.params.productId });
this.review = {
title: "",
content: "",
};
} catch (error) {}
},
},
Node
And on my api I just added the middleware as docs require
import { RecaptchaV3 } from 'express-recaptcha/dist'
const recaptcha = new RecaptchaV3(
'MY_SITE_KEY',
'MY_SECRET_KEY'
)
routes.post('/product/:id/review', recaptcha.middleware.verify, async (request: Request, response: Response) => {
if (request.recaptcha?.error) {
return response.status(400).json({ message: request.recaptcha.error })
}
const review = await prisma.review.create({
data: {
productId: request.params.id,
title: request.body.review.title,
content: request.body.review.content,
},
select: {
id: true,
title: true,
content: true,
}
})
response.json({review});
});

Node Js, mongoose best practice to build server side datatable logic with everything working like skip, limit, sort, filter and pagination

Right now I am able to fetch the data and show in the table in front side, but I need
help to implement the code for skip, limit, searching, sorting and pagination so everything will be a functional.
I looked over the internet but didn't find good source to implement, I hope this might
help others in future. Anyone’s help will be appreciated.
**javascript code**
$(document).ready(function() {
let table = $('#exportable_table').DataTable({
"processing": true,
"searching": true,
"serverSide": true,
"ajax": {
url:"/employee/data-table/get-data",
error:(error)=>{
console.log(error);
}
},
'columns': [
{ data: '_id' },
{ data: 'employee_name' },
{ data: 'gender' },
{ data: 'email' },
{ data: 'mobile_number' },
{ data: 'salary' },
{ data: 'created_at' },
{ data: 'updated_at' },
{ data: '', "defaultContent": "<button class='btn btn-primary' onclick='edititem();'>Edit</button>" },
{ data: '', "defaultContent": "<button class='btn btn-danger' onclick='deleteitem();'>Delete</button>"}
],
});
});
**backend side logic**
employeeDataTableData: async (req, res) => {
let employeeData = await EmployeeService.getEmployee();
var response = {
"draw": parseInt(req.query.draw),
"iTotalRecords": employeeData.length,
"iTotalDisplayRecords": 2,
"data": employeeData
}
res.status(200).send(response);
}
**logic to fetch data from database**
exports.getEmployee = async () => {
try {
let employeeData = await EmployeeModel.find().lean();
if (!employeeData) return false;
return employeeData;
} catch (error) {
console.log("Error : ", error);
}
};

PAYPAL : going from sandbox to live REST-SDK-JS

Hello ,Since everything is working perfect in sandbox mode im trying to switch to live mode .. i created a live app and got the live credentials but the issue is the backend still generating a sandbox.paypal.com link ... any solution ?
const express = require("express");
const router = express.Router();
const paypal = require("paypal-rest-sdk");
const User = require("../../../Database/User");
const Order = require("../../../Database/Orders");
const { isUserAuthenticated } = require("../../Oauth/middlewares/auth");
const { Clean_input } = require("../../utils/utils");
paypal.configure({
mode: "live", //sandbox or live
client_id:
"LIVE CLIENT ID",
client_secret:
"LIVE CLIENT SECRET",
});
router.post("/pay",isUserAuthenticated, async (req, res) => {
const order_data = req.body.order_data;
var create_payment_json = {
intent: "sale",
payer: {
payment_method: "paypal",
}, application_context: {
brand_name:'BRAND NAME',
shipping_preference: 'NO_SHIPPING'
},
redirect_urls: {
return_url:
"https://rturn",
cancel_url: "cancel",
},
transactions: [
{
item_list: {
items: [
{
name: order_data.order_name,
sku: order_data.order_name,
price: order_data.price,
currency: "USD",
quantity: 1,
},
],
},
amount: {
currency: "USD",
total: order_data.price,
},
application_context: {
NOSHIPPING: 1,
},
description: order_data.order_details.msg,
},
],
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
throw error;
} else {
for (let i = 0; i < payment.links.length; i++) {
if (payment.links[i].rel === "approval_url") {
const OrderStart = new Order({
order_owner: req.user._id,
order_name: order_data.order_name,
order_details: order_data.order_details,
order_account: {
email : Clean_input(order_data.Email) ,
password : Clean_input(order_data.pwd) ,
},
order_statue: "waiting payment",
order_price: {
price: order_data.price,
taxes: "0",
total_price: order_data.price,
},
payment_methode: order_data.payment_method,
payment_info: {
payment_id: payment.id,
payment_link: payment.links[i].href,
payment_status: "waiting",
payment_data: execute_payment_json,
},
});
OrderStart.save(function (err, user) {
if (err) console.log(err);
if (user) {
console.log(user);
res.status(201).json({ payment_link: payment.links[i].href });
}
});
}
}
}
});
});
module.exports = router;
**FYI : In my code all credentials and redirects are well placed **
SOLVED : I WAS USING WEBHOOKS.JS WITH SAME SANDBOX CONFIG THAT WAS THE PROBLEM

Must provide source or customer stripe live mode

this is my first time using stripe and I am getting an error Must provide source or customer. once I went live. In the test mode I used "tok_mastercard" as my source but clearly when I went live it isn't valid. What am I missing here please help.
This is my POST request in the backend
stripe.charges
.create({
amount: req.renter.rent * 100,
currency: "usd",
source: req.body.token,
application_fee_amount: req.renter.rent * 0.05 * 100,
transfer_data: {
//the destination needs to not be hard coded it needs to
//come from what property the renter is in
destination: req.renter.stripeConnectId,
// destination: "acct_1GOCMqDfw1BzXvj0",
},
})
.then((charge) => {
console.log(req.renter);
res.send(charge);
})
.catch((err) => {
console.log(err);
});
});
this is my two functions in the frontend using react-native and node
handleCardPayPress = async () => {
try {
this.setState({ loading: true, token: null });
const token = await stripe.paymentRequestWithCardForm({
// Only iOS support this options
smsAutofillDisabled: true,
requiredBillingAddressFields: "full",
prefilledInformation: {
billingAddress: {
name: "",
line1: "",
line2: "",
city: "",
state: "",
country: "US",
postalCode: "",
email: "",
},
},
});
this.setState({ loading: false, token });
} catch (error) {
this.setState({ loading: false });
}
};
makePayment = async () => {
try {
//Mate the payment
const response = await unitApi.post("/payments", {
data: {
amount: this.state.renter.rent,
currency: "usd",
token: this.state.token,
},
});
Alert.alert("Success!", `Confirmation ID: ${response.data.id}`, [
{ text: "Done" },
]);
console.log(response.data);
// navigate("Home");
} catch (err) {
//failiur and showing the error message
console.log(err);
Alert.alert("Failed!", "Card declined.", [{ text: "Declined" }]);
}
};
Odds are pretty good that this.state.token doesn't contain what you think it does in the unitApi.post() function call; I'd recommend logging that and seeing if that helps, and also logging req.body.token server-side.

Resources