/stripe-guides

How to use Stripe with Vue.js?

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.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to use Stripe with Vue.js?

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:

  1. Go to https://stripe.com and sign up for an account
  2. Navigate to the Developers section
  3. Find your API keys (both publishable and secret)
  4. Make note of these keys as we'll need them for our implementation

 

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:







 

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:







 

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:







 

Step 12: Set Up a Payment Confirmation Page

 

Create a payment confirmation page to handle the return URL from Stripe:







 

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:

  1. Use Stripe's test card numbers:
  • 4242 4242 4242 4242 (successful payment)
  • 4000 0000 0000 0002 (declined payment)
  • 4000 0000 0000 3220 (3D Secure authentication required)
  1. Use any future expiration date and any 3-digit CVC

  2. For postal code, use any valid postal code format, like "12345"

 

Step 15: Deploy to Production

 

When ready for production:

  1. Update your environment variables to use your production Stripe keys
  2. Ensure your backend has proper error handling and logging
  3. Implement appropriate security measures
  4. Set up Stripe webhooks for production
  5. Test the entire payment flow in your production environment

 

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.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022