stripe.confirmCardPayment is not a function - node.js

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.

Related

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.

Problem with ottoman not resolving the references

I have two models in my ottoman 1.0.5 setup. One holds contact info which includes an emails array of docs and then the email doc. I can insert new contacts fine as well as emails in docs and the corresponding link in the contact doc for the new email.
Here is my model
const ottoman = require("ottoman")
ottoman.bucket = require("../app").bucket
var ContactModel = ottoman.model("Contact",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
first_name : "string",
last_name : "string",
emails: [
{
ref:"Email"
}
]} )
var EmailModel = ottoman.model("Email",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
type : "string",
address : "string",
name: "string"
} )
module.exports = {
ContactModel : ContactModel,
EmailModel : EmailModel
}
Now to get an contact and all its emails i use this function
app.get("/contacts/:id", function(req, res){
model.ContactModel.getById(req.params.id,{load: ["emails"]}, function(error, contact){
if(error) {
res.status(400).json({ Success: false , Error: error, Message: ""})
}
res.status(200).json({ Success: true , Error: "", Message: "", Data : contact})
})
})
Which returns me this
{
"Success": true,
"Error": "",
"Message": "",
"Data": {
"timestamp": "2019-01-30T23:59:59.188Z",
"emails": [
{
"$ref": "Email",
"$id": "3ec07ba0-aaec-4fd4-a207-c4272cef8d66"
}
],
"_id": "0112f774-4b5d-4b73-b784-60fa9fa2f9ff",
"first_name": "Test",
"last_name": "User"
}
}
if i go and log the contact to my console i get this
OttomanModel(`Contact`, loaded, key:Contact|0112f774-4b5d-4b73-b784-60fa9fa2f9ff, {
timestamp: 2019-01-30T23:59:59.188Z,
emails: [ OttomanModel(`Email`, loaded, key:Email|3ec07ba0-aaec-4fd4-a207-c4272cef8d66, {
timestamp: 2019-01-31T00:36:01.264Z,
_id: '3ec07ba0-aaec-4fd4-a207-c4272cef8d66',
type: 'work',
address: 'test#outlook.com',
name: 'Test Outlook',
}),
OttomanModel(`Email`, loaded, key:Email|93848b71-7696-4ef5-979d-05c19be9d593, {
timestamp: 2019-01-31T04:12:40.603Z,
_id: '93848b71-7696-4ef5-979d-05c19be9d593',
type: 'work',
address: 'newTest#outlook.com',
name: 'Test2 Outlook',
}) ],
_id: '0112f774-4b5d-4b73-b784-60fa9fa2f9ff',
first_name: 'Test',
last_name: 'User',
})
This shows that emails was resolved but why does it not show up in the returned json. On the other hand if i return contact.emails i get the resolved emails just fine. So i hope someone can shed some light on what i am missing here
I asked a similar question on the couchbase forum, and I also found out the solution:
(a slight difference that the result of my search is an array not an object like in your case)
forum.couchbase.com
app.get("/assets", (req, res) => {
AssetModel.find({}, { load: ["assetModelId", "assetGroupId", "assetTypeId"] }, (err, results) => {
if (err) return res.status(400).send("no asset found");
const assets = [];
results.map(asset => {
assets.push({...asset});
});
res.status(200).send(assets)
});
});

Email verification using secrettoken in nodejs

I am trying to verify the user by taking the secrettoken from the link sent in the email. I am able to extract the secrettoken but not able to update the value of active as true.
Below is my code
router.route('/verify')
.get((req,res)=>{
console.log('request recieved');
const token = req.query.id;
User.updateOne(
{ secretToken: token },
{
$set: { price: true }
},function(err,res){
if(err){
throw err;
}
else{
console.log('one document updated');
}
}
);
});
"email": "surendrap720#gmail.com",
"username": "surendrap720",
"password": "$2a$10$UEKSpPpVWfZ3urclkayW6OcAUvscBrql23WU6fvfbI0Nd1jzo2Bxa",
"type": "tutor",
"secretToken": "5A6fXVh5gEObwUQxgpG4DpJ85COMJveJ",
"active": false,
You are not modifying active at all in your updateOne code.
change this:
$set: { price: true }
to this:
{ active: true }

Creating a customer in BrainTree with a credit card

I'm reading the docs about creating a customer. I need to create one with a credit card, a cvc number but I get an error and I don't know how I must create it.
I show my code
if(user.local.subscription == undefined){
//creamos cliente
gateway.customer.create({
creditCard : {
number : cardnumber,
expirationDate : "12/15"
}
}, function (err, result) {
if(err){
//return res.status(500).json({ error : "Error creating customer"});
console.log(err);
}
console.log(result);
/*user.subscription = result;
userId = result.customer.id;*/
});
}
var braintree = require("braintree");
var gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "your sanboxmerchant",
publicKey: "your sandbox public key",
privateKey: "sandbox privatekey"
});
gateway.customer.create({
creditCard : {
cardholder_name : 'james bliz',
number : "4111111111111111",
cvv : '123',
expirationDate : "12/17"
}
}, function (err, result) {
if(err){
//return res.status(500).json({ error : "Error creating customer"});
console.log(err);
}
console.log(result);
/*user.subscription = result;
userId = result.customer.id;*/
});
the answer should be somthing like this
{ customer:
{ id: '29931379',
merchantId: 'qn5442rvm794nc6q',
firstName: null,
lastName: null,
company: null,
email: null,
phone: null,
fax: null,
website: null,
createdAt: '2015-05-12T10:33:41Z',
updatedAt: '2015-05-12T10:33:42Z',
customFields: '',
creditCards: [ [Object] ],
addresses: [],
paymentMethods: [ [Object] ] },
success: true }
take the required field from it i think you will need only the customer id from tha result object.

Using Paypal Rest API with Node

I am having a problem debugging my paypal integration with Node and the rest api https://github.com/paypal/rest-api-sdk-nodejs
I created a Paypal account
I got the creditials for the app
I created an app and set a password for a user
I log into the sandbox with that user
I don`t see any transaction history
The code snippet is as follows :
var config_opts = {
'host': 'api.sandbox.paypal.com',
'port': '',
'client_id': 'my id',
'client_secret': 'my secret'
};
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000",
"cancel_url": "http://localhost:3000"
},
"transactions": [{
"amount": {
"currency": "USD",
"total": "10.00"
},
"description": "This is the payment description."
}]
};
paypal_sdk.payment.create(create_payment_json, config_opts, function (err, res) {
if (err) {
console.log( err );
}
if (res) {
console.log("Create Payment Response");
console.log(res);
}
});
The response I get is as follows:
{ id: 'PAY-55J119327J2030636KLXMVJI',
create_time: '2014-02-02T22:45:57Z',
update_time: '2014-02-02T22:45:57Z',
state: 'created',
intent: 'sale',
payer:
{ payment_method: 'paypal',
payer_info: { shipping_address: {} } },
transactions:
[ { amount: [Object],
description: 'This is the payment description.' } ],
links:
[ { href: 'https://api.sandbox.paypal.com/v1/payments/payment/PAY- 55J119327J2030636KLXMVJI',
rel: 'self',
method: 'GET' },
{ href: 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-90D3081342725343U',
rel: 'approval_url',
method: 'REDIRECT' },
{ href: 'https://api.sandbox.paypal.com/v1/payments/payment/PAY-55J119327J2030636KLXMVJI/execute',
rel: 'execute',
method: 'POST' } ] }
I am wondering if there is some additional step in authenticating that I am missing ?
First, you have to declare a proper return_url (not just localhost:3000). I suggest that you change your return_url to "http://localhost:3000/success". Then, insert this one above your payment POST METHOD:
app.get('/success', function(req, res) {
var paymentId = req.query.paymentId;
var payerId = { 'payer_id': req.query.PayerID };
paypal.payment.execute(paymentId, payerId, function(error, payment){
if(error){
console.error(error);
} else {
if (payment.state === 'approved'){
res.send('payment completed successfully');
console.log(payment);
} else {
res.send('payment not successful');
}
}
});
});
This GET method will execute your payment. But, before it can execute, you must redirect first your server's response to paypal sandbox for payment confirmation.
Edit the content of your paypal_sdk.payment.create() function like this one:
paypal_sdk.payment.create(create_payment_json, config_opts, function (err, res) {
if (err) {
console.log( err );
}
else {
console.log("Create Payment Response");
console.log(res);
//you forgot to redirect your response to paypal sandbox
var redirectUrl;
for(var i=0; i < payment.links.length; i++) {
var link = payment.links[i];
if (link.method === 'REDIRECT') {
redirectUrl = link.href;
}
}
res.redirect(redirectUrl);
}
});
I hope this can help (especially to those who are still looking for answers)
You must go to Dashboard -> Rest API transactions.
See the attached screenshot:

Resources