This video is available to students only

Creating Stripe Payment Service

In this lesson, we're going to set up Stripe payment service

Creating Stripe payment service#

Now that we have set up Stripe, let's create a payment service which will be responsible for interacting with the Stripe server. Inside Infrastructure Services, let's create a new class called PaymentService. To start off, let's create a constructor. We need to access the Stripe keys which are inside the appsettings.Development.Json file, so we can use IConfiguration with name, config. Let's import it and initialize field from parameter.

Now we will create an asynchronous function which will return the paymentIntent so we can write public async Task PaymentIntent and let's call it PaymentIntentAsync. This will take the basket as a parameter. Let's import Task from Threading.Tasks and PaymentIntent using stripe. Also, we'd import the Basket using Entity. Inside the function, we will write StripeConfiguration.ApiKey which will be equal to config Stripe SecretKey. We'd make sure we're not making any spelling errors; it looks fine. Below this, let's create a new service which will be equal to new PaymentIntentService. This is provided by Stripe as well. We also need intent which will be equal to new PaymentIntent.

Let's now write the total cost of the basket. We will use basket.Items.Sum and inside, we just need the price of the course, so we can write item.Course.Price. Now let's import Sum from System.Linq. We want to check if we have the paymentintentId already. If we have it, then it means that we're updating the previous paymentIntent; otherwise, we'll have to create a new payment intent. So let's check if basket.PaymentIntentId is empty. If it is, we will create options which will be equal to the new PaymentIntentCreateOptions; we want to provide amount here, and if we pass the total, we will see an error because Stripe expects long but our price is float type. We can simply parse it by creating a new long variable updated total. Now we can write long and multiply the total with 100. Instead of total, we can pass updatedTotal. It also needs currency so let's write usd. We also need to mention the PaymentMethodTypes, and as of now, we are only supporting cards, so let's make a new list of string, and mention the card. Although there are plenty of options to choose from, we will keep it simple for this course.

Start a new discussion. All notification go to the author.