Integrate Stripe Elements in Angular?

Krunal Shah

Feb 14, 2020 | 4 min read

How Stripe Elements work for the Web?

  • Stripe.Js is our foundational JavaScript library for building payment flows.
  • The primary integration path through Stripe.js is with Elements, which enables you to collect sensitive payment information using customizable UI components.
  • With Stripe.js, you can also tokenize sensitive information, integrate with Checkout, and handle 3D Secure authentication.

What is Stripe Elements?

Stripe Elements is a set of prebuilt UI components, like inputs and buttons, for building your checkout flow.

It’s available as a feature of Stripe.js.

Stripe.js tokenize the sensitive information within an Element without ever having it touch your server.

Elements includes features like:

  • Formatting card information automatically as it’s entered
  • Translating placeholders into your customer’s preferred language
  • Using responsive design to fit the width of your customer’s screen or mobile device
  • Customizing the styling to match the look and feel of your checkout flow

Prerequisites

  • Node installed on your machine
  • NPM installed on your machine
  • Basic Knowledge of JavaScript
  • Installing Angular CLI 8 : npm install -g @angular/cli
  • Creating your Angular 8 Project : ng new angular-example
  • Creating Components : ng g c payment-components
  • Run on local Server on http://localhost:4200 : ng serve

Steps to Integrate Stripe Elements in Angular 8

  • Initial setup of Elements
  • Create payment form with Stripe Element
  • Customize style and formatting
  • Handle error and validation of payment form
  • Create Token for security on form submit
  • Pass secure token in API for checkout process

Step 1: Initial setup of Elements

Include the following script in the head section on every page on your site. This script must always load directly from js.stripe.com to remain PCI compliant.

You can’t include the script in a bundle or host a copy of it yourself.

Add bellow stript in index.html file :

Step 2: Convert your existing payment form

To use Elements, you create empty DOM elements (containers) instead of directly using DOM input's. Elements inserts a Stripe-hosted UI component within your container.

Migrating to Elements allows you to make use of the card Element.

This flexible UI component simplifies your form by minimizing the number of fields you need, requiring much less markup.

Add bellow code in payment-component.html file :

<form action="/charge" method="post" id="payment-form">
    <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>

    <input type="submit" class="submit" value="Submit Payment">
</form>

Next, initialize the Stripe client by providing your publishable API key, and create an instance of Elements.

Add bellow code in payment-component.ts file :

var stripe = Stripe('<<YOUR-PUBLISHABLE-API-KEY>>');
var elements = stripe.elements();

You can now create a card Element and add it to your page using the mount() method.

var card = elements.create('card');

// Add an instance of the card UI component into the `card-element` <div>
card.mount('#card-element');

Step 3: Customize style and formatting

Card elements can be customized to fit perfectly within your checkout page. For instance, you can make sure that the font is styled correctly by providing some additional options when creating the component:

Add bellow code in payment-component.ts file :

// Create an style object which passes when card element is initialized
var styleCard =  {
  'style': {
    'base': {
      'fontFamily': 'Arial, sans-serif',
      'fontSize': '8px',
      'color': '#C1C7CD',
    },
    'Invalid': {  'color': 'red', },
  }
});
// Create an instance of the card UI component
var card = elements.create('card', styleCard);
// Remove Zip-code in card UI component
var card = elements.create('card', { hidePostalCode: true, style: styleCard });

Step 4: Handle events and errors

Card Elements include real-time input validation that helps facilitate your users’ checkout flow, increasing conversion.

Elements also provide specific information about validation errors in real-time, helping you communicate them to your users.

Add bellow code in payment-component.ts file :

card.addEventListener('change', function(event) {
  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
  }
});

Step 5: Create Token for security on form submit

Pass the createToken() method a Stripe Element as its first argument to generate a token for payment checkout.

Add bellow code in payment-component.ts file :

function createToken() {
  stripe.createToken(card).then(function(result) {
    if (result.error) {
      // Inform the user if there was an error
      var errorElement = document.getElementById('card-errors');
      errorElement.textContent = result.error.message;
    } else {
      // Send the token to your server
      stripeTokenHandler(result.token);
    }
  });
};

// Create a token when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(e) {
  e.preventDefault();
  createToken();
});

Step 6: Pass secure token in API for the checkout process

By using Http, call the Backend API and pass the token with the amount for the checkout process.

Conclusion

  • Here we define how Stripe Element has been integrated in angular 8
  • It provides style to card element as per user requirements
  • It provides validation error if card details are not valid
  • It provides security to card details secure when a backend call is established for the checkout process.

If user does not need Zip-code , then he can remove it by passing bellow code at time of card element has been initialized : bellow code at time of card element has been initialized:

· · · ·

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.

Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.