npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

rescript-stripe

v0.11.0

Published

💸 Stripe Billing as a Config

Readme

ReScript Stripe 💸

ReScript client for the Stripe API.

npm install rescript-stripe

Bindings

The package contains partial bindings for the Stripe NodeJs client.

Please, create a PR if you need something missing.

Billing as a Config

Describe your Billing as a config and interact with Stripe API with the best DX possible and Git history.

module CourseSubscription = {
  type data = {
    userId: string,
    courseName: string,
    courseId: string,
  }
  type plan =
    | Starter
    | Pro({withExtraSeats: bool})

  let userId = Stripe.Metadata.ref("user_id", S.string)
  let courseId = Stripe.Metadata.ref("course_id", S.string)
  let withExtraSeats = Stripe.Metadata.ref("with_extra_seats", S.bool)

  let config = {
    Stripe.Billing.ref: "course",
    data: s => {
      userId: s.primary(userId, ~customerLookup=true),
      courseId: s.primary(courseId),
      courseName: s.matches(S.string),
    },
    termsOfServiceConsent: true,
    plans: [
      (
        "starter",
        s => {
          s.tag(withExtraSeats, false)
          Starter
        },
      ),
      (
        "pro",
        s => {
          Pro({
            withExtraSeats: s.field(withExtraSeats),
          })
        },
      ),
    ],
    products: (~plan, ~data) => {
      switch plan {
      | Starter => [
          {
            name: data.courseName,
            ref: `starter_course_${data.courseId}`,
            prices: [
              {
                ref: `starter_course_${data.courseId}`,
                lookupKey: true,
                currency: USD,
                unitAmountInCents: 10_00,
                recurring: Licensed({
                  interval: Month,
                }),
              },
              {
                ref: `starter_course_${data.courseId}_yearly`,
                lookupKey: true,
                currency: USD,
                unitAmountInCents: 100_00,
                recurring: Licensed({
                  interval: Year,
                }),
              },
            ],
          },
        ]
      | Pro({withExtraSeats}) => [
          {
            Stripe.ProductCatalog.name: data.courseName,
            ref: `pro_course_${data.courseId}`,
            prices: [
              {
                ref: `pro_course_${data.courseId}`,
                lookupKey: true,
                currency: USD,
                unitAmountInCents: 50_00,
                recurring: Licensed({
                  interval: Month,
                }),
              },
              {
                ref: `pro_course_${data.courseId}_yearly`,
                lookupKey: true,
                currency: USD,
                unitAmountInCents: 500_00,
                recurring: Licensed({
                  interval: Year,
                }),
              },
            ],
          },
        ]->Array.concat(
          withExtraSeats ? [
            {
              Stripe.ProductCatalog.name: data.courseName ++ " Additional Seats",
              ref: `pro_course_${data.courseId}_extra_seat`,
              unitLabel: "user",
              prices: [
                {
                  ref: `pro_course_${data.courseId}_extra_seat`,
                  lookupKey: true,
                  currency: USD,
                  unitAmountInCents: 10_00,
                  recurring: Metered({
                    interval: Month,
                    ref: `extra_seat`,
                  }),
                },
                {
                  ref: `pro_course_${data.courseId}_extra_seat_yearly`,
                  currency: USD,
                  unitAmountInCents: 10_00,
                  recurring: Metered({
                    interval: Year,
                    ref: `extra_seat`,
                  }),
                }
              ]
            }]
          : []
        )
      }
    },
  }
}

After you described the config, you can use it to interact with Stripe API.

Create subscription

await stripe->Stripe.Billing.createHostedCheckoutSession({
  config: CourseSubscription.config,
  data: {
    userId: "dzakh",
    courseId: "rescript-schema-to-the-moon",
    courseName: "ReScript Schema to the Moon",
  },
  plan: Starter,
  interval: Month,
  allowPromotionCodes: true,
  successUrl: `https://x.com/dzakh_dev`,
})

Retrieve customer

let customer = await stripe->Stripe.Billing.retrieveCustomer({
  userId: "dzakh",
  courseId: "rescript-schema-to-the-moon",
  courseName: "ReScript Schema to the Moon",
}, ~config=CourseSubscription.config)

Retrieve subscription

let subscription = await stripe->Stripe.Billing.retrieveSubscription({
  userId: "dzakh",
  courseId: "rescript-schema-to-the-moon",
  courseName: "ReScript Schema to the Moon",
}, ~config=CourseSubscription.config)

Retrieve subscription with customer

let {subscription, customer} = await stripe->Stripe.Billing.retrieveSubscriptionWithCustomer({
  userId: "dzakh",
  courseId: "rescript-schema-to-the-moon",
  courseName: "ReScript Schema to the Moon",
}, ~config=CourseSubscription.config)

Get subscription metadata

let userId = subscription->Stripe.Metadata.get(CourseSubscription.userId)
//? string

🧠 This is 100% type safe and works only on subscriptions belonging to the "Course Subscription" config.

⚠️ This requires that all plans have the same set of metadata fields. There's no explicit validation for this yet.

Verify that subscription belongs to the config

let genericSubscription = await stripe->Stripe.Subscription.retrieve("sub_123")

let userId = subscription->Stripe.Metadata.get(CourseSubscription.userId)
//? Compilation error

subscription->Stripe.Billing.verify(CourseSubscription.config)->Option.map(subscription => {
  let userId = subscription->Stripe.Metadata.get(CourseSubscription.userId)
  //? string
  userId
})

Get meter event name by reference

let eventName = subscription->Stripe.Subscription.getMeterEventName(~meterRef="extra_seat")

ReScript Stripe might create multiple meters under the hood, so you need to call the function to get the right meter event name to report usage.

This is done because you can report meter usage per customer, so if a customer has multiple subscriptions, you need to have different meters for each one. ReScript Stripe manages this for you.

Report usage for a subscription

let _ =
  await stripe->Stripe.Subscription.reportMeterUsage(
    subscription,
    ~meterRef="extra_seat",
    ~value=1,
  )

Customer portal helpers

let link = stripe->Stripe.CustomerPortal.prefillEmail(~link="https://customer.portal.com", ~email="[email protected]")

Handling a WebHook with rescript-rest and Next.js

let stripe = Stripe.make("sk_test_...")

let route = Rest.route(() => {
  path: "/api/stripe/webhook",
  method: Post,
  input: s => {
    "body": s.rawBody(S.string),
    "sig": s.header("stripe-signature", S.string),
  },
  responses: [
    s => {
      s.status(200)
      let _ = s.data(S.literal({"received": true}))
      Ok()
    },
    s => {
      s.status(400)
      Error(s.data(S.string))
    },
  ],
})

// Disable bodyParsing to make Raw Body work
let config: RestNextJs.config = {api: {bodyParser: false}}

let default = RestNextJs.handler(route, async ({input}) => {
  stripe
  ->Stripe.Webhook.constructEvent(
    ~body=input["body"],
    ~sig=input["sig"],
    // You can find your endpoint's secret in your webhook settings
    ~secret="whsec_...",
  )
  ->Result.map(event => {
    switch event {
    | CustomerSubscriptionCreated({data: {object: subscription}}) =>
      await processSubscription(subscription)
    | _ => ()
    }
  })
})

Create/Find Customer and Checkout Session for selected plan

let session = await stripe->Stripe.Billing.createHostedCheckoutSession({
  config: CourseSubscription.config,
  data: {
    userId: "dzakh",
    courseId: "rescript-schema-to-the-moon",
    courseName: "ReScript Schema to the Moon",
  },
  plan: Starter,
  interval: Year,
  allowPromotionCodes: true,
  successUrl: `https://myapp.com/success`,
})
Console.log(session.url)

🧠 It'll throw if the subscription already exist 🧠 Customer, products, prices, meters are automatically created when they are not found