IMG-LOGO

PayPal Express Checkout using C# MVC Web API

andy - 28 Oct, 2016 22760 Views 23 Comment

In this tutorial you will learn how easily you can implement a simple checkout express using C# MVC Web API. We will create a really simple shopping cart where customers can add and delete their cart items before proceed to payment.

Let's start by creating an empty web application MVC project. In this example, we will use the Visual Studio Community 2015. Open the program and click the Menu > File > Project.

Select the Template for C# Language and choose the ASP.Net Web Application.

We are going to create this sample project as Web API Project.

The next step is to install the PayPal SDK. We can use Nuget Manager console to install this. It will basically will add the PayPal.dll and NewtonSoft.dll into the project. To install the component, simply type in the following code.

Install-Package PayPalCoreSDK

The next step is to create a PayPal app. You will need to go to the PayPal developer site.

https://developer.paypal.com

If you do not have an account, you will need to create it first. Once create you can create a new app under Rest API apps.

Alternatively, if you are lazy to create an API account, you can use the following API credentials. They are from PayPal SDK sample. If it does not work, please use your own credential API Keys.

Client ID: AbB-IrAZcrf_Z4eTA6fjFHXaORl_RsdQ7dV1E5akBNZxs3LY4Kf3uRU2XiFFnSwI5h7UpbwM4JQXpYx6
Client Secret: EGdqipr2ptfiAI1nQ3ufJ07duSWW7G_eAQ5dqqGTsXVA_TruqplK60qrXFCaQoAWtRqaFshMDIcrCEm7

Once we have the API keys we can now add those information into our project web.config, you can save this information in the database if you prefer. Open your web.config and add the following line in your web.config file under configuration section.

<paypal>
    <settings>
      <!-- Replace the mode to `security-test-sandbox` to test if your server supports TLSv1.2. For more information follow README instructions.-->
      <add name="mode" value="sandbox"/>
      <add name="connectionTimeout" value="360000"/>
      <add name="requestRetries" value="1"/>
      <add name="clientId" value="AbB-IrAZcrf_Z4eTA6fjFHXaORl_RsdQ7dV1E5akBNZxs3LY4Kf3uRU2XiFFnSwI5h7UpbwM4JQXpYx6"/>
      <add name="clientSecret" value="EGdqipr2ptfiAI1nQ3ufJ07duSWW7G_eAQ5dqqGTsXVA_TruqplK60qrXFCaQoAWtRqaFshMDIcrCEm7"/>
    </settings>
  </paypal>

And then add the following section setting under ConfigSections item. Make sure you add this one otherwise you will get an error saying related configuration data for the page is invalid.

<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />

The next step is to create a PayPal Configuration static class. This class will be used to return a PayPal API authentication object token against your credential api keys. On your solution explorer, create a new folder called Utilities. Add a new static class name PayPalConfiguration.cs

Edit the class file and copy the following code.

using PayPal.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ByTutorial.com.PayPalExpressCheckout.Utilities
{
    public class PayPalConfiguration
    {
        public readonly static string ClientId;
        public readonly static string ClientSecret;

        // Static constructor for setting the readonly static members.
        static PayPalConfiguration()
        {
            var config = GetConfig();
            ClientId = config["clientId"];
            ClientSecret = config["clientSecret"];
        }

        // Create the configuration map that contains mode and other optional configuration details.
        public static Dictionary<string, string> GetConfig()
        {
            return ConfigManager.Instance.GetProperties();
        }

        // Create accessToken
        private static string GetAccessToken()
        {           
            string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();
            return accessToken;
        }

        // Returns APIContext object
        public static APIContext GetAPIContext(string accessToken = "", string requestID = "")
        {
            var apiContext = new APIContext(string.IsNullOrEmpty(accessToken) ? GetAccessToken() : accessToken, string.IsNullOrEmpty(requestID) ? Guid.NewGuid().ToString() : requestID);
            apiContext.Config = GetConfig();
            return apiContext;
        }
    }
}
The request id is basically used to represent the order id, this must be unique and actually being presented to prevent any duplication same payment. In this example, I am using GUID for testing purpose only. But in real life, you should replace this with an invoice or order no.

We need to modify the home page index.html to the following code. Note: all the screens like View Cart, Order confirmation, View transactions history will be placed into one page. Feel free to separate them if you need to.

<div id="transparent-bg"></div>
<div id="loading-message"></div>
<div id="product-panel" class="panel-box">
    <h1>Product List</h1>
    <div class='m-bot'>
        <table cellpadding='0' cellspacing='0' class='tbl-cart-amount'>
            <tr>
                <td class='bold'>No of Items: </td>
                <td><span id="no-of-items" class='value'>0</span></td>
            </tr>
            <tr>
                <td class='bold'>Cart Amount: </td>
                <td>$<span id="cart-amount" class='value'>0.0</span></td>
            </tr>
            <tr>
                <td colspan="2"><input type="button" class="btn" id="btnShowTransactions" value="Show Transaction History" /></td>
            </tr>
        </table>
    </div>
    <div id="product-box"></div>
</div>

<div id="cart-panel" class="panel-box">
    <h1>My Cart</h1>
    <div id="cart-box"></div>
</div>

<div id="confirmation-panel" class="panel-box">
    <h1>Order confirmation</h1>
    <table class='tbl' cellpadding='0' cellspacing='0'>
        <tr class='trHeader'>
            <td>Billing Information</td>
            <td>Shipping Information</td>
        </tr>
        <tr>
            <td><div id="billing-information"></div></td>
            <td><div id="shipping-information"></div></td>
        </tr>
    </table>

    <table class='tbl m-top' cellpadding='0' cellspacing='0' id='cart-confirm'></table>
</div>

<div id="complete-panel" class="panel-box">
    <h1>Order Completed</h1>
    <div id="complete-box"></div>
</div>

<div id="transaction-panel" class="panel-box">
    <h1>Transaction History</h1>
    <div id="transaction-box"></div>
</div>

<p class='buttons'><input type="button" value="View Cart" id="btnViewCart" class='btn-action btn' /> <input type="button" value="Continue Shopping" id="btnContinueShopping" class='btn-action btn' /> <input type="button" value="Checkout" id="btnCheckout" class='btn-action btn' /> <input type="button" value="Pay" id="btnPay" class='btn-action btn' /> <input type="button" value="Back" id="btnBack" class='btn-action btn' /></p>

<div class="m-top" id="message"></div>

@section scripts{
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/2.15.1/moment-with-locales.min.js"></script>
    <script src="~/Scripts/paypal.js"></script>
}

This will be the css style for styling our shopping cart.

body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}


.panel-box, .btn-action{
    display:none;
}

.tbl{
	border-top:solid 1px #161515;
	border-left:solid 1px #161515;
}

.tbl td{
	border-right:solid 1px #161515;
	border-bottom:solid 1px #161515;
	padding:5px 10px;
}

table.tbl tr.trHeader{
	background:#141111;
	color:#fff;
}

.txtQty{
	width:70px;
}

.btn{
	cursor:pointer;
	margin:0 10px;
}

table.tbl-cart-amount td{
	padding:5px 10px;
}

.value{
	font-weight:bold;
	font-size:1.5rem;
}

.bold{
	font-weight:bold;
}

.m-bot{
	margin-bottom:15px;
}

.m-top{
	margin-top:15px;
}

.error-message{
	color:#fff;
	background:red;
	padding:20px;
}

#transparent-bg{
	display: none; 
	position: fixed;
    top: 0%; 
	left: 0%; 
	width: 100%; 
	height: 100%; 
	background-color: Black; 
	z-index: 1001;
    -moz-opacity: 0.35; 
	opacity: .35; 
	filter: alpha(opacity=35);
}

#loading-message{
	position:fixed;
	left:50%;
	top:50%;
	margin-top:-75px;
	height:150px;
	width:300px;
	margin-left:-150px;
	z-index:1002;
	background:#fff;
	text-align:center;
	padding:10px;
	box-sizing: border-box;
	border-radius:5px;
	display:none;
}

.buttons{
	margin-top:20px;
}

And this is our main javascript logic that will perform the shopping cart payment.

var cartList = [];

$(function () {

    $.ajax({
        type: "POST",
        url: "/API/PayPal/GetProducts",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xhr, status, error) {
            console.log(xhr.responseText);
        },
        success: function (responseData) {
            cartList = getCart();
            if (cartList == null || cartList != null && cartList.length == 0) {
                cartList = responseData.slice(0);
                saveCart();
            }
            buildProductList(cartList);

            //get params
            var params = getParams();
            if (Object.keys(params).length == 0) {
                //initial page load we want to show product list
                $(".btn-action, #btnViewCart").hide();
                $("#product-panel, #btnContinueShopping").show();
            } else {
                //confirmation payment mode
                if (params["payerid"] != null && params["token"] != null && params["paymentid"] != null) {
                    $(".panel-box, #btnCheckout").hide();
                    $("#confirmation-panel").show();
                    showMessage("<p><img src='/content/loading.gif'/></p><p>Please wait while we get the order information.</p>");

                    $.ajax({
                        type: "POST",
                        url: "/API/PayPal/GetPaymentDetails?paymentID=" + params["paymentid"],
                        error: function (xhr, status, error) {
                            console.log(xhr.responseText);
                        },
                        success: function (r) {
                            hideMessage();
                            if (r != null) {
                                if (r.state == "approved") {
                                    $(".panel-box, .buttons").hide();
                                    $("#complete-panel").show();
                                    $("#complete-box").html("<p>Thank you for your purchase. A copy of your purchase order and receipt has been sent to your email address. Your payment reference number is <span class='bold'>" + r.transactions[0].related_resources[0].sale.id + "</span></p>");

                                } else {
                                    $(".panel-box").hide();
                                    $("#confirmation-panel").show();
                                    $("#btnContinueShopping, #btnPay").show();
                                    //build the payer information
                                    var customer = r.payer.payer_info;
                                    var sb = ""
                                    sb = sb + "<table class='tbl' cellpadding='0' cellspacing='0'>";
                                    sb = sb + "<tr><td class='td-label'>Customer Name</td><td>" + customer.first_name + " " + customer.last_name + "</td></tr>";

                                    var billingAddress = customer.billing_address == null ? customer.shipping_address : customer.billing_address;
                                    sb = sb + "<tr><td class='td-label'>Address</td><td>" + billingAddress.line1 + "<br/>" + (billingAddress.line2 == null ? "" : billingAddress.line2) + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>Suburb</td><td>" + billingAddress.city + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>State</td><td>" + billingAddress.state + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>Post Code</td><td>" + billingAddress.postal_code + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>Phone</td><td>" + (billingAddress.phone == null ? "" : billingAddress.phone) + "</td></tr>";
                                    sb = sb + "</table>";
                                    $("#billing-information").html(sb);

                                    //shipping information
                                    var shippingAddress = customer.shipping_address;
                                    sb = ""
                                    sb = sb + "<table class='tbl' cellpadding='0' cellspacing='0'>";
                                    sb = sb + "<tr><td class='td-label'>Receipient Name</td><td>" + shippingAddress.recipient_name + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>Address</td><td>" + shippingAddress.line1 + "<br/>" + (shippingAddress.line2 == null ? "" : shippingAddress.line2) + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>Suburb</td><td>" + shippingAddress.city + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>State</td><td>" + shippingAddress.state + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>Post Code</td><td>" + shippingAddress.postal_code + "</td></tr>";
                                    sb = sb + "<tr><td class='td-label'>Phone</td><td>" + (shippingAddress.phone == null ? "" : shippingAddress.phone) + "</td></tr>";
                                    sb = sb + "</table>";

                                    $("#shipping-information").html(sb);

                                    if (r.transactions.length > 0) {
                                        $("#divPaymentTo").html(r.transactions[0].payee.email);
                                        $("#divInvoiceNumber").html(r.transactions[0].invoice_number);
                                        $("#divOrderDescription").html(r.transactions[0].description);

                                        var items = r.transactions[0].item_list.items;
                                        sb = "";
                                        sb = sb + "<tr class='trHeader'>";
                                        sb = sb + "<td>Product Name</td>";
                                        sb = sb + "<td>Unit Price</td>";
                                        sb = sb + "<td>Qty</td>";
                                        sb = sb + "<td>Sub Total</td>";
                                        sb = sb + "</tr>";
                                        items.forEach(function (item) {
                                            var subTotal = parseInt(item.quantity) * parseFloat(item.price);
                                            subTotal = Math.round(subTotal * 100) / 100;
                                            sb = sb + "<tr><td>" + item.name + "</td><td>$" + parseFloat(item.price).toFixed(2) + "</td><td>" + item.quantity + "</td><td>$" + subTotal + "</td></tr>";
                                        });

                                        sb = sb + "<tr>";
                                        sb = sb + "<td colspan='3'><div class='right bold'>Total:</div></td>";
                                        sb = sb + "<td><div id='divSubTotal' class='bold'>$" + r.transactions[0].amount.details.subtotal + "</div></td>";
                                        sb = sb + "</tr>";
                                        sb = sb + "<tr>";
                                        sb = sb + "<td colspan='3'><div class='right bold'>GST:</div></td>";
                                        sb = sb + "<td><div id='divGST' class='bold'>$" + r.transactions[0].amount.details.tax + "</div></td>";
                                        sb = sb + "</tr>";
                                        sb = sb + "<tr>";
                                        sb = sb + "<td colspan='3'><div class='right bold'>Shipping:</div></td>";
                                        sb = sb + "<td><div id='divShipping' class='bold'>$" + r.transactions[0].amount.details.shipping + "</div></td>";
                                        sb = sb + "</tr>";
                                        sb = sb + "<tr>";
                                        sb = sb + "<td colspan='3'><div class='right bold'>Final Amount:</div></td>";
                                        sb = sb + "<td><div id='finalamount' class='bold'>$" + r.transactions[0].amount.total + "</div></td>";
                                        sb = sb + "</tr>";
                                        $("#cart-confirm").append(sb);
                                    }
                                }
                            }
                        }
                    });
                }
            }

        }
    });

    $("#btnViewCart").off("click");
    $("#btnViewCart").on("click", function () {
        showCart(cartList);
    });

    $("#btnContinueShopping").off("click");
    $("#btnContinueShopping").on("click", function () {
        buildProductList(cartList);
    });

    $("#btnCheckout").off("click");
    $("#btnCheckout").on("click", function () {
        var jsonObject = {
            ProductList: getCart(),
            InvoiceNumber: "INV" + Math.floor((Math.random() * 999999) + 1000000),
            Currency: "USD",
            Tax: 0,
            ShippingFee: 0,
            OrderDescription: 'Sample Paypal Express Checkout',
            SiteURL: window.location.href.split('?')[0]
        }
        showMessage("<p><img src='/content/loading.gif'/></p><p>Please wait while we redirect you to PayPal website.</p>");
        $.ajax({
            type: "POST",
            url: "/API/PayPal/GetPaymentPayPalURL",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(jsonObject),
            dataType: "json",
            error: function (xhr, status, error) {
                console.log(xhr.responseText);
            },
            success: function (responseData) {
                hideMessage();
                if (responseData.indexOf("ERROR") >= 0) {
                    $("#message").html("<div class='error-message'>" + responseData + "</div>");
                } else {
                    window.location.href = responseData;
                }
            }
        });
    });

    $("#btnBack").off("click");
    $("#btnBack").on("click", function () {
        $(".panel, #btnBack").hide();
        $("#btnShowTransactions").show();
        buildProductList(cartList);
    });

    $("#btnShowTransactions").off("click");
    $("#btnShowTransactions").on("click", function () {
        showMessage("<p><img src='/content/loading.gif'/></p>Please wait while we retrieve the payment transaction history from PayPal.");
        var jsonObject = {
            Count: 1000,
            StartID : "",
            StartIndex: "",
            EndTime: "",
            StartDate: "",
            PayeeEmail: "",
            PayeeID: "",
            SortBy: "create_time",
            SortOrder: "desc"
        }

        $.ajax({
            type: "POST",
            url: "/API/PayPal/GetPaymentHistory",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(jsonObject),
            dataType: "json",
            error: function (xhr, status, error) {
                console.log(xhr.responseText);
            },
            success: function (r) {
                hideMessage();
                if (r != null) {
                    $(".panel-box, .btn").hide();
                    $("#btnBack, #transaction-panel").hide();
                    if (r.payments <= 0) {
                        $("#transaction-box").html("<div class='info-message'>There are no payment transactions found.</div>");
                    } else {
                        $("#btnBack, #transaction-panel").show();
                        var sb = "";
                        sb = sb + "<table class='tbl' cellpadding='0' cellspacing='0'>";
                        sb = sb + "<tr class='trHeader'>";
                        sb = sb + "<td>Date</td>";
                        sb = sb + "<td>Pay ID</td>";
                        sb = sb + "<td>Reference</td>";
                        sb = sb + "<td>Customer</td>";
                        sb = sb + "<td>Email</td>";
                        sb = sb + "<td>Amount Paid</td>";
                        sb = sb + "<td>Items</td>";
                        sb = sb + "<td>Status</td>";
                        sb = sb + "</tr>";

                        r.payments.forEach(function (payment) {
                            console.log(payment.transactions[0].related_resources[0], "???");
                            sb = sb + "<tr>";
                            sb = sb + "<td>" + moment(payment.create_time).format('MMMM Do YYYY, h:mm:ss') + "</td>";
                            sb = sb + "<td>" + payment.id + "</td>";
                            sb = sb + "<td>" + (payment.transactions[0].related_resources[0].sale != null ? payment.transactions[0].related_resources[0].sale.id : "") + "</td>";

                            sb = sb + "<td>" + (payment.payer.payer_info != null ? payment.payer.payer_info.first_name + " " + payment.payer.payer_info.last_name : payment.payer.funding_instruments[0].credit_card.first_name + " " + payment.payer.funding_instruments[0].credit_card.last_name) + "</td>";
                            sb = sb + "<td>" + (payment.payer.payer_info != null ? payment.payer.payer_info.email : "") + "</td>";
                            sb = sb + "<td>$" + payment.transactions[0].amount.total + "</td>";
                            sb = sb + "<td>";
                            if (payment.transactions[0].item_list != null) {
                                payment.transactions[0].item_list.items.forEach(function (item) {
                                    sb = sb + "<div>" + item.name + " (" + item.quantity + " X $" + item.price + ")" + "</div>";
                                });
                            }
                            sb = sb + "</td>";
                            sb = sb + "<td>" + payment.state + "</td>";
                            sb = sb + "</tr>";
                        });

                        sb = sb + "</table>";
                        $("#transaction-box").html(sb);
                    }
                } else {
                    alert("Sorry there is an error getting the payment history transactions.");
                }
            }
        });
    });

    $("#btnPay").off("click");
    $("#btnPay").on("click", function () {
        if (confirm("Are you sure you want to make the payment for this order?")) {
            showMessage("<p><img src='/content/loading.gif'/></p>Please wait while we process the payment.");
            var params = getParams();
            var jsonObject = {
                PayerID: params["payerid"],
                PaymentID: params["paymentid"]
            }

            $.ajax({
                type: "POST",
                url: "/API/PayPal/ProcessPayment",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(jsonObject),
                dataType: "json",
                error: function (xhr, status, error) {
                    console.log(xhr.responseText);
                },
                success: function (r) {
                    hideMessage();
                    $(".panel-box, .buttons").hide();
                    $("#complete-panel").show();
                    $("#complete-box").html("<p>Thank you for your purchase. A copy of your purchase order and receipt has been sent to your email address. Your payment reference number is <span class='bold'>" + r.transactions[0].related_resources[0].sale.id  + "</span></p>");
                }
            });
        }
    });


});

function showCart(data) {
    $(".panel-box").hide();
    $("#cart-panel").show();

    var sb = "";
    if (data != null && data.length > 0) {
        sb = sb + "<table cellpadding='0' cellspacing='0' class='tbl'>";
        sb = sb + "<tr class='trHeader'>";
        sb = sb + "<td>Product Name</td>";
        sb = sb + "<td>Description</td>";
        sb = sb + "<td>SKU</td>";
        sb = sb + "<td>Price</td>";
        sb = sb + "<td>Qty</td>";
        sb = sb + "<td>Sub Total</td>";
        sb = sb + "<td></td>";
        sb = sb + "</tr>";

        data.forEach(function (product, index) {
            if (product.OrderQty > 0) {
                sb = sb + "<tr>";
                sb = sb + "<td>" + product.Name + "</td>";
                sb = sb + "<td>" + product.Description + "</td>";
                sb = sb + "<td>" + product.SKU + "</td>";
                sb = sb + "<td>$" + product.UnitPrice.toFixed(2) + "</td>";
                sb = sb + "<td>" + product.OrderQty + "</td>";
                sb = sb + "<td>$" + (Math.round((product.UnitPrice * product.OrderQty) * 100) / 100).toFixed(2) + "</td>";
                sb = sb + "<td><input type='button' class='btnDelete btn' data-id='" + product.ProductID + "' value='Delete'/></td>";
                sb = sb + "</tr>";
            }
        });

        sb = sb + "</table>";
    } else {
        sb = "<div class='message-info'>There are no products available.</div>";
    }

    $("#cart-box").html(sb);

    $(".btnDelete").off("click");
    $(".btnDelete").on("click", function () {
        var id = $(this).attr("data-id");
        cartList.forEach(function (item) {
            if (item.ProductID == id) {
                item.OrderQty = 0;
            }
        });
        saveCart();
        showCartAmount();
    });
}

function buildProductList(data) {
    $(".panel-box").hide();
    $("#product-panel").show();

    var sb = "";
    if (data != null && data.length > 0) {
        sb = sb + "<table cellpadding='0' cellspacing='0' class='tbl'>";
        sb = sb + "<tr class='trHeader'>";
        sb = sb + "<td>Product Name</td>";
        sb = sb + "<td>Description</td>";
        sb = sb + "<td>SKU</td>";
        sb = sb + "<td>Price</td>";
        sb = sb + "<td>Qty</td>";
        sb = sb + "<td></td>";
        sb = sb + "</tr>";

        data.forEach(function (product, index) {
            sb = sb + "<tr>";
            sb = sb + "<td>" + product.Name + "</td>";
            sb = sb + "<td>" + product.Description + "</td>";
            sb = sb + "<td>" + product.SKU + "</td>";
            sb = sb + "<td>$" + product.UnitPrice.toFixed(2) + "</td>";
            sb = sb + "<td><input id='txtQty" + product.ProductID + "' type='number' class='txtQty' max-length='3' data-id='" + product.ProductID + "' value='1'/></td>";
            sb = sb + "<td><input type='button' class='btnAddToCart btn' data-id='" + product.ProductID + "' value='Add to Cart'/></td>";
            sb = sb + "</tr>";
        });

        sb = sb + "</table>";
    } else {
        sb = "<div class='message-info'>There are no products available.</div>";
    }
    $("#product-box").html(sb);
    showCartAmount();

    $(".btnAddToCart").off("click");
    $(".btnAddToCart").on("click", function () {
        var id = $(this).attr("data-id");
        var qty = $("#txtQty" + id).val();
        if (qty <= 0) {
            alert("Please enter valid quantity");
        } else {
            cartList.forEach(function (item) {
                if (item.ProductID == id) {
                    item.OrderQty = parseInt(item.OrderQty) + parseInt(qty);
                }
            });
            saveCart();
            showCart(cartList);
        }
    });
}

function showCartAmount() {
    if (cartList != null && cartList.length > 0) {
        var qty = 0;
        var amount = 0;
        cartList.forEach(function (item) {
            if (item.OrderQty > 0) {
                qty = qty + item.OrderQty;
                amount = amount + item.UnitPrice * item.OrderQty;
            }
        });

        $("#btnCheckout, #btnViewCart").hide();
        if (qty > 0) {
            $("#btnCheckout, #btnViewCart").show();
        }

        $("#cart-amount").html((Math.round(amount * 100) / 100).toFixed(2));
        $("#no-of-items").html(qty);
    } else {
        $("#cart-amount").html("0.0");
        $("#no-of-items").html(0);
    }
}

function getParams() {
    var url = window.location.href;
    var params = {};
    var qs = url.indexOf("?") >= 0 ? url.split('?') : [];
    if (qs.length > 0) {
        var arr = qs[1].split('&');
        arr.forEach(function (entry, index) {
            var q = entry.split('=');
            if (q != null && q.length == 2) {
                params[q[0].toString().toLowerCase()] = q[1];
            }
        });
    }
    return params;
}

function saveCart() {
    localStorage.setItem("cart", JSON.stringify(cartList));
}

function getCart() {
    var currentCart = [];
    if (localStorage.getItem("cart") != null) {
        currentCart = JSON.parse(localStorage.getItem("cart"));
    }
    return currentCart;
}

function showMessage(message) {
    $("#transparent-bg").show();
    $("#loading-message").show();
    $("#loading-message").html(message);
}

function hideMessage() {
    $("#transparent-bg").hide();
    $("#loading-message").hide();
    $("#loading-message").html("");
}

Sample Cart Images.

Download Files

Download

Feel free to post your comment if you have any question about this example tutorial.

Comments

Jonas
12 Feb, 2017
Hi , This tutorial is great – but I error like "Currency amount must be non-negative number” I'am runing on my computer (localhost) the hole error is as following: ERROR: {"name":"VALIDATION_ERROR","details":[{"field":"transactions.amount.total","issue":"Currency amount must be non-negative number, may optionally contain exactly 2 decimal places separated by '.', optional thousands separator ',', limited to 7 digits before the decimal point and currency which is a valid ISO Currency Code"}],"message":"Invalid request - see details","information_link":"https://developer.paypal.com/docs/api/#VALIDATION_ERROR","debug_id":"1f91f9441881"} Can you please help me what to do to fix this error? Thank you in advance!
andy
13 Feb, 2017
It looks to me by looking at the error, you may have entered or input negative amount. Could you debug the project and see what is actually the amount has been passed to PayPal?
Jonas
14 Feb, 2017
Hi Andy, thank you for response, Now it's working when I changed UnitPrice tole hole nummber price (non decimal price) in List GetProducts() From: list.Add(new ProductInfo() { ProductID = 1, Name = "PC Case", Description = "Durable PC Case Black Color", UnitPrice = 44.95, SKU = "PC250" }); To: //list.Add(new ProductInfo() { ProductID = 1, Name = "PC Case", Description = "Durable PC Case Black Color", UnitPrice = 44, SKU = "PC250" }); and so on with all products
andy
14 Feb, 2017
Good to hear that Jonas ;-)
chic
11 May, 2017
Hello Thank's for this excellent tutorial ! The issue you mention comes from the formatting information of number for the user executing the web site (CultureInfo). In the function GetPaymentPayPalURL of source PayPalController.cs there are several ToString() applied to double and numbers (for exemple line 50 Math.Round(cartItem.UnitPrice, 2).ToString(); The result is that the string is formatted according to locale culture of user executing the web site (normally IIS user). If you're using an US configured OS, no problem, but if other (like mine : french), the problem appears (the decimal point (.) is a comma (,) in France). The easiest here is to change and use CulureInfo.InvariantCulture (exemple : Math.Round(cartItem.UnitPrice, 2).ToString(CultureInfo.InvariantCulture);). You change in all the places this appears (there are several) and everything works like a charm ! Thank's again for your tutorial ! Cheers. Chic
andy
11 May, 2017
Thanks chic, for sharing your thought. It would be useful for others if they find the same problem.
John A Davis
03 Apr, 2017
How hard would it be to use this but not have a shopping cart? I just want charge for one item (a picture) and allow them to download it. They click "Buy Now" button and get sent to PayPal right away and their transaction when done sends back the details to my server. Could Inuse your code and alter it or would it better to start from scratch.
andy
03 Apr, 2017
I am not sure if you are a programmer or not. But the concept of this shopping cart would work for your single product. So I dont think you need to write it from scratch, if it is easier you may be able to do from scratch otherwise you can just copy the business logic as needed.
John A Davis
03 Apr, 2017
Thank you Andy. Yes, I am a programmer. I can pretty much do anything. I have a webiste that clients can buy credits to list dance lessons. I am using Paypal and it has been going for 8+ years. However, there is all this new stuff and I think I might be able to figure out how to use your code. Thank you. Paypal developer website is very confusing.
andy
03 Apr, 2017
That's good John if you are a programmer. Yeah the Paypal development site is a bit confusing. that's why I create this simple example to help people out. To make your life easier, if you do not mind the shopping cart, you can just alter the API class controller named PayPalController and add your single product there in GetProducts method. As the example is hard coded, you can save the product information from a database so it can save your time if you need to make some changes. without have to recompile and built the project. Let me know if you need further help.
Eddie Chan
27 Jan, 2018
Hi Andy, Do users (i.e. buyer) need a PayPal account in order to perform Express Checkout? Do I need 'Add To Cart' button or just CheckOut button? Please advise. Thanks, Eddie Chan
andy
28 Jan, 2018
Hi Eddie, The buyers or users don't have to register or need a PayPal account. When they redirected to PayPal site to make the payment, they have an option to enter their credit card details. Regarding with your second question, whether you need to have Add to Cart button or just Checkout button. It will depend, if you only have one product and do not allow multiple purchases at one time, you can only have Checkout button only, but if you want to allow buyers can purchase multiple items at one time. It would be good to allow them to add the purchased items to the cart. In this case, you want to allow Add to Cart button.
Deepti
14 Feb, 2018
Hi , This tutorial is great – but I want to update the amount List.Add(new ProductInfo() { ProductID = 1, Name = "PC Case", Description = "Durable PC Case Black Color", UnitPrice = 0.01, SKU = "PC250" }) but it always comming as 45.95 please tell me where to set these amount With Regards Deepti
andy
15 Feb, 2018
Hi Deepti, You have to compile the project once you made the changes. Otherwise, it will still use the old value.
Deepti
15 Feb, 2018
Hi , Thanks for your Reply But I compiled and Checked Whole project but sill i am unable to find where the amount is getting set whether the amount is set in webapi i wanted to change it from 45.95 to something else please help me out
andy
19 Feb, 2018
Hi Deepti, did you run or compiled? Could you please check the modification date of the DLL file in the bin folder and see if it is up to date. I don't see why it will not update the price. How about you add new product as well.
Basanta
16 Feb, 2018
Hi Andi! Thank you so much for this tutorial. I'm going to implement this in my project. Thanks again :)
Alma La Rocco
02 Mar, 2018
Hello Andy. Thank you for sharing your tutorial. It helped me a lot. I have two questions: 1. How do you change the name of the store, so instead of saying "Facilitator test store" says my store name. 2. How do I hide the "Ship to" section (after you login into PayPal) Thanks in advance.
andy
02 Mar, 2018
Hi Alma, the store name is configured using the PayPal account. If you are using sandbox account, you should be able to change it. Regarding with the Ship section, I think you can do this in the PayPal account settings as well.
Subham
18 Sep, 2018
I am getting 401 error at Make Payment method. I am using live credentials and live mode. Basically, I want to use invoice API of PayPal. So can you help me where should I replace the code to generate an invoice, please do share with me if you have any solution.
andy
22 Sep, 2018
Do you have a url where I can have a look. It looks like you got the 401 unauthorised access.
Akshay Bhagwat
18 Nov, 2018
Hi sir i see following error message and return to merchant We aren't able to process your payment using your PayPal account at this time. Please go back to the merchant and try using a different payment method.
Matt
18 Oct, 2020
I am just wondering if there is an example of the above in dotnet core? Thank you.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

ASP.Net MVC Identity without Entity Framework

Learn how to create your own custom identity authentication and authorization with ASP Net MVC without using Entity Framework By default the example given in the MVC official tutorial site is using Entity Framework So if you do not want ...

How to enable attribute routing in C# MVC?

p If you want to enable routing in C MVC you have to do the following steps Note this only applies to strong MVC version 5 or above strong Open your RouteConfig cs file under App_Start folder in your MVC ...