{"id":4114,"date":"2023-11-04T23:14:04","date_gmt":"2023-11-04T23:14:04","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-shopping-cart-with-angular-and-paypal\/"},"modified":"2023-11-05T05:47:59","modified_gmt":"2023-11-05T05:47:59","slug":"how-to-build-a-shopping-cart-with-angular-and-paypal","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-shopping-cart-with-angular-and-paypal\/","title":{"rendered":"How to Build a Shopping Cart with Angular and PayPal"},"content":{"rendered":"
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.<\/p>\n
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:<\/p>\n
Let’s start by setting up a new Angular project:<\/p>\n
ng new shopping-cart\n<\/code><\/pre>\n\n- Change into the project directory:<\/li>\n<\/ol>\n
cd shopping-cart\n<\/code><\/pre>\n\n- Install the required packages by running the following command:<\/li>\n<\/ol>\n
npm install\n<\/code><\/pre>\nNow that we have set up the project, let’s move on to building the shopping cart functionality.<\/p>\n
Building the Shopping Cart<\/h2>\n\n- Create a new component for the shopping cart:<\/li>\n<\/ol>\n
ng generate component shopping-cart\n<\/code><\/pre>\n\n- Open the
app.component.html<\/code> file and update it to include the shopping cart component:<\/li>\n<\/ol>\n<app-shopping-cart><\/app-shopping-cart>\n<\/code><\/pre>\n\n- Open the
shopping-cart.component.html<\/code> file and add the following HTML markup for the shopping cart:<\/li>\n<\/ol>\n<h2>Shopping Cart<\/h2>\n\n<div *ngIf=\"cartItems.length > 0; else emptyCart\">\n <table>\n <thead>\n <tr>\n <th>Product<\/th>\n <th>Price<\/th>\n <th>Quantity<\/th>\n <th>Total<\/th>\n <th>Actions<\/th>\n <\/tr>\n <\/thead>\n <tbody>\n <tr *ngFor=\"let item of cartItems\">\n <td>{{ item.name }}<\/td>\n <td>{{ item.price }}<\/td>\n <td>{{ item.quantity }}<\/td>\n <td>{{ item.price * item.quantity }}<\/td>\n <td>\n <button (click)=\"removeFromCart(item)\">Remove<\/button>\n <\/td>\n <\/tr>\n <\/tbody>\n <\/table>\n<\/div>\n\n<ng-template #emptyCart>\n <p>Your cart is empty.<\/p>\n<\/ng-template>\n\n<p>Total: {{ getTotal() }}<\/p>\n\n<button (click)=\"checkout()\">Checkout<\/button>\n<\/code><\/pre>\n\n- Open the
shopping-cart.component.ts<\/code> file and add the following code:<\/li>\n<\/ol>\nimport { Component, OnInit } from '@angular\/core';\nimport { CartService } from '..\/cart.service';\n\n@Component({\n selector: 'app-shopping-cart',\n templateUrl: '.\/shopping-cart.component.html',\n styleUrls: ['.\/shopping-cart.component.css']\n})\nexport class ShoppingCartComponent implements OnInit {\n cartItems: any[] = [];\n\n constructor(private cartService: CartService) { }\n\n ngOnInit() {\n this.cartItems = this.cartService.getItems();\n }\n\n removeFromCart(item: any) {\n this.cartService.removeFromCart(item);\n this.cartItems = this.cartService.getItems();\n }\n\n getTotal() {\n let total = 0;\n for (const item of this.cartItems) {\n total += item.price * item.quantity;\n }\n return total;\n }\n\n checkout() {\n \/\/ Redirect to PayPal for checkout\n }\n}\n<\/code><\/pre>\n\n- Create a new service named
cart.service.ts<\/code> to handle cart operations:<\/li>\n<\/ol>\nng generate service cart\n<\/code><\/pre>\n\n- Open the
cart.service.ts<\/code> file and add the following code:<\/li>\n<\/ol>\nimport { Injectable } from '@angular\/core';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class CartService {\n items: any[] = [];\n\n constructor() { }\n\n addToCart(item: any) {\n const existingItem = this.items.find(i => i.id === item.id);\n if (existingItem) {\n existingItem.quantity++;\n } else {\n this.items.push({ ...item, quantity: 1 });\n }\n }\n\n getItems() {\n return this.items;\n }\n\n removeFromCart(item: any) {\n const index = this.items.findIndex(i => i.id === item.id);\n if (index !== -1) {\n this.items.splice(index, 1);\n }\n }\n\n clearCart() {\n this.items = [];\n }\n}\n<\/code><\/pre>\nNow we have a basic shopping cart functionality in place. Let’s integrate it with PayPal for payment processing.<\/p>\n
Integrating with PayPal<\/h2>\n\n- Sign up for a PayPal Business account if you don’t have one already.<\/p>\n<\/li>\n
- \n
In the PayPal developer dashboard, create a new REST API app.<\/p>\n<\/li>\n
- \n
Once the app is created, you will be provided with a client ID. Make note of this as we will need it later.<\/p>\n<\/li>\n
- \n
Install the PayPal JavaScript SDK by running the following command:<\/p>\n<\/li>\n<\/ol>\n
npm install @paypal\/react-paypal-js\n<\/code><\/pre>\n\n- In the
shopping-cart.component.ts<\/code> file, add the following code to import the PayPal JavaScript SDK:<\/li>\n<\/ol>\nimport { PayPalScriptProvider, PayPalButtons } from \"@paypal\/react-paypal-js\";\n<\/code><\/pre>\n\n- Replace the
checkout()<\/code> function in the ShoppingCartComponent<\/code> class with the following code:<\/li>\n<\/ol>\ncheckout() {\n \/\/ Create a new PayPal order\n fetch('\/api\/create-order', {\n method: 'POST',\n headers:\n {\n 'Content-Type': 'application\/json'\n },\n body: JSON.stringify({\n items: this.cartItems,\n total: this.getTotal()\n })\n })\n .then(res => res.json())\n .then(data => {\n \/\/ Render PayPal buttons with the order details\n this.renderPayPalButtons(data.orderId);\n })\n .catch(error => {\n console.error('Error:', error);\n });\n}\n\nrenderPayPalButtons(orderId: string) {\n const paypalStyle = {\n layout: 'horizontal',\n color: 'silver',\n shape: 'rect'\n };\n\n const paypalConfig = {\n clientId: 'YOUR_PAYPAL_CLIENT_ID',\n currency: 'USD',\n createOrder: (data: any, actions: any) => {\n return actions.order.create({\n purchase_units: [\n {\n amount: {\n currency_code: 'USD',\n value: this.getTotal()\n }\n }\n ]\n });\n },\n onApprove: (data: any, actions: any) => {\n return actions.order.capture().then((details: any) => {\n \/\/ Handle successful payment\n console.log(\"Payment completed. Transaction details:\", details);\n\n \/\/ Clear the cart\n this.cartService.clearCart();\n this.cartItems = [];\n });\n }\n };\n\n return (\n <PayPalScriptProvider options={{ 'client-id': paypalConfig.clientId }}>\n <PayPalButtons style={paypalStyle} createOrder={paypalConfig.createOrder} onApprove={paypalConfig.onApprove} \/>\n <\/PayPalScriptProvider>\n );\n}\n<\/code><\/pre>\n\n- \n
Replace 'YOUR_PAYPAL_CLIENT_ID'<\/code> with your PayPal client ID obtained in step 3.<\/p>\n<\/li>\n- \n
Create a new server endpoint to create a PayPal order. In the root of the project, create a new file named server.js<\/code> and add the following code:<\/p>\n<\/li>\n<\/ol>\nconst express = require('express');\nconst app = express();\nconst cors = require('cors');\nconst bodyParser = require('body-parser');\nconst paypal = require('@paypal\/checkout-server-sdk');\n\n\/\/ Set up the PayPal environment\nconst clientId = 'YOUR_PAYPAL_CLIENT_ID';\nconst clientSecret = 'YOUR_PAYPAL_CLIENT_SECRET';\nconst environment = new paypal.core.SandboxEnvironment(clientId, clientSecret);\nconst client = new paypal.core.PayPalHttpClient(environment);\n\napp.use(cors());\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\n\napp.post('\/api\/create-order', (req, res) => {\n const request = new paypal.orders.OrdersCreateRequest();\n request.prefer(\"return=representation\");\n request.requestBody({\n intent: \"CAPTURE\",\n purchase_units: [\n {\n amount: {\n currency_code: \"USD\",\n value: req.body.total\n }\n }\n ]\n });\n\n client.execute(request)\n .then(response => {\n res.json({ orderId: response.result.id });\n })\n .catch(error => {\n res.status(500).json({ error: error.message });\n });\n});\n\napp.listen(5000, () => {\n console.log('Server is running on http:\/\/localhost:5000');\n});\n<\/code><\/pre>\n\n- \n
Replace 'YOUR_PAYPAL_CLIENT_ID'<\/code> with your PayPal client ID obtained in step 3.<\/p>\n<\/li>\n- \n
Install the required dependencies for the server by running the following commands:<\/p>\n<\/li>\n<\/ol>\n
npm install express cors body-parser @paypal\/checkout-server-sdk\n<\/code><\/pre>\n\n- Start the server by running the following command:<\/li>\n<\/ol>\n
node server.js\n<\/code><\/pre>\nNow, 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.<\/p>\n
Conclusion<\/h2>\n
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.<\/p>\n","protected":false},"excerpt":{"rendered":"
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 Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[357,1337,599,46,1338,597,1336,1341,1339,1340,471,49,237,594],"yoast_head":"\nHow to Build a Shopping Cart with Angular and PayPal - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n