Checkout - Shopping cart, PayPal and Stripe

PayPal and Stripe – Javascript

0
(0)

Whether you are creating an E-commerce website or simply wanted to receive payments from your website using PayPal and Stripe, this script already contains all the source code you need to show Stripe and PayPal payment buttons and receive payments directly in your Stripe and PayPal accounts.

It also has a full shopping cart implementation, where you can add products to the cart, update quantities, remove products from the cart and move to checkout.

Demo

Source code:

Shopping cart with PayPal and Stripe payments - Javascript
Shopping cart with PayPal and Stripe payments – Javascript

Home page

Products

Here you can add products to the shopping cart and also you can remove products from the shopping cart.

When you add or remove a product from the shopping cart, you will see the shopping cart badge on top updating its values in real-time.

Cart badge

Shopping cart

On clicking the above “Cart” button you will be redirected to the shopping cart page where you can change the number of products and can also remove the product from the shopping cart.

Cart

You can also see the grand total at the bottom right that changes in real-time as you change the quantity of product or when you remove a product from the shopping cart.

Checkout

Here you can make the payment using Stripe or Paypal.

PayPal and Stripe checkout

Fully documented code

Comments have been added with each line of code for explanation.

Code documentation
Code documentation 2
Code documentation 3

Separate file for each function

To manage the code, each payment method is separated in its own file. So you can easily change and modify the code as per your needs.

File management

Price $20 (USD)

Buy now:

  1. Kindly let us know your name and email.
  2. We will send you the payment details.
  3. After the payment is made, the source code will be emailed to you.

[passster password=”highsierra”]

Source code:

/* enable error reporting */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/* setup stripe secret and publishable keys */
define("STRIPE_SECRET_KEY", "");
define("STRIPE_PUBLISHABLE_KEY", "");

/* connect with database */
$conn = mysqli_connect("localhost:8889", "root", "root", "shopping_cart");

/* get shopping cart */
$shopping_cart = isset($_COOKIE["shopping_cart"]) ? json_decode($_COOKIE["shopping_cart"]) : [];

The badge on top:

<!-- link to shopping cart page -->
<a href="<?php echo count($shopping_cart) > 0 ? 'cart.php' : 'javascript:void(0);'; ?>" class="btn btn-primary" id="link-shopping-cart">
    <span style="color: white; margin-right: 5px;">Cart</span>

    <!-- display number of items currently in cart,
        and hide the badge if the cart is empty -->
    <span class="badge badge-light" id="shopping-cart-count" style="<?php echo count($shopping_cart) == 0 ? 'display: none;' : ''; ?>">
        <?php echo count($shopping_cart); ?>
    </span>
</a>

Show all products

<?php
    /* get all products */
    $result = mysqli_query($conn, "SELECT * FROM products");

    /* loop through each product */
    while ($row = mysqli_fetch_object($result)):

        /* check if product already exists in cart */
        $flag = false;
        foreach ($shopping_cart as $c)
        {
            if ($c->id == $row->id)
            {
                $flag = true;
                break;
            }
        }
?>

    <div class="col-md-4" style="margin-top: 30px;">
        <div class="card" style="width: 18rem;">

            <!-- display product image here -->
            <img class="card-img-top" src="<?php echo $row->image; ?>"
            alt="Card image cap"
            style="height: 285px; object-fit: cover;">

            <!-- product name and description -->
            <div class="card-body">
                <h5 class="card-title">
                    <?php echo $row->name; ?>
                    <span class="badge badge-info">$<?php echo $row->price; ?></span>
                </h5>
                
                <p class="card-text"><?php echo substr($row->description, 0, 100) . "..."; ?></p>

                <!-- button to add item in cart, hidden if product is already in cart -->
                <button
                    type="button"
                    onclick="onclick_addToCart(this);"
                    data-id="<?php echo $row->id; ?>"
                    data-name="<?php echo $row->name; ?>"
                    data-price="<?php echo $row->price; ?>"
                    data-image="<?php echo $row->image; ?>"
                    class="btn btn-primary"
                    style="<?php echo $flag ? 'display: none;' : ''; ?>">
                    Add to cart
                </button>

                <!-- button to remove item from cart, hidden if product is not in cart -->
                <button
                    type="button"
                    onclick="onclick_removeFromCart(this);"
                    data-id="<?php echo $row->id; ?>"
                    class="btn btn-danger"
                    style="<?php echo $flag ? '' : 'display: none;'; ?>">
                    Remove from cart
                </button>

            </div>
        </div>
    </div>

<?php endwhile; ?>

Add to cart, remove from cart, update badge

function onclick_addToCart(self) {
    /* get all values for storing in cart */
    var id = self.getAttribute("data-id");
    var name = self.getAttribute("data-name");
    var price = self.getAttribute("data-price");
    var image = self.getAttribute("data-image");

    /* add in shopping cart using cookies */
    cart.addInCart(id, name, price, image);

    /* hide the "add to cart" button, and display "remove from cart" button */
    self.style.display = "none";
    self.nextElementSibling.style.display = "inline";

    /* update badge on top navigation bar */
    updateBadge();
}

function onclick_removeFromCart(self) {
    /* get all values for storing in cart */
    var id = self.getAttribute("data-id");

    /* remove from shopping cart using cookies */
    cart.removeItemFromCart(id);

    /* hide the "remove from cart" button, and display "add to cart" button */
    self.style.display = "none";
    self.previousElementSibling.style.display = "inline";

    /* update badge on top navigation bar */
    updateBadge();
}

function updateBadge() {
    /* get number of items in shopping cart */
    var cartItems = cart.getCartItems().length;

    /* if there is any item in the cart, then display the number.
        And make the badge visible */
    if (cartItems > 0) {
        document.getElementById("shopping-cart-count").innerHTML = cartItems;
        document.getElementById("shopping-cart-count").style.display = "inline";

        /* enable the link to cart page */
        document.getElementById("link-shopping-cart").setAttribute("href", "cart.php");
    } else {

        /* otherwise, hide the badge */
        document.getElementById("shopping-cart-count").style.display = "none";

        /* disable the link to cart page */
        document.getElementById("link-shopping-cart").setAttribute("href", "javascript:void(0);");
    }
}

cart.js

var cart = {
    key: "shopping_cart",
    addInCart: function(id, name, price, image) {
        var cartItems = this.getCartItems();
        cartItems.push({
            "id": id,
            "name": name,
            "price": price,
            "image": image,
            "quantity": 1
        });

        /* setting the cookie expiry time to one year */
        document.cookie = this.key + "=" + JSON.stringify(cartItems) + ";max-age=31536000";
    },
    getCartItems: function() {
        var cookies = document.cookie.split(";");
        for (var a = 0; a < cookies.length; a++) {
            var parts = cookies[a].split("=");
            if (parts[0].trim() == this.key) {
                return JSON.parse(parts[1]);
            }
        }
        return [];
    },
    removeItemFromCart: function(id) {
        var cartItems = this.getCartItems();
        cartItems = cartItems.filter(function (item) {
            return item.id != id;
        });
        document.cookie = this.key + "=" + JSON.stringify(cartItems);
    },
    emptyCart: function() {
        var items = this.getCartItems();
        for (var a = 0; a < items.length; a++) {
            this.removeItemFromCart(items[a].id);
        }
    },
    updateCartQuantity: function(id, quantity) {
        var cartItems = this.getCartItems();
        for (var a = 0; a < cartItems.length; a++) {
            if (cartItems[a].id == id) {
                cartItems[a].quantity = quantity;
                break;
            }
        }
        document.cookie = this.key + "=" + JSON.stringify(cartItems);
    }
};

Shopping cart

<?php
    $grand_total = 0;
    foreach ($shopping_cart as $item):
        $grand_total += ($item->price * $item->quantity);
?>
<tr>
    <td style="display: flex;">
        <img src="<?php echo $item->image; ?>"
            class="img-thumbnail img-sm"
            style="width: 150px; height: 150px; object-fit: cover;">
        <h6 class="title text-truncate" style="margin-left: 10px;"><?php echo $item->name; ?></h6>
    </td>

    <td> 
        <input type="number" name="quantity" class="form-control" value="<?php echo $item->quantity; ?>" min="1" onchange="onchange_cartQuantity(this);" data-id="<?php echo $item->id; ?>" data-price="<?php echo $item->price; ?>">
    </td>

    <td> 
        <div class="price-wrap"> 
            <var class="price">USD <span class="total-price"><?php echo ($item->price * $item->quantity); ?></span></var> 
        </div>
    </td>

    <td class="text-right">
        <button type="button" onclick="deleteFromCart(this);" data-id="<?php echo $item->id; ?>" class="btn btn-outline-danger"> × </button>
    </td>
</tr>

<?php endforeach; ?>

<h3>
    Total

    <span style="float: right;" id="grand-total">$<?php echo $grand_total; ?></span>
</h3>

Update quantity, remove the product

function onchange_cartQuantity(self) {
    /* get product ID and price */
    var id = self.getAttribute("data-id");
    var price = self.getAttribute("data-price");

    /* quantity must be get from input field value */
    var quantity = parseInt(self.value);

    /* update product's quantity in cart using cookies */
    cart.updateCartQuantity(id, quantity);

    /* update the product's total price in cart */
    self.parentElement.parentElement.querySelector(".total-price").innerHTML = (price * quantity).toFixed(2);

    /* function to update grand total. Separate function is created
        because it will be use in updating quantity and
        on deleting product */
    updateGrandTotal();
}

function updateGrandTotal() {
    /* initialize grand total to 0 */
    var grandTotal = 0;

    /* get all cart items */
    var items = cart.getCartItems();
    
    /* loop through all items */
    for (var a = 0; a < items.length; a++) {
        /* calculate price multiply by quantity and increment in grant total */
        grandTotal += (items[a].price * items[a].quantity);
    }

    /* display grand total with dollar sign.
        toFixed() function is used to limit the decimal to 2 places. */
    document.getElementById("grand-total").innerHTML = "$" + grandTotal.toFixed(2);
}

function deleteFromCart(self) {
    /* get product ID */
    var id = self.getAttribute("data-id");

    /* remove item from cart */
    cart.removeItemFromCart(id);

    /* remove product node */
    self.parentElement.parentElement.remove();

    /* update grand total */
    updateGrandTotal();

    /* update badge */
    updateBadge();
}

Checkout

<?php
    /* calculate grand total of cart when page loads */
    $grand_total = 0;
    foreach ($shopping_cart as $item):
        $grand_total += ($item->price * $item->quantity);
    endforeach;
?>

<!-- hidden field for grand total is created, so we can get it in Javascript -->
<input type="hidden" id="grand-total" value="<?php echo $grand_total; ?>">

Billing details

<!-- billing details -->
<div class="row">
    <div class="col-md-12">
        <h3>Billing Details</h3>

        <form id="form-billing-details">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label>Name</label>
                        <input name="name" required class="form-control">
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" required class="form-control">
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="number" min="0" name="phone" required class="form-control">
                    </div>
                </div>
            </div>

            <h3>Address</h3>

            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label>City</label>
                        <input name="city" required class="form-control">
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-group">
                        <label>Country</label>
                        <input name="country" required class="form-control">
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-group">
                        <label>State</label>
                        <input name="state" required class="form-control">
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label>Line 1</label>
                        <textarea name="line1" required class="form-control"></textarea>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-group">
                        <label>Line 2</label>
                        <textarea name="line2" required class="form-control"></textarea>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-group">
                        <label>Postal code</label>
                        <input type="number" min="0" name="postal_code" required class="form-control">
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

Stripe

<!-- include Stripe library -->
<script src="https://js.stripe.com/v3/"></script>

<div class="collapse" id="collapseStripe">
    <div class="card card-body">

        <script>

            /* global variables */
            var stripe = null;
            var cardElement = null;

            /* initialize stripe when page loads */
            window.addEventListener("load", async function () {
                stripe = Stripe('');
                var elements = stripe.elements();
                cardElement = elements.create('card');
                cardElement.mount('#stripe-card-element');
            });

            /* this function will be called when the "Pay now" button is pressed */
            function payViaStripe(self) {

                /* display the loader */
                self.querySelector(".fa-spinner").style.display = "";

                /* get stripe payment intent */
                const stripePaymentIntent = document.getElementById("stripe-payment-intent").value;

                /* get billing detail form values for stripe payment method */
                var billingDetailForm = document.getElementById("form-billing-details");
        
                /* execute the payment */
                stripe
                    .confirmCardPayment(stripePaymentIntent, {
                        payment_method: {
                                card: cardElement,
                                billing_details: {
                                    "address": {
                                        "city": billingDetailForm.city.value,
                                        "country": billingDetailForm.country.value,
                                        "line1": billingDetailForm.line1.value,
                                        "line2": billingDetailForm.line2.value,
                                        "postal_code": billingDetailForm.postal_code.value,
                                        "state": billingDetailForm.state.value
                                    },
                                    "email": billingDetailForm.email.value,
                                    "name": billingDetailForm.name.value,
                                    "phone": billingDetailForm.phone.value
                                },
                            },
                        })
                        .then(function(result) {

                            // Handle result.error or result.paymentIntent
                            if (result.error) {
                                console.log(result.error);
                                alert(result.error.message);
                                // Display "error.message" to the user...

                                self.querySelector(".fa-spinner").style.display = "none";
                            } else {
                                console.log("The card has been verified successfully...", result.paymentIntent);
                                alert("Payment has been made.");
                                self.querySelector(".fa-spinner").style.display = "none";

                                /* you can use the result.paymentIntent object for saving
                                    in database if you want */

                                /* empty the cart */
                                cart.emptyCart();

                                /* redirect the user to home page */
                                window.location.href = "index.php";
                            }
                        });
            }
        </script>

        <!-- Stripe Elements Placeholder -->
        <div class="row" style="margin-top: 20px;">
            <div class="col-md-12">
                <div class="card-label">
                    <div id="stripe-card-element"></div>
                </div>
            </div>
        </div>

        <div class="row" style="margin-top: 30px;">
            <div class="col-md-12">
                <button type="button" class="btn btn-success" onclick="payViaStripe(this);">
                    Pay now
                    <i class="fa fa-spinner fa-spin" style="display: none;"></i>
                </button>
            </div>
        </div>

        <?php
            
            /* stripe secret and publishable keys are in db.php */
            $stripe = new \Stripe\StripeClient(STRIPE_SECRET_KEY);
            
            /* creating setup intent */
            $payment_intent = $stripe->paymentIntents->create([
                'payment_method_types' => ['card'],

                /* convert double to integer for stripe payment intent,
                    multiply by 100 is required for stripe */
                'amount' => round($grand_total) * 100,
                
                'currency' => 'usd',
            ]);
        ?>
        <input type="hidden" id="stripe-public-key" value="<?php echo STRIPE_PUBLISHABLE_KEY; ?>">
        <input type="hidden" id="stripe-payment-intent" value="<?php echo $payment_intent->client_secret; ?>">
    </div>
</div>

Paypal

<!-- Load the required checkout.js script -->
<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>

<!-- Load the required Braintree components. -->
<script src="https://js.braintreegateway.com/web/3.39.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.39.0/js/paypal-checkout.min.js"></script>

<div class="collapse" id="collapsePaypal">
    <div class="card card-body">

        <!-- paypal button will be rendered here using Javascript -->
        <div id="btn-paypal-checkout" style="margin-top: 20px;"></div>
        <div id="paypal-button-container" style="width: 100% !important;"></div>

        <script>

            /* global variables that will be received from PayPal
                when payment succeeds */
            var intent = "",
                orderID = "",
                payerID = "",
                paymentID = "",
                paymentToken = "";

            window.addEventListener("load", function () {

                /* cookieItems array will be used for PayPal because it uses
                    a specific format of data */
                var cookieItems = [];
                var cartItems = cart.getCartItems();

                /* fill the cookieItems array with cart items */
                for (var a = 0; a < cartItems.length; a++) {
                    cookieItems.push({
                        name: cartItems[a].name,
                        description: cartItems[a].name,
                        quantity: cartItems[a].quantity,
                        price: parseFloat(cartItems[a].price),
                        sku: cartItems[a].id,
                        currency: "USD"
                    });
                }

                // Render the PayPal button
                paypal.Button.render({

                    // Set your environment
                    env: 'sandbox', // sandbox | production

                    // Specify the style of the button
                    style: {
                        label: 'checkout',
                        size: 'medium', // small | medium | large | responsive
                        shape: 'pill', // pill | rect
                        color: 'gold', // gold | blue | silver | black,
                        layout: 'vertical'
                    },

                    // PayPal Client IDs - replace with your own
                    // Create a PayPal app: https://developer.paypal.com/developer/applications/create

                    client: {
                        sandbox: '',
                        production: ''
                    },

                    funding: {
                        allowed: [
                            paypal.FUNDING.CARD,
                            paypal.FUNDING.ELV
                        ]
                    },

                    payment: function(data, actions) {
                        return actions.payment.create({
                            payment: {
                                transactions: [{
                                    amount: {
                                        /* get grand total from hidden input field */
                                        total: parseFloat(document.getElementById("grand-total").value),
                                        currency: 'USD'
                                    },
                                    item_list: {
                                        /* custom cookieItems array created specifically
                                            for PayPal */
                                        items: cookieItems
                                    }
                                }]
                            }
                        });
                    },

                    onAuthorize: function(data, actions) {
                        return actions.payment.execute().then(function() {
                            /*console.log({
                                method: "onAuthorize",
                                data: data,
                                actions: actions
                            });*/

                            /* you can use all the values received from PayPal
                                as you want */
                            intent = data.intent;
                            orderID = data.orderID;
                            payerID = data.payerID;
                            paymentID = data.paymentID;
                            paymentToken = data.paymentToken;

                            console.log({
                                "intent": intent,
                                "orderID": orderID,
                                "payerID": payerID,
                                "paymentID": paymentID,
                                "paymentToken": paymentToken,
                            });

                            /* empty the cart */
                            cart.emptyCart();

                            /* redirect the user to home page */
                            window.location.href = "index.php";
                        });
                    },
                    
                    onCancel: function (data, actions) {
                        // Show a cancel page or return to cart
                        console.log({
                            method: "onCancel",
                            data: data,
                            actions: actions
                        });
                    }

                }, '#btn-paypal-checkout');
            });
        </script>
    </div>
</div>

[/passster]

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





Leave a Reply

Please disable your adblocker or whitelist this site!