Once off payment with Stripe using the API ID

Viewed 3175

I have created a subscription service using Stripe. I can subscribe a user to use recurring payments. This is the relevant code (node):

  // Create the subscription
  const subscription = await stripe.subscriptions.create({
    customer: req.body.customerId,
    items: [{ price: req.body.priceId }],
    expand: ['latest_invoice.payment_intent'],
  });

This works and uses the priceId as shown in the dashboard:

enter image description here

However, it falls over when I sell a product which isn't recurring. I get the error:

The price specified is set to `type=one_time` but this field only accepts prices with `type=recurring`

I understand the error, but I am not sure if I can set a subscription to not be recurring.

My app has 3 tiers:

  • once off
  • monthly
  • yearly

Ideally, I would like not to add a whole new section of code to handle what seems like a subset of what subscriptions do, but even if I do, the paymentIntent object seems to only take an amount rather than the API ID as shown in the picture. Is there any way to do this using the infrastructure I have already built?

2 Answers

You can't create a subscription with a non-recurring price, instead for one-off payments you'd use a PaymentIntent.

Prices are meant for use with subscriptions and the Checkout product, but you can still use the data in them for PaymentIntents. For instance:

// get the price 
const price = await stripe.prices.retrieve(req.body.priceId);

// check if the price is recurring or not
if (price.recurring !== null) {
  // Create the subscription
  const subscription = await stripe.subscriptions.create({
    customer: req.body.customerId,
    items: [{ price: req.body.priceId }],
    expand: ['latest_invoice.payment_intent'],
  });

  // do something with the subscription

} else {
  const pi = await stripe.paymentIntents.create({
    customer: req.body.customerId,
    currency: 'usd',
    amount: price.unit_amount,
  });
 
  // do something with the PaymentIntent
}
Related