Support for Subscriptions with Stripe

@ISTVS Hi Jenna,

I implemented Stripe subscriptions in a Knack app.

Here’s how to do it.

(Note: This requires custom JavaScript on the frontend and backend, so you’ll need to be comfortable coding—if not I’d be happy to assist you with that.)

The steps are:

  1. Create a Stripe Customer for each Knack account. You can do this manually by logging in to your Stripe account on the Stripe website and creating the customer. Or you can automate this by triggering an Integromat scenario when the Knack acccount is created, and making an HTTP request to the Create Stripe Customer endpoint. Then save the Stripe Customer ID as a field in the Knack account.
  2. Create an endpoint on your backend (see code here). Let’s name this endpoint Create Portal Session. This endpoint receives a Stripe Customer ID and a return URL, then creates a Portal Session, then returns that Portal Session URL to the frontend.
  3. Create a button to Manage Subscription. For example, add this to your frontend html:
    <button id="manage-subscription" class="kn-button">Manage Subscription</button>
  4. In your frontend JS, call your endpoint when the user clicks the Manage Subscription button. The code looks like this:
$('button#manage-subscription').on('click', async () => {
  $('button#manage-subscription').addClass('is-loading')
  const returnUrl = encodeURIComponent(location.href)
  const stripeCustomerId = Knack.getUserAttributes().values.field_123;
  const url = `https://example.com/.netlify/functions/create-portal-session?return_url=${returnUrl}&stripe_customer_id=${stripeCustomerId}`;
  const data = await callEndpoint(url);
  window.location.href = data.portalSession.url;
})

Now your customers will be able to manage their subscriptions, add/remove payment methods, and see their payments history.

Finally, to allow your customers to purchase the subscription, the steps are almost identical. You would follow steps 2-4 again, except you create a Checkout Session instead of a Portal Session, and you create a buy-subscription button instead of manage-subscription button. (Basically, Stripe uses two separate interfaces for buying the subscription and managing it). Checkout Sessions are very similar to Portal Sessions but have slightly different parameters, as seen in the Stripe API docs.

Hope this helps! If not, feel free to reach out.

Ian
Knack Pros