Create Customers and Process Card Payments with Tokenization in Angular
In today's digital age, online payment systems need to be both secure and efficient. One powerful approach for handling card payments securely is tokenization, which helps protect sensitive card information. By using tokenization, businesses can ensure that their customers' card details are securely processed, reducing the risk of fraud. In this article, we will explore how to create customers and process card payments using tokenization in an Angular application.
What is Tokenization in Payment Processing?
Tokenization refers to the process of replacing sensitive card information (like credit or debit card numbers) with a unique identifier, or token, that has no intrinsic value. This token can then be used for processing payments without exposing the original card details.
- Security: Tokenization reduces the risk of data breaches, as card numbers are not stored or transmitted in their raw form.
- Compliance: Tokenization is essential for meeting security standards like PCI-DSS (Payment Card Industry Data Security Standard).
- Convenience: It simplifies the process of handling recurring transactions and enables secure storage for future payments.
With tokenization, sensitive customer data is stored in a secure payment gateway, while only the token is used in your application, making the process safer and more efficient.
Steps to Implement Tokenized Payment Processing in Angular
To process card payments with tokenization in Angular, you will need a third-party payment processor (such as Stripe, PayPal, or Razorpay) that supports tokenization. This guide will use Stripe as an example, but the principles apply to most payment gateways.
Step 1: Set Up Stripe API
First, you need to set up an account with Stripe and get your API keys:
- Go to the Stripe website (https://stripe.com) and create an account.
- Once your account is created, obtain your Publishable Key and Secret Key from the API Keys section of the Stripe Dashboard.
Step 2: Install Stripe in Your Angular Project
Install the Stripe library in your Angular project:
npm install @stripe/stripe-js
npm install @angular/common @angular/http
Step 3: Create a Payment Service in Angular
Create a service in Angular to interact with the Stripe API. This service will handle customer creation and payment processing.
ng generate service payment
payment.service.ts
file and add the necessary logic:import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class PaymentService { constructor(private http: HttpClient) { } // Call backend to create a Stripe customer createCustomer(email: string): Observable<any> { return this.http.post(`${environment.apiUrl}/create-customer`, { email }); } // Call backend to create a payment token createPaymentToken(cardDetails: any): Observable<any> { return this.http.post(`${environment.apiUrl}/create-payment-token`, cardDetails); } // Call backend to process payment processPayment(token: string, amount: number): Observable<any> { return this.http.post(`${environment.apiUrl}/process-payment`, { token, amount }); } }
In this service, you have three methods:
createCustomer()
: This method creates a new customer on Stripe.createPaymentToken()
: This method creates a payment token using card details.processPayment()
: This method processes the payment using the generated token.
Step 4: Integrate Stripe Elements in Angular
Stripe Elements is a set of pre-built UI components that you can use to securely collect card information. The next step is to integrate Stripe Elements into your Angular component.
First, import Stripe and Elements in your component:
import { Component, OnInit } from '@angular/core'; import { PaymentService } from './payment.service'; import { loadStripe } from '@stripe/stripe-js'; @Component({ selector: 'app-payment', templateUrl: './payment.component.html', styleUrls: ['./payment.component.css'] }) export class PaymentComponent implements OnInit { stripe: any; elements: any; card: any; constructor(private paymentService: PaymentService) { } async ngOnInit(): Promise<void> { // Load Stripe.js this.stripe = await loadStripe('your-publishable-key-here'); // Set up Stripe Elements this.elements = this.stripe.elements(); this.card = this.elements.create('card'); this.card.mount('#card-element'); } createCustomer(email: string) { this.paymentService.createCustomer(email).subscribe(response => { // Handle customer creation response }); } processPayment() { this.stripe.createToken(this.card).then((result: any) => { if (result.error) { // Handle error console.error(result.error.message); } else { const token = result.token.id; this.paymentService.processPayment(token, 1000).subscribe(response => { // Handle payment success console.log('Payment processed successfully:', response); }, error => { // Handle payment error console.error('Error processing payment:', error); }); } }); } }
In this component, we:
-
Load Stripe.js using
loadStripe()
. - Set up the Stripe Elements to create a
card
element, which securely collects card details from the user. - Use the
createToken()
method to create a payment token, which we send to the server to process the payment.
Step 5: Create Backend API to Handle Tokenization
On the backend, you’ll need to interact with Stripe’s API to create customers, generate payment tokens, and process payments. This typically involves writing server-side code in a backend framework like Node.js, Django, or Ruby on Rails.
Here’s an example of what the backend might look like with Node.js:
const express = require('express');
const Stripe = require('stripe');
const stripe = Stripe('your-secret-key-here');
const app = express();
app.use(express.json());
// Route to create a Stripe customer
app.post('/create-customer', async (req, res) => {
const { email } = req.body;
try {
const customer = await stripe.customers.create({ email });
res.send({ customerId: customer.id });
} catch (error) {
res.status(500).send({ error: error.message });
}
});
// Route to create a payment token (tokenization)
app.post('/create-payment-token', async (req, res) => {
const { cardDetails } = req.body;
try {
const token = await stripe.tokens.create({ card: cardDetails });
res.send({ token: token.id });
} catch (error) {
res.status(500).send({ error: error.message });
}
});
// Route to process payment
app.post('/process-payment', async (req, res) => {
const { token, amount } = req.body;
try {
const charge = await stripe.charges.create({
amount,
currency: 'usd',
source: token,
});
res.send({ success: true, charge });
} catch (error) {
res.status(500).send({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
This backend code listens for requests to:
- Create a new Stripe customer.
- Create a payment token from the card details.
- Process the payment using the generated token.
Conclusion
By implementing tokenization with Stripe in your Angular application, you can securely handle customer payments without storing sensitive credit card information on your servers. This approach minimizes the risk of data breaches and ensures that your payment processing meets industry security standards like PCI-DSS.
Using Stripe Elements and the provided backend API, you can create customers, generate payment tokens, and securely process card payments, making your Angular application both efficient and secure for handling online transactions.