Integrate a Stripe Payment Gateway for the Product Cart E-Commerce Application-Part 3
Table of Contents
In part 2 of this series, we have completed the shopping cart and a checkout view with the total amount to be paid. In this part, we shall discuss and walk through the integration of the Stripe Payment Gateway with the checkout. We shall create a few test transactions and see the detailed payment result on our registered user’s dashboard on the Stripe website.
Stripe is a world renowned payment framework. As per their website
Millions of businesses of all sizes—from startups to large enterprises—use Stripe’s software and APIs to accept payments, send payouts, and manage their businesses online.
I have broken the entire payment gateway integration process to a few steps:
- Add Stripe.Net NuGet package
- Get the API Keys from the Stripe Website
- Configure the appsettings.json file
- Create a Class for StripeSetting
- Configure the Startup Class
- Edit the Index View of the Checkout Controller
- Edit the Index Action Method of the Checkout Controller
- Add Processing Action Method to the Checkout Controller
- Create the View for the Processing Action Method
Now let me discuss the steps one at a time.
Add Stripe.Net NuGet package
Using either the package manager console or ManageNuGet package menu install the Stripe.Net latest package available for use. If you wish to use Package Manager Console, open as in the figure below

On the Package Manager Console : Issue the command
Install-Package Stripe.Net
Get the API Keys from the Stripe Website
- Visit https://stripe.com and click “Developers” tab
- On this tab click Full API Reference
- On the page that opens, Click Development quickstart and Obtain your API keys on the resulting page https://stripe.com/docs/development/quickstart#api-keys
NOTE: Stripe issues a pair of these keys known as Publishable and Secret without registering, for test and they also work as tested by me. However, it is advisable to register with them to access your dashboard where you could see your test payments as I will show here. You will get another pair of these keys on logging in with registered credentials. There are many other things that you could perform on your dashboard and I leave it to you to explore them further.
Configure the appsettings.json file
Now open the appsettings.json file and create a block for stripe by adding the following code just before “AllowedHosts” (which is at the end) Here I am using the keys available without logging in, but you may use the keys provided to you on login as a registered user as in both the cases it works fine.
"Stripe": {
"PublishableKey": "pk_test_TYooMQauvdEDq54NiTphI7jx",
"SecretKey": "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
},
Create a Class for StripeSetting
Create a Data folder on the root of the project and add a class named StripeSettings and add the code as below
public class StripeSettings
{
public string SecretKey { get; set; }
public string PublishableKey { get; set; }
}
Configure the Startup Class
Configure the Startup class ConfigureServices to include the Stripe configuration which was set in appsettings.json
services.Configure<StripeSettings>(Configuration.GetSection("Stripe"));
Now put the following line of code in the Configure method of the Startup class
StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc";
This is the secret key that was obtained from the Stripe website earlier.
Edit the Index View of the Checkout Controller
Paste the following markup in the index view of the Checkout Controller to replace the existing cde
@using Microsoft.Extensions.Options
@inject IOptions<ECommerceShoppingCartASPNet5.Data.StripeSettings> Stripe
@{
Layout = "_Layout";
}
<div class="text-center">
<form asp-action="Processing" asp-controller="Checkout" method="post">
<article>
<label>Amount: $ @Math.Round(@ViewBag.DollarAmount, 2)</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="@Stripe.Value.PublishableKey"
data-amount="@ViewBag.Total"
data-name="[Deveducate]"
data-description="Flower payments"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="en"
data-zip-code="true">
</script>
</form>
</div>
Edit the Index Action Method of the Checkout Controller
Paste the following code snippet in the Checkout Controller to replace the existing code
[TempData]
public string TotalAmount { get; set; }
public IActionResult Index()
{
var cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
ViewBag.cart = cart;
ViewBag.DollarAmount = cart.Sum(item => item.Product.Price * item.Quantity);
ViewBag.total = Math.Round(ViewBag.DollarAmount, 2)*100;
ViewBag.total = Convert.ToInt64(ViewBag.total);
long total = ViewBag.total;
TotalAmount = total.ToString();
return View();
}
Note that I have created a property named TotalAmount and decorated it with TempData attribute. This attribute will ensure that the TotalAmount is persistent across posts to another Action Method which will be known as “Processing” action method.
The Index Action Method creates and assigns a cart to the dynamic ViewBag object. It then gets the total price amount of products in the cart in dollar value. The dollar value is internally converted to cents and rounded up to 2 places of decimal. This is necessary as the Stripe gateway deals in cents only for calculations. The rounded up total price in cents is then converted to long data type (as Stripe considers amount to be of lomg
Add Processing Action Method to the Checkout Controller
Now create an Action Method called Processing with the following code
[HttpPost]
public IActionResult Processing(string stripeToken, string stripeEmail)
{
var optionsCust = new CustomerCreateOptions
{
Email = stripeEmail,
Name = "Robert",
Phone = "04-234567"
};
var serviceCust = new CustomerService();
Customer customer = serviceCust.Create(optionsCust);
var optionsCharge = new ChargeCreateOptions
{
/*Amount = HttpContext.Session.GetLong("Amount")*/
Amount = Convert.ToInt64(TempData["TotalAmount"]),
Currency = "USD",
Description = "Buying Flowers",
Source = stripeToken,
ReceiptEmail = stripeEmail,
};
var service = new ChargeService();
Charge charge = service.Create(optionsCharge);
if (charge.Status == "succeeded")
{
string BalanceTransactionId = charge.BalanceTransactionId;
ViewBag.AmountPaid =Convert.ToDecimal(charge.Amount) % 100 / 100 + (charge.Amount)/100 ;
ViewBag.BalanceTxId = BalanceTransactionId;
ViewBag.Customer = customer.Name;
//return View();
}
return View();
}
This method is responsible for processing of the checkout and is decorated with an HttpPost verb as it of Post type. Here the customer object is created with options to fill the customer details such as: Email, Name, Phone etc. in the CustomerCreateOptions object. These options are then passed to a CustomerService type through the latter’s Create method to create the customer.
Similarly a charge object is created with options to fill the charge details such as: Amount, Currency, Description, Source, Receipt email etc. in the ChargeCreateOptions object. These options are passed to a ChargeService type through the latter’s Create method to create the charge.
Now how to process when the charge (payment) succeeds? The method I have adopted in this project is to show properties such as the Customer name, Amount paid etc. in the Processing View when the charge status is “succeeded” as the response of the payment request.
Run the Application
Now run the application by clicking the IIS Express icon on top and it shows the following work flow:

On Clicking Go To Checkout we see the Stripe Gateway returned view as follows:

On clicking Pay with Card button and filling the form it displays as follows:

Once the Pay (Amount) button is clicked the payment is processed and the resultant screen looks like below

The following diagram show a few of the test payments detailed on the Stripe website dashboard that I created on my journey towards completing the project. Since it is per user profile, only those payments using the profile secret key will be listed here. That means if you use general(unlogged user) secret key it won’t be logged in the dashboard.

5 Responses
This whole series has been very informative, thank you very much 🤝
Thanks for your kind words. I am glad that it helped.
Cheers
Kaushik
Hi Arionne,
Thanks for your kind words. Please stay in touch with us for more such posts.
Best
Kaushik
sir iska source code and vedio mil sakta hai kya hindi mai
The video is at the following link: https://youtu.be/YMWWeAkAviA
Source Code: https://github.com/krchome/ECommerceShoppingCartASPNet5