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; } } }
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
Feel free to post your comment if you have any question about this example tutorial.