Must provide source or customer stripe live mode - node.js

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.

Related

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});
});

Declare the product id instead of the product informations

I'm trying to implement Stripe into my nodeJS script.
app.post('/create-checkout-session/', async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: '100 points',
},
unit_amount: 100,
},
quantity: 1,
},
],
mode: 'payment',
success_url: 'http://localhost:4200/success',
cancel_url: 'http://localhost:4200/cancel',
});
res.json({ id: session.id });
});
But that's not what I want, I would like to add the id of the product in the HTML and then show this product or that product according to, in the checkout :
<button (click)="checkout('price_1L4kj8FkiBiEQqb0n2Huec06')" class="p-10 bg-green-200 text-black m-10">
1$
</button>
.ts :
checkout(priceId) {
// Check the server.js tab to see an example implementation
this.http.post('http://localhost:3001/create-checkout-session/', { priceId })
.pipe(
switchMap(session => {
return this.stripeService.redirectToCheckout({ sessionId: session['id'] })
})
)
.subscribe(result => {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
});
}

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

How to terminate My function, it is working but never ending

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>

stripe.confirmCardPayment is not a function

when i am creating subscription through stripe it gives err message
As i am doing subscription through stripe
i am also giving some msg about authentication in dashboard like 3d secure authenticatio.
and my cvc_check is unavailable in showing dashboard
1.first issue is 3d secure authentication.
2.cvc check unavailbel in India.
My account is also india
TypeError: stripe.confirmCardPayment is not a function
my code is pls what i am doing wrong
stripe.customers.create(
{
name: name,
email: email,
phone: reqObj.phone,
address: { "city": reqObj.address, "country": "IN",
"line1": "", "line2": "", "state":"India" },
},
function (err, customer) {
if (err) {res.json({ "status": false, "error": err })
console.log(err)
}else {
customer_id=customer.id;
stripe.tokens.create(
{
card: {
number: reqObj.card_no,
exp_month: reqObj.exp_month,
exp_year: reqObj.exp_year,
cvc: reqObj.cvc
},
},
function (err, token) {
if (err) {
res.json({ "status": false, "errorT": err})
} else {
// stripe.customers.createSource(
// customer_id,
// { source: token.id },
// function (err, card) {
// if (err) {
// res.json({ status: "false", "error": err })
// }else {
stripe.plans.list(
{ product: "prod_IMGu6PI2mJbBCi", active: true },
function (err, plans) {
if (!err) {
for(i in plans.data){
if(plans.data[i].amount==reqObj.amount){
var myId=plans.data[i].id
stripe.paymentMethods.create({
type: 'card',
card: {
number: reqObj.card_no,
exp_month: reqObj.exp_month,
exp_year: reqObj.exp_year,
cvc: reqObj.cvc
},
},function(err,result){
// console.log(err,result)
stripe.paymentMethods.attach(result.id, {
customer: customer_id,
},function(err,result1){
// console.log(err,"result1",result1)
stripe.customers.update(
customer_id,
{
invoice_settings: {
default_payment_method: result.id,
},
},function(err,res2){
// console.log(err,"res2")
stripe.subscriptions.create({
customer: customer_id,
items: [{ price: myId}],
expand: ['latest_invoice.payment_intent'],
},function(err,res3){
console.log(err,"res3",
res3.latest_invoice.payment_intent.client_secret)
a=res3.latest_invoice.payment_intent.client_secret
stripe.confirmCardPayment(
res3.latest_invoice.payment_intent.client_secret,
function(err,paymentIntent)
{
console.log(err,"paymentIntent",paymentIntent)
}
)}
);
} );
});
});
}
});
}
// asynchronously called
});
Your code is mixing up client-side and server-side code together which will not work. The stripe.confirmCardPayment() method comes from Stripe.js and should be called client-side in Javascript inside the browser, not server-side with Node.js.
The beginning of your code is updating a Customer with the right default payment method id. Then it's creating a Subscription. And then, if the creation fails to have the first invoice paid, for example if the card is declined or requires 3D Secure, you have to then go back to the client, in the browser, to run the next step which is to confirm the PaymentIntent associated with the Subscription's Invoice.
So you need to go back to the client, where you originally created the PaymentMethod id pm_123456 that you passed in result.id and then try to confirm the PaymentIntent.

Resources