Using an array to fill in the items section on the JavaScript SDK

Rossco99
Contributor
Contributor

Hi there, I am currently building a website that has a store section in it and I am trying to integrate the PayPal Smart buttons. I want PayPal to give them the list of times at checkout and I know that I have to do this using the "items: []" array. But I want the items to change based on what the users have in their cart. My cart is integrated using VanillaCartJS. It gets the cart items using things like "cartItem.name", "cartItem.price" and "cartItem.quantity". And The last function "PayPalItems()" is what I am trying to use to call the items array. It is as follows:

 

function PayPalItems() {

return cart.map((cartItem, index) => {
++index;
let currency = cartItem.price;
let quantity = cartItem.quantity;
let itemName = cartItem.name;

let items = [{"unit_amount": {"currency_code": "USD","value": currency},"quantity": quantity,"name": itemName,}];

return items;
});

}

 

In the script where I render the PayPal Buttons looks like this:

 

<!-- JavaScript to call cart.js file and render PayPal Buttons -->
<script src="cart.js"></script>

<script>
paypal.Buttons({
createOrder: function(data, actions) {
// This function sets up the details of the transaction, including the amount and line item details.
return actions.order.create({
"purchase_units": [{
"amount": {
"value": countCartTotal(),
"currency_code": "USD",
"breakdown": {
"item_total": {
"currency_code": "USD",
"value": countCartTotal()
},
},
},
"items": PayPalItems()
}
]
});
},
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.
window.location.href = "orderConfirmed.php";
clearCart()
});
}
}).render('#paypal-button-container');
//This function displays Smart Payment Buttons on your web page.
</script>

 

In the value section, I use a function called "countCartTotal()" This adds up all the items in the cart to give a total that PayPal can then charge the user at checkout.  When I run the code, the user is charged the correct amount but the items are not displayed and when I look at the JavaScript Console I get the following error:

 

Error: /v2/checkout/orders returned status: 400 (Corr ID: 62dab91ed532d)

 

Does anyone know how to fix this? Thanks 

Login to Me Too
0 REPLIES 0

Haven't Found your Answer?

It happens. Hit the "Login to Ask the community" button to create a question for the PayPal community.