PaymentIntent with subscription-based product - node.js

I am creating a paymentIntent in my backend, and I need to know how to attach subscription based products to said paymentIntent so that I can bill the customer on an interval. Every tutorial I have seen uses Stripe checkout instead of Stripe's paymentIntent api. Here is my code:
app.post("/create-payment-intent", async (req, res) => {
const { items } = req.body;
// Create a PaymentIntent with the order amount and currency.
// How do I attach a product to the paymentIntent?
const paymentIntent = await stripe.paymentIntents.create({
amount: calculateOrderAmount(items),
currency: "usd"
});
res.send({
clientSecret: paymentIntent.client_secret
});
});
Any help would be greatly appreciated.

You need to use the Billing APIs, not a Payment Intent: https://stripe.com/docs/billing/subscriptions/examples

Related

Stripe subscription always gives me "status: 'requires_confirmation'

I have a subscription route like this. My flow looks like this
User select a plan.
User enter card details through Stripe Card Element
User click Subscribe button.
As per docs,
I'm creating a customer.
Then creating a subscription for this customer.
But, my dashboard says payment incomplete and response object on creating subscriptions shows status: 'requires_confirmation'. What I am doing wrong?
router.post('/subscription', auth, async (req, res) => {
const { payment_method, price_id } = req.body;
const customer = await Stripe.customers.create({
email: 'test#gmail.com',
payment_method: payment_method,
description: 'New Customer',
invoice_settings: { default_payment_method: payment_method }
});
try {
const subscription = await Stripe.subscriptions.create({
customer: customer.id,
items: [
{
price: price_id
}
],
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent']
});
res.send({
status: subscription.latest_invoice.payment_intent.status,
subscriptionId: subscription.id,
});
} catch (error) {
return res.status(400).send({ error: { message: error.message } });
}
});
[![Stripe dashboard][1]][1]
[1]: https://i.stack.imgur.com/Sx0zN.png
It sounds like you’re doing things a bit out of order from the way the Stripe docs suggest. In this guide, the subscription object is created prior to collecting the payment method. The reason your invoice isn’t automatically paid is because you are explicitly passing in a payment_behavior of default_incomplete, which tells Stripe not to pay the invoice and allows you to collect payment details client-side and confirm the payment. Since you have already collected payment details, don’t pass in a payment_bevavior of default_incomplete.

Stripe recurring payment integrate with masterpass

Is there any way to take recurring payment with Masterpass using Stripe?
Google pay and Apple pay can take the recurring payment with Stripe by returning the card token for stripe process. Is there any way to get card token like this with Masterpass?
Yes you can, you'd create a PaymentMethod with the data you get back from Secure Remote Commerce (which is what Masterpass is calling itself now) and use that to start a subscription.
Follow Stripe's SRC guide, then when you get to the "complete the payment" part you'd do something this instead:
// create the payment method
const pm = await stripe.paymentMethods.create({
type: 'card',
card: {
masterpass: {
cart_id: cartId, // your unique cart ID
transaction_id: req.query.oauth_verifier, // get this from the SRC callback URL
},
}
});
// create the Stripe customer
const cust = await stripe.customers.create({
payment_method: pm.id,
});
// create the subscription
const sub = await stripe.subscriptions.create({
customer: cust.id,
items: [{
price: {{PRICE_ID}},
}],
default_payment_method: pm.id,
});

Stripe No such customer (Express Connected Account)

I'm trying to allow users to create one-off invoices after they have onboarded to the platform via an Express account.
I have a Node route set up to create and send an invoice.
I'm getting the error
StripeInvalidRequestError: No such customer: 'cus_I3Xra0juO9x2Iu'
However the customer does exist in the user's connect account.
The route is below
app.post('/api/new_invoice', async (req, res) => {
try {
const { customer, deliverables, amount, payableBy } = req.body
const product = await stripe.products.create({
name: deliverables,
})
const price = await stripe.prices.create({
unit_amount: amount,
currency: 'aud',
product: product.id,
})
const invoiceItem = await stripe.invoiceItems.create({
customer,
price: price.id,
})
const stripeInvoice = await stripe.invoices.create(
{
customer,
collection_method: 'send_invoice',
days_until_due: 30,
invoiceItem,
},
{
stripeAccount: req.user.stripeAcct,
}
)
const invoice = await new Invoice({
customer,
deliverables,
amount,
paid: false,
issueDate: Date.now(),
payableBy,
_user: req.user.id,
}).save()
res.send(invoice.data)
console.log(invoiceItem, stripeInvoice)
} catch (err) {
console.log(err)
res.status(400)
res.send({ error: err })
return
}
})
From what I understand adding a second object to stripe.invoices.create with the connect account's id then it should look into their Stripe account for the customer?
Thanks in advance
When making a call on behalf of a connected account, you need to set the Stripe-Account header as their account id as documented here. This header has to be set on every API request you make on behalf of that connected account.
In your code, you are only setting the header on the Invoice Create API request but not the other one(s) such as the Invoice Item Create. Make sure to pass it everywhere and your code will start working.

How to attach a payment method with Stripe?

I'm struggling to get Stripe to work on my server.
So, on the client side, I have this code (after much struggle to get element working) :
this.props.stripe.createPaymentMethod({ type: 'card', card: cardElement, billing_details: { name: name } }).then((paymentMethod) => {
// server request with customer_id and paymentMethod.id);
});
This works fine. Now, on the server (NodeJS), I want to add a new on-going subscription with a fixed fee for my customer.
Here's what I have :
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000,
currency: 'usd',
payment_method_types: ['card'],
customer: req.body.customer_id,
metadata: { integration_check: 'accept_a_payment' },
});
const paymentIntentConfirmation = await stripe.paymentIntents.confirm(paymentIntent.id, { payment_method: req.body.paymentMethod_id });
const newSubscription = await stripe.subscriptions.create({
customer: req.body.customer_id,
items: [{ plan: premium_plan.id, quantity: 1 }],
default_payment_method: req.body.paymentMethod_id,
});
const attachPaymentToCustomer = await stripe.paymentMethods.attach(req.body.paymentMethod_id, { customer: req.body.customer_id });
const updateCustomerDefaultPaymentMethod = await stripe.customers.update(req.body.customer_id, {
invoice_settings: {
default_payment_method: req.body.paymentMethod_id,
},
});
So, if I don't attach the payment to customer, I get the following error message :
'The customer does not have a payment method with the ID pm_1Gx9m1HVGJbiGjghYhrkt6j. The payment method must be attached to the customer.'
If I do, I get the following error message :
'This PaymentMethod was previously used without being attached to a Customer or was detached from a Customer, and may not be used again.'
So, how do I add the damn payment method, so when I retrieve my customer, it shows this customer has been updated with a new subscription to the service he just subscribed to, together with his payment method (a CC in this case).
Any help here for a frustrated user is very appreciated !
On a more general note, implementing Stripe has been a very painful experience so far. Nothing seems to work. I use Typescript and there are so many bugs. The documentation is not very helpful and not well explained. "Create a source", "create a token", "create a payment intent", "create a setup intent", how am i supposed to understand the difference between all these things ? I want to add a god damn online subscription, which should be quite a standard procedure for an Internet service. Why are there so many different guidelines, with tokens, with sources, etc....
There's a few changes you can make here to get it working, in order to start a Subscription [1] you don't need to create and confirm a PaymentIntent. That is created automatically inside the Invoice(s) as they're created for payment. So the steps roughly are (you've done a lot of this already but just to have an end to end example):
Create a customer
Collect the payment information securely using Stripe.js
Attach the PaymentMethod to the Customer
(Optionally) save that as the invoice settings default payment method (because you can pass the PaymentMethod to the Subscription creation as a default payment method, but it's good practice so that you can start Subscriptions for that Customer with the same payment method)
Create a Subscription
Provision your service
Take into account SCA/3DS and handle authentication [2]
That's outlined in detail on [1]. Here's some sample code to get the Subscription started, you can replace the calls that create products and prices with your own IDs of course:
const customer = await stripe.customers.create({
name: "Foo Bartley"
});
const paymentMethod = await stripe.paymentMethods.create(
{
type: 'card',
card: {
number: '4242424242424242',
exp_month: 6,
exp_year: 2021,
cvc: '314',
},
}
);
const product = await stripe.products.create(
{name: 'Gold Special'}
);
const price = await stripe.prices.create(
{
unit_amount: 1111,
currency: 'eur',
recurring: {interval: 'month'},
product: product.id,
}
);
// Everything above here is just setting up this demo
const attachPaymentToCustomer = await stripe.paymentMethods.attach(
paymentMethod.id, // <-- your payment method ID collected via Stripe.js
{ customer: customer.id } // <-- your customer id from the request body
);
const updateCustomerDefaultPaymentMethod = await stripe.customers.update(
customer.id, { // <-- your customer id from the request body
invoice_settings: {
default_payment_method: paymentMethod.id, // <-- your payment method ID collected via Stripe.js
},
});
const newSubscription = await stripe.subscriptions.create({
customer: customer.id, // <-- your customer id from the request body
items: [{ plan: price.id, quantity: 1 }], // <-- plans and prices are compatible Prices is a newer API
default_payment_method: paymentMethod.id, // <-- your payment method ID collected via Stripe.js
});
Hope this helps!
[1] https://stripe.com/docs/billing/subscriptions/fixed-price#create-subscription
[2] https://stripe.com/docs/billing/subscriptions/fixed-price#manage-payment-authentication

When saving a customer in production, where to locate Stripe's source token

I am following Stripe's account here: https://stripe.com/docs/saving-cards
in particular where the customer information is saved:
(async function() {
// Create a Customer:
const customer = await stripe.customers.create({
source: 'tok_mastercard',
email: 'paying.user#example.com',
});
// Charge the Customer instead of the card:
const charge = await stripe.charges.create({
amount: 1000,
currency: 'usd',
customer: customer.id,
});
// YOUR CODE: Save the customer ID and other info in a database for later.
})();
in development I can input source: 'tok_mastercard' and it operates as intended, however what would the token be in production when using sk_live_... ? the doc is not clear so far as I can tell.
The token would be something you create client-side when you collect the card details securely either using Stripe Elements or Stripe Checkout. Those let you exchange card details for a Stripe Token with a unique id tok_12345 that you then send to your server to create the customer and the charge.

Resources