Payment in Angular Using Stripe

Mobina Khalilzade
2 min readJul 27, 2023

Intro:

We intend to build a payment solution using Stripe in an Angular application.

Problem:

I was asked to build a checkout page for a payment in our application written in Angular. After doing some research and googling, I found Stripe as the best solution that would work. I started to read the Stripe documentation but the samples are only targeted to the pure JS or React. As a result, I had to come up with a solution and decided to write this article for whomever wants to use Stripe in Angular. Let’s get started!

You can find the Stripe documentation by clicking here.

Solution

I have a component called checkout. First of all, in the checkout.component.ts, I implement the ngOnInit() and invoke Stripe inside it:

In this piece of code the Stripe script is injected in the document. Inside the script.onload you should put the stripe key (See here). I put the key inside the environment file and call it from there.

Here is checkout.component.html. When the “Pay” button is clicked by the user, it calls the preparePayment() method.

In this method, the payment id should be sent to the server. And then the server sends back a client secret as a response. After that initialize() method is called.

Here the initialize() method loads the Stripe UI in the HTML. You can set your configurations for the appearance or the other options. In line 7, the client secret and appearance have to be set.

Next, in the HTML, a piece of code like below has to be written. It shows the payment form inside the first ng-container (I make *ngIf=”payment.openStripe” TRUE to show the form after initialize() method). When the payment is completed, another UI is shown to the user like the second ng-container:

Now the user sees something like this:

For the testing purposes you can enter the card number as “4242 4242 4242 4242” and anything arbitrary for the other inputs. When the “Pay” button is clicked, the makePayment() method is called. In this code the payment is finalized and in the confirmParams, the URL, where user should go after the payment completion, should be set. In the return_url, I put the domain of our site for the production and for the development environment you can set it as “http://localhost:4200/”. Finally, show a toast with proper message.

That's it! Now you have a nice payment in your Angular application using Stripe.

Happy Coding!

--

--