Stephen Ostermiller
Stephen Ostermiller

Reputation: 25524

Use Stripe to collect credit data, receive a token, then start and pay for a subscription

I started development on the payment system for our subscription website using Stripe's custom form: https://stripe.com/docs/custom-form. I have the development site working such that when somebody chooses a subscription, it pops up a form to collect the credit card data, that data is submitted to Stripe, and stripe sends back a token.

In the "Next steps" at the bottom, it seems to indicate that I can then use this token to sign the user up for a subscription. However, the subscription page doesn't show how to use that token when creating a subscription. It appears from that page that when a subscription is created, Stripe will create an invoice and email it to the user.

I'd really like to handle the first payment directly on the website rather than lose users in an email flow. I think it can be done, but I can't find an example. How do I use the Stripe token from the collected credit card to charge the user for the first period of the subscription? The only code for creating a subscription is:

Stripe::Subscription.create(
  :customer => customer.id,
  :plan => "basic-monthly",
)

Which doesn't pass the token in. Where do I pass the token?

Upvotes: 0

Views: 237

Answers (2)

Stephen Ostermiller
Stephen Ostermiller

Reputation: 25524

The token can be passed as the source attribute when creating a subscription:

Stripe::Subscription.create(
  :customer => customer.id,
  :plan => "basic-monthly",
  :source => token,
)

I end up doing that for existing customers. Since I am collecting their credit card information again, this allows Stripe to use whatever they just entered.

For new customers, set the source field when creating the customer. The payment source stored with the customer end up getting used when the subscription is created.

You can't create a customer with a source token and then use the same token on the subscription too. I've found out that Stripe considers this to be re-using the token and it throws an exception. You have to conditionally use it in one place or the other depending on whether or not the customer is newly created.

Upvotes: 0

Ywain
Ywain

Reputation: 17503

You need to use the token to create a customer object, and you can then use the resulting customer object to create the subscription.

This tutorial explains the subscriptions flow with Stripe: https://stripe.com/docs/subscriptions/quickstart.

Upvotes: 1

Related Questions