← Back to all snippets
JAVASCRIPT

Client-Side Payment Integration with Stripe Elements

Securely integrate Stripe Elements into your web application for collecting payment details directly from the client, enhancing user experience and PCI compliance.

// Ensure Stripe.js is loaded in your HTML:
// <script src="https://js.stripe.com/v3/"></script>

const stripe = Stripe('pk_test_YOUR_STRIPE_PUBLISHABLE_KEY'); // Replace with your publishable key
const elements = stripe.elements();

// Create an instance of the card Element.
const card = elements.create('card', {
  style: {
    base: {
      fontSize: '16px',
      color: '#32325d',
      '::placeholder': {
        color: '#aab7c4',
      },
    },
    invalid: {
      color: '#fa755a',
      iconColor: '#fa755a',
    },
  },
});

// Add an instance of the card Element into the `card-element` div.
card.mount('#card-element');

// Handle real-time validation errors from the card Element.
card.on('change', function(event) {
  const displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
  }
});

// Handle form submission.
const form = document.getElementById('payment-form');
form.addEventListener('submit', async function(event) {
  event.preventDefault();

  const { paymentMethod, error } = await stripe.createPaymentMethod({
    type: 'card',
    card: card,
    billing_details: {
      // Collect billing details if required, e.g., name, email
      name: document.getElementById('cardholder-name').value,
      email: document.getElementById('cardholder-email').value,
    },
  });

  if (error) {
    // Display error.message in your UI.
    const displayError = document.getElementById('card-errors');
    displayError.textContent = error.message;
  } else {
    // Send paymentMethod.id to your server for further processing (e.g., charging the card)
    console.log('PaymentMethod created:', paymentMethod.id);
    
    // Example: Send to your backend
    const response = await fetch('/api/create-payment-intent', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ paymentMethodId: paymentMethod.id, amount: 1000 }), // Amount in cents
    });

    const paymentResult = await response.json();

    if (paymentResult.error) {
      alert(paymentResult.error.message);
    } else if (paymentResult.paymentIntent && paymentResult.paymentIntent.status === 'succeeded') {
      alert('Payment successful!');
      // Redirect or show success message
    } else {
      // Handle other payment intent statuses (e.g., requires_action)
      alert('Payment processing required further action or failed.');
    }
  }
});

// Example HTML structure:
// <form id="payment-form">
//   <div class="form-row">
//     <label for="cardholder-name">Cardholder Name</label>
//     <input id="cardholder-name" type="text" placeholder="Jane Doe" required />
//   </div>
//   <div class="form-row">
//     <label for="cardholder-email">Cardholder Email</label>
//     <input id="cardholder-email" type="email" placeholder="[email protected]" required />
//   </div>
//   <div class="form-row">
//     <label for="card-element">Credit or debit card</label>
//     <div id="card-element">
//       <!-- A Stripe Element will be inserted here. -->
//     </div>
//     <!-- Used to display form errors. -->
//     <div id="card-errors" role="alert"></div>
//   </div>
//   <button type="submit">Submit Payment</button>
// </form>
How it works: This JavaScript snippet shows how to integrate Stripe Elements for secure client-side payment collection. It initializes Stripe with a publishable key, creates a `card` Element for collecting credit card details, and mounts it to a designated DOM element. Upon form submission, it securely creates a `PaymentMethod` using Stripe.js and then sends the `paymentMethod.id` to a backend API for charging, ensuring PCI compliance by never handling raw card data on your server.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs