This video is available to students only

Creating Payments Controller

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

Creating payments controller#

Let's create an endpoint now for our payments. Inside controllers, we need a new one which will be called PaymentsController. This will derive from our Base Controller like always. Let's create a constructor and pass PaymentService, StoreContext and IMapper. Let's import it and initialize field from parameter. We can start creating the endpoints now. We can start with HttpPost request because we will be creating a new payment intent. Let's authorize this request as well because we only want logged-in users to be able to purchase courses.

Let's write a function which will return BasketDto. We are returning BasketDto because we want to store some information with the client because the client secret information will be used to make the payment without interacting with our API. Let's call this method PaymentIntentAsync. Let's import Task, ActionResult and BasketDto. Inside, we will retrieve the basket; we can use the same Extract Basket method here. Let's copy and paste it here. Let's pass User.Identity.Name. We know the user is available because this method is Authorized so we don't need to make it optional, but basket can be empty. If it is, we wll return NotFound error with new APIResponse 404.

We need the intent now so we can use await paymentService.PaymentIntentAsync and pass the basket. At this stage, we want the intent because this is what our PaymentService is doing. If intent doesn't return, we won't be able to make the payment so we can check if intent is null, then we can return BadRequest and pass new APIResponse with 400 status and with title, Problem creating the payment intent. Now we want to return the basket with the PaymentIntentId, so we can write basket.PaymentIntentId is equal to basket.PaymentIntentId if it already exists; otherwise, we can set it to intent dot Id. Same goes for the basket dot ClientSecret. If basket.ClientSecret is null, it will be intent.ClientSecret. Let's update the basket using context.Update. Let's check if saving this was successful.

Let's now put result be equal to context.SaveChangesAsync and check if it's more than zero. If result is false, we will return BadRequest with new api response 400 and message, Problem updating basket with intent. Finally, if everything is successful, let's return the basket using automapper.map from Basket to BasketDto and pass the basket. We also need to make changes to the BasketDto. Let's add PaymentIntentId of type string and ClientSecret of type string.

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