简体   繁体   中英

Pass variable to item in paypal-checkout

I started working with angular almost a whole week ago. And to make things easy I am trying to implement a paypal-checkout.

The checkout works fine, as long as I only pass the total amount. But I would like to pass several items to paypal.

I tried it this way:

    import {
      Component,
      OnInit,
      ViewChild,
      Input,
      ElementRef,
      Output,
      EventEmitter
    } from "@angular/core";

    declare var paypal;

    @Component({
      selector: "app-payme",
      templateUrl: "./payme.component.html",
      styleUrls: ["./payme.component.scss"]
    })
    export class PaymeComponent implements OnInit {
      @ViewChild("paypal", { static: true }) paypalElement: ElementRef;
      @Input() total: number;
      @Input() cart: [];

      //payCart: [];

      @Output() isPaidFor: EventEmitter<boolean> = new EventEmitter();

      paidFor = false;

      constructor() {}

      cartInConsole() {
        console.log("PayPalTotal", this.total);
      }

      declareItem() {
        let paypalItem = [];
        for (let i =0 ; i< this.cart.length; i++) {
            let currency = "EUR";
            let quantity = this.cart[i].selectedSize;
            let name = this.cart[i].name;
            let amount = this.cart[i].selectedPrice;
            console.log("DeclareFunction rennt");
            //let pushItem = {"quantity": quantity};  
            paypalItem.push({"unit_amount": {"currency_code": "EUR","value": currency, "amount": amount},"quantity": quantity,"name": name});
           console.log("Declare", paypalItem) 
            return paypalItem
          }

         console.log("StackOverFow", paypalItem )
      };


      ngOnInit() {
        console.log("PayPalCart", this.cart);
        this.declareItem();
        paypal
          .Buttons({
            createOrder: (data, actions) => {
              return actions.order.create(

                {
              purchase_units: [{
                amount: {
                    currency_code: 'EUR',
                    value: this.total,

                    }
                },
              items: this.paypalItem
            }]
            },
            onApprove: async (data, actions) => {
              const order = await actions.order.capture();
              this.paidFor = true;
              this.isPaidFor.emit(this.paidFor);
              console.log("Order", order);
            }
          })
          .render(this.paypalElement.nativeElement);
      }

    }

But all I get as a response is: items is not defined.

The console.log of my paypalItem looks okay - it seems to be an array of object, just like it should be.

But how do I get it to pass that object to item or item?

By the way: which one is it? Item or items? A few hours of googling an getting all different answers, makes you doubt anything:-)

Thanks a lot in advance!

UPDATE

I tried declaring paypalItem and then setting in the declareItem-function. Unfortunately with the same result...

The code now looks like this:

 import {
  Component,
  OnInit,
  ViewChild,
  Input,
  ElementRef,
  Output,
  EventEmitter
} from "@angular/core";

declare var paypal;

@Component({
  selector: "app-payme",
  templateUrl: "./payme.component.html",
  styleUrls: ["./payme.component.scss"]
})
export class PaymeComponent implements OnInit {
  @ViewChild("paypal", { static: true }) paypalElement: ElementRef;
  @Input() total: number;
  @Input() cart: [];
paypalItem: [];
  //payCart: [];

  @Output() isPaidFor: EventEmitter<boolean> = new EventEmitter();

  paidFor = false;

  constructor() {}

  cartInConsole() {
    console.log("PayPalTotal", this.total);
  }

  declareItem() {
    let paypalItem = [];
    for (let i =0 ; i< this.cart.length; i++) {
        let currency = "EUR";
        let quantity = this.cart[i].selectedSize;
        let name = this.cart[i].name;
        let amount = this.cart[i].selectedPrice;
        console.log("DeclareFunction rennt");
        //let pushItem = {"quantity": quantity};  
        paypalItem.push({"unit_amount": {"currency_code": "EUR","value": currency, "amount": amount},"quantity": quantity,"name": name});
       console.log("Declare", paypalItem) 
        this.paypalItem = paypalItem;
      }

     console.log("StackOverFow", paypalItem )
  };


  ngOnInit() {
    console.log("PayPalCart", this.cart);
    this.declareItem();
    paypal
      .Buttons({
        createOrder: (data, actions) => {
          return actions.order.create(

            {
          purchase_units: [{
            amount: {
                currency_code: 'EUR',
                value: this.total,

                }
            },
          items: this.paypalItem
        }]
        },
        onApprove: async (data, actions) => {
          const order = await actions.order.capture();
          this.paidFor = true;
          this.isPaidFor.emit(this.paidFor);
          console.log("Order", order);
        }
      })
      .render(this.paypalElement.nativeElement);
  }

}

Any other ideas?

One more update:

Full code is on codesandbox

Not seeing a varaible declared as paypalItem in the class. Declare a variable called paypalItem , then inside method declareItem() assign the paypalItem array to the class level paypalItem you declared before.


declareItem() {
...
this.paypalItem = paypalItem;
}

Update

It was a fault of your model binding. Paypal create order expects model with different required properties when you add items. I have added a sample model in the code. You can map your values to your model and replace it over there.

For testing, replace this code snippet over yours in the sandbox. Will work fine.

Refer this. api documentation for create (items array)

 paypal
      .Buttons({
        createOrder: (data, actions) => {
          // This function sets up the details of the transaction, including the amount and line item details.
          return actions.order.create({
            intent: "CAPTURE",
            purchase_units: [
              {
                amount: {
                  currency_code: "EUR",
                  value: "0.02",
                  breakdown: {
                    item_total: {
                      currency_code: "EUR",
                      value: "0.02"
                    }
                  }
                },
                items: [
                  {
                    name: "item1",
                    unit_amount: {
                      currency_code: "EUR",
                      value: "0.01"
                    },
                    quantity: "1"
                  },
                  {
                    name: "item2",
                    unit_amount: {
                      currency_code: "EUR",
                      value: "0.01"
                    },
                    quantity: "1"
                  }
                ]
              }
            ]
          });
        },
        onApprove: function(data, actions) {
          // This function captures the funds from the transaction.
          return actions.order.capture().then(function(details) {
            // This function shows a transaction success message to your buyer.
            alert("Transaction completed by " + details.payer.name.given_name);
          });
        }
      })
      .render(this.paypalElement.nativeElement);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM