Home > Mobile >  If I have an object of items , how do I put it in the paypal-rest-sdk items section (node.js)
If I have an object of items , how do I put it in the paypal-rest-sdk items section (node.js)

Time:12-01

For example . I have a variable called cart , when I console.log it this is what comes

Cart {
  items: {
    '1': { item: [Object], qty: 1, price: 150 },
    '2': { item: [Object], qty: 1, price: 200 }
  },
  totalQty: 2,
  totalPrice: 350,
  add: [Function (anonymous)],
  reduceByOne: [Function (anonymous)],
  increaseByOne: [Function (anonymous)],
  deleteItem: [Function (anonymous)],
  generateArray: [Function (anonymous)]
}

This is the paypal section

const create_payment_json = {
    "intent": "sale",
    "payer": {
        "payment_method": "paypal"
    },
    "redirect_urls": {
        "return_url": "http://localhost:3000/success",
        "cancel_url": "http://localhost:3000/failed"
    },
    "transactions": [{
        "item_list": {
            "items": [{
                "name": "item",
                "sku": "item",
                "price": "200.00",
                "currency": "USD",
                "quantity": 1
            }]
        },
        "amount": {
            "currency": "USD",
            "total": "200.00"
        },
        "description": "This is the payment description."
    }]
};

How do I put the items that are in the cart in the items section of the paypal so it can account for all the items. I am new to this. Is it possible to run a loop in the "item_list" object ? Any help is highly appreciated. Thank you

CodePudding user response:

This is a straightforward programming task: write a function that iterates over Cart.items and returns an items array. There are many ways to construct such a loop, or even use a mapping function. Just an example

function getItems(cart) {
    let itemsArray = [];
    for (const [idx, item] of Object.entries(cart)) {
      console.log(`${idx}: ${item}`);
      itemsArray.push({
                "name": "item name goes here", //data seems to be in item.item
                "price": item.price,
                "currency": "USD",
                "quantity": item.qty
            });
    }
    return itemsArray;
}

Then you use it...

        "item_list": {
            "items": getItems(Cart.items)
        }

Another thing to note is that your PayPal code is for the deprecated v1/payments API or checkout.js. You should be using the current v2/checkout/orders and JS SDK. See examples in Set up standard payments

  • Related