The shopping cart functionality is essential for any e-commerce website. In this tutorial, we will learn how to build a shopping cart using Angular and integrate it with PayPal for seamless payment processing.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of Angular framework and JavaScript. Make sure you have the following installed on your system:
- Node.js
- Angular CLI
Setting Up the Project
Let’s start by setting up a new Angular project:
- Open your terminal and navigate to the directory where you want to create the project.
- Run the following command to create a new Angular project:
ng new shopping-cart
- Change into the project directory:
cd shopping-cart
- Install the required packages by running the following command:
npm install
Now that we have set up the project, let’s move on to building the shopping cart functionality.
Building the Shopping Cart
- Create a new component for the shopping cart:
ng generate component shopping-cart
- Open the
app.component.html
file and update it to include the shopping cart component:
<app-shopping-cart></app-shopping-cart>
- Open the
shopping-cart.component.html
file and add the following HTML markup for the shopping cart:
<h2>Shopping Cart</h2>
<div *ngIf="cartItems.length > 0; else emptyCart">
<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of cartItems">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.price * item.quantity }}</td>
<td>
<button (click)="removeFromCart(item)">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
<ng-template #emptyCart>
<p>Your cart is empty.</p>
</ng-template>
<p>Total: {{ getTotal() }}</p>
<button (click)="checkout()">Checkout</button>
- Open the
shopping-cart.component.ts
file and add the following code:
import { Component, OnInit } from '@angular/core';
import { CartService } from '../cart.service';
@Component({
selector: 'app-shopping-cart',
templateUrl: './shopping-cart.component.html',
styleUrls: ['./shopping-cart.component.css']
})
export class ShoppingCartComponent implements OnInit {
cartItems: any[] = [];
constructor(private cartService: CartService) { }
ngOnInit() {
this.cartItems = this.cartService.getItems();
}
removeFromCart(item: any) {
this.cartService.removeFromCart(item);
this.cartItems = this.cartService.getItems();
}
getTotal() {
let total = 0;
for (const item of this.cartItems) {
total += item.price * item.quantity;
}
return total;
}
checkout() {
// Redirect to PayPal for checkout
}
}
- Create a new service named
cart.service.ts
to handle cart operations:
ng generate service cart
- Open the
cart.service.ts
file and add the following code:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CartService {
items: any[] = [];
constructor() { }
addToCart(item: any) {
const existingItem = this.items.find(i => i.id === item.id);
if (existingItem) {
existingItem.quantity++;
} else {
this.items.push({ ...item, quantity: 1 });
}
}
getItems() {
return this.items;
}
removeFromCart(item: any) {
const index = this.items.findIndex(i => i.id === item.id);
if (index !== -1) {
this.items.splice(index, 1);
}
}
clearCart() {
this.items = [];
}
}
Now we have a basic shopping cart functionality in place. Let’s integrate it with PayPal for payment processing.
Integrating with PayPal
- Sign up for a PayPal Business account if you don’t have one already.
-
In the PayPal developer dashboard, create a new REST API app.
-
Once the app is created, you will be provided with a client ID. Make note of this as we will need it later.
-
Install the PayPal JavaScript SDK by running the following command:
npm install @paypal/react-paypal-js
- In the
shopping-cart.component.ts
file, add the following code to import the PayPal JavaScript SDK:
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
- Replace the
checkout()
function in theShoppingCartComponent
class with the following code:
checkout() {
// Create a new PayPal order
fetch('/api/create-order', {
method: 'POST',
headers:
{
'Content-Type': 'application/json'
},
body: JSON.stringify({
items: this.cartItems,
total: this.getTotal()
})
})
.then(res => res.json())
.then(data => {
// Render PayPal buttons with the order details
this.renderPayPalButtons(data.orderId);
})
.catch(error => {
console.error('Error:', error);
});
}
renderPayPalButtons(orderId: string) {
const paypalStyle = {
layout: 'horizontal',
color: 'silver',
shape: 'rect'
};
const paypalConfig = {
clientId: 'YOUR_PAYPAL_CLIENT_ID',
currency: 'USD',
createOrder: (data: any, actions: any) => {
return actions.order.create({
purchase_units: [
{
amount: {
currency_code: 'USD',
value: this.getTotal()
}
}
]
});
},
onApprove: (data: any, actions: any) => {
return actions.order.capture().then((details: any) => {
// Handle successful payment
console.log("Payment completed. Transaction details:", details);
// Clear the cart
this.cartService.clearCart();
this.cartItems = [];
});
}
};
return (
<PayPalScriptProvider options={{ 'client-id': paypalConfig.clientId }}>
<PayPalButtons style={paypalStyle} createOrder={paypalConfig.createOrder} onApprove={paypalConfig.onApprove} />
</PayPalScriptProvider>
);
}
-
Replace
'YOUR_PAYPAL_CLIENT_ID'
with your PayPal client ID obtained in step 3. -
Create a new server endpoint to create a PayPal order. In the root of the project, create a new file named
server.js
and add the following code:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const paypal = require('@paypal/checkout-server-sdk');
// Set up the PayPal environment
const clientId = 'YOUR_PAYPAL_CLIENT_ID';
const clientSecret = 'YOUR_PAYPAL_CLIENT_SECRET';
const environment = new paypal.core.SandboxEnvironment(clientId, clientSecret);
const client = new paypal.core.PayPalHttpClient(environment);
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/api/create-order', (req, res) => {
const request = new paypal.orders.OrdersCreateRequest();
request.prefer("return=representation");
request.requestBody({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "USD",
value: req.body.total
}
}
]
});
client.execute(request)
.then(response => {
res.json({ orderId: response.result.id });
})
.catch(error => {
res.status(500).json({ error: error.message });
});
});
app.listen(5000, () => {
console.log('Server is running on http://localhost:5000');
});
-
Replace
'YOUR_PAYPAL_CLIENT_ID'
with your PayPal client ID obtained in step 3. -
Install the required dependencies for the server by running the following commands:
npm install express cors body-parser @paypal/checkout-server-sdk
- Start the server by running the following command:
node server.js
Now, when you click on the “Checkout” button in the shopping cart, it will create a new order in PayPal and redirect you to the PayPal payment page. After completing the payment, the cart will be cleared.
Conclusion
In this tutorial, we have learned how to build a shopping cart using Angular and integrate it with PayPal for payment processing. We have covered the basic functionality of adding items to the cart, displaying the cart items, removing items from the cart, calculating the total, and redirecting to PayPal for checkout. You can further enhance this shopping cart by adding features like user authentication, order history, and order confirmation emails.