Vue Use Stripe

0.1.1 · active · verified Sun Apr 19

Vue Use Stripe is a lightweight (0.7 KB gzipped) Vue 3 wrapper for Stripe.js, providing a Composition API hook (`useStripe`) and a `StripeElement` component to simplify the integration of Stripe Elements. It is written in TypeScript and ships with comprehensive type definitions. The library currently stands at version 0.1.1 and has a relatively stable, though infrequent, release cadence, primarily focusing on minor enhancements and bug fixes. A key differentiator is its support for both Vue 2 (via `vue-demi` and `@vue/composition-api`) and Vue 3, allowing for broader compatibility in existing projects. It primarily focuses on exposing Stripe's functionalities through reactive Vue constructs, rather than introducing complex abstractions, making it a thin and flexible layer over the official Stripe.js library.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Stripe, create a 'card' element, and handle its change events in a Vue 3 Composition API setup. It also shows a basic `confirmCardSetup` call, emphasizing the need for a backend-provided client secret.

import { defineComponent, ref } from 'vue'
import { useStripe, StripeElement } from 'vue-use-stripe'

export default defineComponent({
  components: { StripeElement },
  setup() {
    const event = ref(null)

    const { stripe, elements: [cardElement] } = useStripe({
      key: process.env.VUE_APP_STRIPE_PUBLIC_KEY ?? '',
      elements: [{ type: 'card', options: {} }],
    })

    const registerCard = async () => {
      if (event.value?.complete && stripe.value && cardElement.value) {
        // Example: Confirm card setup. Replace with your actual Stripe API call.
        // Ensure a client secret is provided from your backend.
        const { setupIntent, error } = await stripe.value.confirmCardSetup(
          '<YOUR_CLIENT_SECRET_FROM_BACKEND>', // Replace with actual client secret
          {
            payment_method: {
              card: cardElement.value,
            },
          }
        )

        if (error) {
          console.error('Error confirming card setup:', error.message)
        } else if (setupIntent) {
          console.log('Card setup successful:', setupIntent)
          // Send setupIntent.id to your server for further processing
        }
      }
    }

    return {
      event,
      cardElement,
      registerCard,
    }
  },
  template: `
    <div>
      <StripeElement :element="cardElement" @change="event = $event" />
      <button @click="registerCard">Add Card</button>
      <div v-if="event && event.error" style="color: red;">{{ event.error.message }}</div>
      <div v-else-if="event && event.complete">Card input complete.</div>
    </div>
  `
})

view raw JSON →