Save a payment method for later
Save a customer's payment method without charging it, with a SetupIntent, the Payment Element and useSetupIntent(). Stripe runs 3D Secure while the customer is present, so later off-session charges are less likely to fail. To decide between a SetupIntent and a PaymentIntent, see Payment objects.
Before you begin
- Vue Stripe is installed and its stylesheet imported (Install and set up).
- A Stripe Customer (
cus_...) for the person whose payment method you save, stored with your user record. The server sample reads it fromreq.user.stripeCustomerId. - Your app can reach your server's
/apiroutes during development (Send API requests to your server).
1. Create a SetupIntent on your server
// Node.js (Express-style handler)
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)
app.post('/api/create-setup-intent', async (req, res) => {
const setupIntent = await stripe.setupIntents.create({
customer: req.user.stripeCustomerId, // the signed-in customer, never an ID from the browser
automatic_payment_methods: { enabled: true }
})
res.json({ clientSecret: setupIntent.client_secret })
})2. Render the Payment Element with the SetupIntent
Pass the SetupIntent's client secret to VueStripeElements. The save button goes in a child component so it can use the composable.
<!-- SaveCardPage.vue -->
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
VueStripeProvider,
VueStripeElements,
VueStripePaymentElement
} from '@vue-stripe/vue-stripe'
import '@vue-stripe/vue-stripe/style.css' // once, e.g. in main.ts
import SaveCardButton from './SaveCardButton.vue'
const publishableKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY
const setupSecret = ref('')
const isComplete = ref(false)
const status = ref<'idle' | 'success' | 'error'>('idle')
const errorMessage = ref('')
onMounted(async () => {
try {
const response = await fetch('/api/create-setup-intent', { method: 'POST' })
if (!response.ok) throw new Error(`HTTP ${response.status}`)
setupSecret.value = (await response.json()).clientSecret
} catch {
status.value = 'error'
errorMessage.value = 'Could not start saving your card. Please reload the page.'
}
})
</script>
<template>
<VueStripeProvider v-if="setupSecret" :publishable-key="publishableKey">
<VueStripeElements :client-secret="setupSecret">
<VueStripePaymentElement @change="(e) => (isComplete = e.complete)" />
<SaveCardButton
:client-secret="setupSecret"
:disabled="!isComplete"
@success="status = 'success'"
@error="(msg) => { status = 'error'; errorMessage = msg }"
/>
</VueStripeElements>
</VueStripeProvider>
<p v-if="status === 'success'">Card saved.</p>
<p v-if="status === 'error'" class="error">{{ errorMessage }}</p>
</template>3. Confirm the SetupIntent
confirmSetup() runs elements.submit() for you, then confirms; a validation error comes back as result.error like a confirmation error. Pass skipSubmit: true only if you already called useStripeElements().submit() yourself.
<!-- SaveCardButton.vue: rendered inside VueStripeElements -->
<script setup lang="ts">
import { ref } from 'vue'
import { useSetupIntent } from '@vue-stripe/vue-stripe'
import type { SetupIntent } from '@vue-stripe/vue-stripe'
const props = defineProps<{ clientSecret: string; disabled: boolean }>()
const emit = defineEmits<{
(e: 'success', setupIntent: SetupIntent): void
(e: 'error', message: string): void
}>()
const { confirmSetup, loading } = useSetupIntent()
const saved = ref(false)
const handleSave = async () => {
const result = await confirmSetup({
clientSecret: props.clientSecret,
confirmParams: {
return_url: `${window.location.origin}/account/cards`
},
redirect: 'if_required'
})
if (result.error) {
emit('error', result.error.message || 'Failed to save card')
} else if (result.setupIntent?.status === 'succeeded') {
saved.value = true
emit('success', result.setupIntent)
}
}
</script>
<template>
<button v-if="!saved" :disabled="disabled || loading" @click="handleSave">
{{ loading ? 'Saving...' : 'Save card' }}
</button>
</template>The button goes away once the card is saved, and the page shows "Card saved." in its place. A SetupIntent can be confirmed only once: a second click would get an error from Stripe, and the page would replace "Card saved." with it. To save another card, create a new SetupIntent.
The succeeded SetupIntent's payment_method is attached to the customer. Store its ID with your customer record if you need it.
4. Show the result on the return page
Cards and most wallets save on the page (redirect: 'if_required'), and the page shows "Card saved.". Payment methods that redirect, such as some bank and wallet methods, send the customer to the return_url from step 3, /account/cards, with setup_intent_client_secret and redirect_status in the query string. Give that URL a page, or the customer lands on a 404 after saving. Read the result there with retrieveSetupIntent(), in a component inside the provider:
<!-- SetupStatus.vue: rendered inside VueStripeProvider -->
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useSetupIntent } from '@vue-stripe/vue-stripe'
const { retrieveSetupIntent } = useSetupIntent()
const status = ref('')
onMounted(async () => {
const clientSecret = new URLSearchParams(window.location.search).get('setup_intent_client_secret')
if (!clientSecret) return
const { setupIntent, error } = await retrieveSetupIntent(clientSecret)
status.value = error ? 'unknown' : (setupIntent?.status ?? 'unknown')
})
</script>
<template>
<p v-if="status === 'succeeded'">Payment method saved.</p>
<p v-else-if="status === 'processing'">Your payment method is being saved. We will email you when it is ready.</p>
<p v-else-if="status === 'requires_payment_method'">Saving failed. Please try another payment method.</p>
<p v-else-if="status">We could not check whether your payment method was saved. Please contact us.</p>
</template><!-- CardsPage.vue: the page at /account/cards -->
<script setup lang="ts">
import { VueStripeProvider } from '@vue-stripe/vue-stripe'
import SetupStatus from './SetupStatus.vue'
const publishableKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY
</script>
<template>
<VueStripeProvider :publishable-key="publishableKey">
<SetupStatus />
</VueStripeProvider>
</template>With the plugin, render <SetupStatus /> without the provider. If /account/cards is already a page in your app, for example the list of saved cards, render SetupStatus at its top; or point return_url at another page that renders it. Use this page to inform the customer only; listen for setup_intent.succeeded in a webhook to act on the saved method.
5. Charge the saved payment method later
On your server, create a PaymentIntent for the customer with the saved payment method and off_session: true:
const paymentIntent = await stripe.paymentIntents.create({
amount: 2000,
currency: 'usd',
customer: 'cus_xxx',
payment_method: paymentMethodId, // from the SetupIntent
off_session: true,
confirm: true,
metadata: { orderId: 'order_123' } // your own order ID, read back by the webhook
})If the bank asks for authentication again, the charge fails with authentication_required; bring the customer back on-session to confirm it.
Test data: see Test your integration.
See also
- useSetupIntent API: confirm options and result
- Card confirmers:
useConfirmCardSetupwith the Card Element - Start a subscription
- Handle errors and declines
- PaymentIntent or SetupIntent
- Live demo
- Stripe docs: Save and reuse payment methods
