Want some programming help? [close]

Using Stripe.js Elements with Angular

Introduction

This will cover a simple example of how to get a credit card payment source token from Stripe that you can use to associate a Stripe customer with a payment source. This is good for subscription services where you need to store the payment source to later add subscriptions to.

We will look at the process for using Stripe.js Elements to create a credit card form that will obtain the token we need.

Refer to the official Stripe.js & Elements documentation for more information.

Steps

You can follow the official Stripe.js & Elements documentation for the most part just as they are, but there are a couple things to know when using it with Angular.

The general process is like this:

  • Add the Stripe.js include to the <head> of your index.html.
  • Add the Stipe HTML form to the *.component.html file of a component
  • In the *.component.ts file declare Stripe object as external variable
  • In the *.component.ts file bind to the form submission and process with Stripe

Add the Stripe.js include

In the <head> tag of the index.html file, add the Stripe.js Elements include:

<script src="https://js.stripe.com/v3/"></script>

Add Stripe form HTML

In a *.component.html file add the payment form. For example:

<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"></div>
    <div id="card-errors" role="alert"></div>
  </div>
  <button>Add payment source</button>
</form>

Again refer to the official Stripe.js & Elements documentation for the latest code.

The CSS

You can style the form however you want, or not do any styling at all. Refer to the official Stripe.js & Elements documentation for examples of CSS you can use. Also refer to [https://stripe.dev/elements-examples/](https://stripe.dev/elements-examples/(https://stripe.dev/elements-examples/).

Here are couple CSS selectors you can use to style the primary aspects of the form if desired:

// Main form styling
.StripeElement { }

// Focused field that user has text cursor in
.StripeElement--focus { }

// A field with an error or incomplete
.StripeElement--invalid { }

Declare Stripe var as external variable

Inside the Angular component, the Stripe object is not defined, and is coming from the JavaScript include in the <head> of index.html. To address this, it must be declared as an external variable.

Do this at the top of the component file (*.component.ts), outside of the component before it is declared. Add:

// Before the component
declare var Stripe: any;

Once you have done this, you can use the Stripe.js example code pretty much as it is. Inside the ngOnInit() method you can put all the code to set up the events on the credit card field

For the official JavaScript code example refer to official Stripe.js & Elements documentation

 // ...
 // Inside the component
 // Code adapted from example at https://stripe.com/docs/stripe-js

 ngOnInit() {
    // Your Stripe public key
    const stripe = Stripe('pk_test_123456123456123456');

    // Create `card` element that will watch for updates
    // and display error messages
    const elements = stripe.elements();
    const card = elements.create('card');
    card.mount('#card-element');
    card.addEventListener('change', event => {
      const displayError = document.getElementById('card-errors');
      if (event.error) {
        displayError.textContent = event.error.message;
      } else {
        displayError.textContent = '';
      }
    });

    // Listen for form submission, process the form with Stripe,
    // and get the 
    const paymentForm = document.getElementById('payment-form');
    paymentForm.addEventListener('submit', event => {
      event.preventDefault();
      stripe.createToken(card).then(result => {
        if (result.error) {
          console.log('Error creating payment method.');
          const errorElement = document.getElementById('card-errors');
          errorElement.textContent = result.error.message;
        } else {
          // At this point, you should send the token ID
          // to your server so it can attach
          // the payment source to a customer
          console.log('Token acquired!');
          console.log(result.token);
          console.log(result.token.id);
        }
      });
    });
  }

  // ...

After you get the token from the form submission, you should send it to your backend server so it can use the payment source token to attach the payment method to a Stripe customer. Refer to https://stripe.com/docs/sources/customers for more information on Sources and Customers.

Conclusion

You should now have a better understanding of how to use Stripe.js elements from an Angular component.

References

Advertisement