INFO Security and Administration

Integrating Payment Gateways with Angular and Stripe

As more and more businesses move online, having a seamless and secure payment process is becoming increasingly important. Integrating payment gateways into your web application can be a daunting task, but with the help of Angular and Stripe, it can be made relatively simple.

In this tutorial, we will cover the steps involved in integrating Stripe as a payment gateway into an Angular web application.

Prerequisites

Before we begin, make sure you have the following:

  • A Stripe account. If you don’t have one, you can sign up for free at https://stripe.com/
  • An Angular project set up and running.

Step 1: Install the Stripe API

The first step is to install the Stripe API library in your Angular project. You can do this by running the following command in your terminal:


npm install --save @stripe/stripe-js

This will install the Stripe API and add it to your project’s dependencies.

Step 2: Create a Stripe Service

Next, we need to create a service that will interact with the Stripe API. In Angular, services are used to encapsulate reusable functionality.

Create a new file called stripe.service.ts in your project’s src/app directory, and add the following code:


import { Injectable } from '@angular/core';
import { Stripe } from '@stripe/stripe-js';

@Injectable({
  providedIn: 'root'
})
export class StripeService {
  private stripePromise: Promise<Stripe>;

  constructor() {
    this.stripePromise = window['Stripe']('YOUR_STRIPE_PUBLIC_KEY');
  }

  getStripe(): Promise<Stripe> {
    return this.stripePromise;
  }
}

In this code, we create a new StripeService and define a stripePromise variable, which is a Promise that resolves to a Stripe object. We also create a getStripe() method that returns the stripePromise.

Note that you will need to replace YOUR_STRIPE_PUBLIC_KEY with your own Stripe public key.

Step 3: Create a Payment Component

Next, we need to create a component that will handle the payment process. Create a new file called payment.component.ts in your project’s src/app directory, and add the following code:


import { Component } from '@angular/core';
import { StripeService } from './stripe.service';

@Component({
  selector: 'app-payment',
  templateUrl: './payment.component.html',
})
export class PaymentComponent {
  constructor(private stripeService: StripeService) {}

  async handlePaymentClick() {
    const stripe = await this.stripeService.getStripe();

    // Call your server to create the Checkout Session
    const sessionId = await fetch('/create-checkout-session', {
      method: 'POST',
    }).then(function (response) {
      return response.json();
    });

    // When the customer clicks on the button, redirect them to Checkout
    const result = await stripe.redirectToCheckout({
      sessionId: sessionId,
    });

    if (result.error) {
      console.error(result.error);
    }
  }
}

In this code, we create a new PaymentComponent and define a handlePaymentClick() method that is called when the user clicks on the payment button. In this method, we get a reference to the Stripe API by calling the getStripe() method from our StripeService.

We then call our server to create a new Checkout Session, and retrieve the sessionId from the server’s response. Finally, we redirect the user to the Stripe checkout page using the redirectToCheckout() method, passing in the sessionId.

Note that in this code, we assume that you have already set up a server that can create a

Checkout Session when it receives a POST request to /create-checkout-session. If you haven’t done this yet, you will need to set up a server that can handle this request and return the sessionId.

Step 4: Create the Payment Template

Now that we have created the component logic, we need to create the template that will display the payment form. Create a new file called payment.component.html in your project’s src/app directory, and add the following code:


<button (click)="handlePaymentClick()">Pay with Stripe</button>

In this code, we simply create a button that will call the handlePaymentClick() method when clicked.

Step 5: Add the Payment Component to Your App

Now that we have created the PaymentComponent, we need to add it to our app. Open your app.module.ts file, and add the following code:


import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { PaymentComponent } from './payment.component';
import { StripeService } from './stripe.service';

@NgModule({
  declarations: [AppComponent, PaymentComponent],
  imports: [BrowserModule],
  providers: [StripeService],
  bootstrap: [AppComponent],
})
export class AppModule {}

In this code, we add PaymentComponent to the declarations array, and StripeService to the providers array. We also import PaymentComponent and StripeService at the top of the file.

Step 6: Test the Payment Process

Now that we have set up our payment component, we need to test the payment process. To do this, start your Angular app by running the following command in your terminal:


ng serve

Then navigate to http://localhost:4200/payment in your browser. You should see a “Pay with Stripe” button. Click the button to initiate the payment process. If everything is set up correctly, you should be redirected to the Stripe checkout page where you can complete the payment process.

Sum up

In this tutorial, we have covered the steps involved in integrating Stripe as a payment gateway into an Angular web application. We created a StripeService to interact with the Stripe API, a PaymentComponent to handle the payment process, and a template to display the payment form. By following these steps, you can easily integrate Stripe into your own Angular web application and provide a seamless and secure payment process for your users.

You may also like...