Learn how to integrate Stripe payments into your Vue.js app with this step-by-step tutorial, covering setup, payment forms, backend, webhooks, and deployment.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
How to Use Stripe with Vue.js: A Comprehensive Tutorial
Introduction
In this tutorial, I'll walk you through integrating Stripe payments into your Vue.js application. We'll cover everything from setting up your Stripe account to implementing payment processing functionality in your Vue application.
Step 1: Set Up Your Stripe Account
Before we can start coding, you need to set up a Stripe account:
Step 2: Create a New Vue.js Project
If you don't already have a Vue.js project, create one using the Vue CLI:
# Install Vue CLI if you haven't already
npm install -g @vue/cli
# Create a new project
vue create stripe-vue-integration
# Navigate to the project directory
cd stripe-vue-integration
Step 3: Install Required Dependencies
We need to install the Stripe.js library and any other dependencies:
npm install @stripe/stripe-js
npm install axios # For making HTTP requests to your backend
Step 4: Set Up Environment Variables
Create a .env file in your project root to store your Stripe publishable key:
VUE_APP_STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key\_here
Note: Never include your Stripe secret key in your frontend code!
Step 5: Create a Stripe Service
Create a new file called stripe-service.js
in the src/services
directory:
import { loadStripe } from '@stripe/stripe-js';
let stripePromise;
export const getStripeInstance = () => {
if (!stripePromise) {
stripePromise = loadStripe(process.env.VUE_APP_STRIPE_PUBLISHABLE_KEY);
}
return stripePromise;
};
Step 6: Create a Payment Component
Create a new component called PaymentForm.vue
in the src/components
directory:
Payment Details
Processing...
{{ error }}
Step 7: Set Up Your Backend (Node.js Express Example)
You'll need a backend to create payment intents securely. Here's an example using Node.js with Express:
// server.js
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
// Initialize Stripe with your secret key
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
// Create a payment intent
app.post('/create-payment-intent', async (req, res) => {
try {
const { amount, description } = req.body;
// Create a PaymentIntent with the order amount and currency
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: 'usd',
description,
// Verify your integration by passing this parameter
metadata: { integration_check: 'accept_a\_payment' }
});
// Send the client secret to the client
res.json({ clientSecret: paymentIntent.client\_secret });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Step 8: Use the Payment Component in Your App
Now, integrate the payment component into your Vue application:
Vue.js Stripe Checkout Example
Select a Product
{{ product.name }}
${{ (product.price / 100).toFixed(2) }}
Step 9: Handle Successful Payments
To properly handle successful payments, we'll modify our component to emit events for parent components to respond to:
// In PaymentForm.vue, add to the handleSubmit method:
if (result.paymentIntent.status === 'succeeded') {
// Emit an event with the payment intent details
this.$emit('payment-success', result.paymentIntent);
// You might also want to clear the form or reset the component state
this.card.clear();
}
Step 10: Implement Webhook Handling (Server-Side)
For production applications, you should implement webhook handling to ensure payment events are properly processed even if client-side processes fail:
// Add this to your server.js file
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
} catch (err) {
console.log(`Webhook Error: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
switch (event.type) {
case 'payment\_intent.succeeded':
const paymentIntent = event.data.object;
console.log('PaymentIntent was successful!');
// Then define and call a function to handle the event payment\_intent.succeeded
handleSuccessfulPayment(paymentIntent);
break;
case 'payment_intent.payment_failed':
const failedPaymentIntent = event.data.object;
console.log('Payment failed:', failedPaymentIntent.last_payment_error?.message);
// Then define and call a function to handle the event payment_intent.payment_failed
handleFailedPayment(failedPaymentIntent);
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
// Return a 200 response to acknowledge receipt of the event
res.send();
});
function handleSuccessfulPayment(paymentIntent) {
// Update your database, fulfill orders, etc.
console.log(`Payment for ${paymentIntent.amount} was successful!`);
}
function handleFailedPayment(paymentIntent) {
// Handle failed payments, notify users, etc.
console.log(`Payment for ${paymentIntent.amount} failed!`);
}
Step 11: Add Payment Elements for a More Customized UI (Optional)
For a more customized payment UI, you can use Stripe's Payment Elements:
Checkout
Processing...
{{ error }}
Step 12: Set Up a Payment Confirmation Page
Create a payment confirmation page to handle the return URL from Stripe:
Verifying payment...
Payment Failed
{{ error }}
Payment Successful!
Thank you for your purchase.
Amount: {{ formatAmount(paymentIntent.amount) }}
Payment ID: {{ paymentIntent.id }}
Status: {{ paymentIntent.status }}
Step 13: Set Up Router for the Confirmation Page
If you're using Vue Router, set it up to handle the payment confirmation page:
// src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
import PaymentConfirmation from '../views/PaymentConfirmation.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/payment-confirmation',
name: 'PaymentConfirmation',
component: PaymentConfirmation
}
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE\_URL,
routes
});
export default router;
Step 14: Testing Your Integration
To test your Stripe integration:
Use any future expiration date and any 3-digit CVC
For postal code, use any valid postal code format, like "12345"
Step 15: Deploy to Production
When ready for production:
Conclusion
You've now successfully integrated Stripe payments into your Vue.js application! This integration allows you to securely accept payments with minimal effort, leveraging Stripe's robust payment infrastructure. Remember to follow best practices for payment security, always process actual payments on the server-side, and implement proper error handling to provide a smooth user experience.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.