Published on: 28 October, 2016

PayPal Express Checkout using C# MVC Web API

Posted by andy | 3993 views 4 likes 2 favourites 9 comments
Tumblr Digg Google Plus

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
Commented on: 12 Feb, 2017 04:04:43 AM
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
Commented on: 13 Feb, 2017 11:22:20 AM
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
Commented on: 14 Feb, 2017 07:00:32 AM
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
Commented on: 14 Feb, 2017 03:22:21 PM
Good to hear that Jonas ;-)
chic
Commented on: 11 May, 2017 04:25:41 PM
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
Commented on: 11 May, 2017 04:50:53 PM
Thanks chic, for sharing your thought. It would be useful for others if they find the same problem.
John A Davis
Commented on: 03 Apr, 2017 08:54:47 AM
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
Commented on: 03 Apr, 2017 09:21:48 AM
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
Commented on: 03 Apr, 2017 02:36:59 PM
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
Commented on: 03 Apr, 2017 02:58:04 PM
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.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Share your article with us and add your own google adsense account to earn extra money. Plus, you can promote a link back to your site.
Related Articles
Published on: 27 October, 2017
In this article, you will learn how to download a file in Web API MVC. We will use HTTP Get API method to perform this download action with one single parameter which will accept the file name.