Angular's Integration with PayPal for Shipping Costs

I am facing an issue with my e-commerce website where the receipt only displays the total payment of the items purchased. I have searched for an SDK that supports Angular or TypeScript PayPal integration, but could only find one for JavaScript which did not work for my Angular code. How can I add a shipping cost, for example $5.00, to the Angular PayPal integration?

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { CartService } from 'src/app/service/service.service';
import { HttpClient } from '@angular/common/http';
import { IPayPalConfig, ICreateOrderRequest, IOnShippingChangeData } from 'ngx-paypal';
import emailjs, { EmailJSResponseStatus, init } from '@emailjs/browser';
init("user_66nwzX6xZ5j1WCaDKBM51");

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.scss']
})
export class CartComponent implements OnInit {

  public payPalConfig ? : IPayPalConfig;
  public products : any = [];
  public grandTotal !: number;
  paymentHandler: any = null;
  showSuccess: boolean | undefined;
  
  constructor(private cartService : CartService, private http: HttpClient) { }

  ngOnInit(): void {
    this.cartService.getProducts()
    .subscribe(res=>{
      this.products = res;
      this.grandTotal = this.cartService.getTotalPrice();
    })
  }

  totalItemPayment(quantity: number, price: number){
    return quantity * price;
  }

  removeItem(item: any){
    this.cartService.removeCartItem(item);
  }

  emptycart(){
    this.cartService.removeAllCart();
  }

  checkout(){
    const myValue: any = this.grandTotal.toFixed(2);
    console.log("total price (value) = " + myValue);
    let text = JSON.stringify(this.cartService.cartItemList);
    const jsonObj = JSON.parse(text);
    for(var i = 0; i < jsonObj.length; i++)
      {
        const description = "quantity: " + jsonObj[i]['quantity'] + "\ntitle: " + jsonObj[i]['title'] + "\n\n";
      }
    
    const title: string[] = [];

    for(var i = 0; i < jsonObj.length; i++){
      title.push(jsonObj[i]['quantity'] + " " + jsonObj[i]['title']);
    }
    
    var moo = JSON.stringify(title);
    console.log(moo);
    
    this.payPalConfig = {
      currency: 'USD',
      clientId: "[type in your client-id]",
      //@ts-ignore
      createOrderOnClient: (data) => <ICreateOrderRequest>{
        intent: 'CAPTURE',
        purchase_units: [{
          amount: {
            currency_code: 'USD',
            value: myValue,
            breakdown: {
              item_total: {
                currency_code: 'USD',
                value: myValue
              },
              shipping: {
                currency_code: 'USD',
                value: '5.00'
              }
            },
          },
          description: moo,
        }]
      },
      advanced: {
        commit: 'true'
      },
      style: {
        label: 'paypal',
        layout: 'vertical'
      },
      onApprove: (data, actions) => {
        console.log('onApprove - transaction was approved, but not authorized', data, actions);
        actions.order.get().then((details: any) => {
          console.log('onApprove - you can get full order details inside onApprove: ', details);
        });
      },
      onClientAuthorization: (data) => {
        console.log('onClientAuthorization - you should probably inform your server about completed transaction at this point', data);
        this.showSuccess = true;
       // empties cart after user purchases
        this.emptycart();
      },
      onCancel: (data, actions) => {
        console.log('OnCancel', data, actions);
      },
      onError: err => {
        console.log('OnError', err);
      },
      onClick: (data, actions) => {
        console.log('onClick', data, actions);
      },
      onShippingChange: (data, actions) => {
        return actions.resolve() // or .reject()
      },
    };

  }
}

Answer №1

I'm not very experienced with the API, but after reviewing the documentation and example (https://www.npmjs.com/package/ngx-paypal), I was wondering if including an items sub array in your purchase-units would result in the desired outcome?

....
items: [{
                        name: 'Enterprise Subscription',
                        quantity: '1',
                        category: 'DIGITAL_GOODS',
                        unit_amount: {
                            currency_code: 'EUR',
                            value: '9.99',
                        },
                    }]
....

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bring in an Angular Component into a different Component by stating the name of the component as an input parameter

In my project, I am looking to develop an angle component made up of multiple sub-components. The end goal is to construct a versatile tree component with nodes that cater to different data types. Each data type in the tree component will import specific s ...

"NameService is not provided in Angular, please check your module

I've been struggling with loading a class into my Angular component. I've spent quite some time trying to figure out the solution, even attempting to consolidate everything into a single file. Here is what I have: Application.ts /// <referenc ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

Utilize Ionic for mobile development - Demonstrating the process of displaying a save prompt on Android devices

I am trying to find a way to export JSON as a file using Ionic running as an APK on Android. While I can easily do this when using a browser on PC, it seems impossible on Android as I am unable to download the file. I have tried using "a link" and ngx-fil ...

Using a click event to target the next div and apply a CSS class using Typescript

I am trying to create a Typescript function that will locate the next div and apply a CSS class to it. Here is what I have attempted: <ul> <li><a href="#" onclick="toggle()">Item 1</a></li> <div class="content hide ...

Troubleshooting a useContext error in Next.js with TypeScript

I've been working on an app using next.js for the frontend, and I encountered an issue while trying to stringify an object. Here's a snippet of the error message: Argument of type '{ auth: dataObject; }' is not assignable to parameter o ...

Looking for a TypeScript annotation that allows accessing an object property using a variable

When working with plain JavaScript, we have the ability to access an object's property value using a variable. For example, this is permitted: let obj = { a: 100, b: 'Need help with TypeScript', c: new Date() }; let prop = 'b'; c ...

Exploring generic types using recursive inference

The scenario: export type SchemaOne<T> = | Entity<T> | SchemaObjectOne<T>; export interface SchemaObjectOne<T> { [key: string]: SchemaOne<T>; } export type SchemaOf<T> = T extends SchemaOne<infer R> ? R : nev ...

Changing Observable to Promise in Angular 2

Q) What is the best way to convert an observable into a promise for easy handling with .then(...)? The code snippet below showcases my current method that I am looking to transform into a promise: this._APIService.getAssetTypes().subscribe( assetty ...

Utilize a single component across various instances for enhanced efficiency

After thorough research, I couldn't find a solution to my problem despite similar questions being asked. I've developed an angular component for styled radio buttons and need to use it multiple times on different instances. To get a better unde ...

Troubleshooting Node.js TypeScript breakpoints in Visual Studio Code

I've attempted multiple solutions, but none seem to be working for me. Although the code is running, I'm having trouble setting breakpoints and debugging it. Can you offer any assistance? Below is the configuration script I've tried in VSCo ...

Exploring Angular: Looping through an Array of Objects

How can I extract and display values from a JSON object in a loop without using the keyValue pipe? Specifically, I am trying to access the "student2" data and display the name associated with it. Any suggestions on how to achieve this? Thank you for any h ...

Issue occurred while trying to set the value from an API call response in the componentDidMount lifecycle method

There is a boolean variable disableButton: boolean; that needs to be set based on the response received from this API call: async getDocStatus(policy: string): Promise<boolean> { return await ApiService.getData(this.apiUrl + policy + this.myEndpo ...

Why did the homepage load faster than the app.component.ts file?

I am facing an issue where the homepage is loading before app.component.ts, causing problems with certain providers not working properly due to import processes not being fully completed. Despite trying to lazy load the homepage, the console.log still sho ...

Having difficulty troubleshooting the /app router application on version 13.4.x

Having trouble debugging a server-side process in my Next.js app that uses the /app router. To reproduce the issue, simply create a new Next.js app with npx create-next-app and select the app router option. I've attempted to attach a debugger to the ...

Encountering issues with installing Angular using npm due to errors

When I run npm install, I encounter errors. Though I can get it to work by using npm install --force, I prefer not to rely on the force flag. After reading through the errors, it seems like there might be a version compatibility issue, but I'm having ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

Utilizing Emotion CSS to incorporate images into buttons

I'm trying to add some style to two buttons, Up and Down, by using emotion CSS but I'm having trouble. Currently, I typically style my elements within a function. Is there a way for me to accomplish this with emotion CSS? I checked out but still ...

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...