JSFiddle - React, Tailwind, and code Playground
by Hemanth HM
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Checkout Integration | Client Demo </title>
</head>
<body>
<div>
<div style="margin:1.5rem">
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="1" max="5" value="1">
</div>
</div>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=test¤cy=USD"></script>
</body>
</html>
JavaScript
const paypalButtonsComponent = paypal.Buttons({
style: {
color: "gold",
shape: "rect",
layout: "vertical"
},
// set up the transaction
createOrder: (data, actions) => {
// pass in any options from the v2 orders create call:
// https://developer.paypal.com/api/orders/v2/#orders-create-request-body
const createOrderPayload = {
purchase_units: [{
amount: {
value: "" + (15.30 * +document.querySelector('#quantity').value)
}
}]
};
return actions.order.create(createOrderPayload);
},
// finalize the transaction
onApprove: (data, actions) => {
const captureOrderHandler = (details) => {
const payerName = details.payer.name.given_name;
console.log('Transaction completed');
};
return actions.order.capture().then(captureOrderHandler);
},
// handle unrecoverable errors
onError: (err) => {
console.error('An error prevented the buyer from checking out with PayPal', err);
}
});
paypalButtonsComponent
.render("#paypal-button-container")
.catch((err) => {
console.error('PayPal Buttons failed to render');
});