Getting Payment Intent from the Server
In this lesson, we're going to make an API call to get payment intent from the server
Getting Payment Intent from the server#
Now that we know how our Checkout page looks like, let's start preparing the payment process. To make payment from our frontend, we need paymentIntentId and the clientSecret which we will receive from our server. Before that, let's make some changes to our basket model. We will add paymentIntendId of type string and clientSecret of type string as well. Both of them are optional so let's add a question mark.
client/src/models/basket.ts
export interface Basket {
clientId: string;
items: CourseItem[];
paymentIntentId?: string;
clientSecret?: string;
}
export interface CourseItem {
courseId: string;
title: string;
instructor: string;
image: string;
price: number;
}
Now let's go to the agent.ts
file and add another endpoint for Payments. We only have one endpoint and we can call it paymentIntent. We are going to make a post request with endpoint being payments and since it's a post request and we're not passing any body, let's add an empty object. Finally, let's export it. Now we need to make this request when the client is ready to make the payment. That happens when the client clicks on Checkout, which means that inside the CheckoutPage, whenever the component first renders, we will make this request.
Let's go to the CheckoutPage and import useEffect from react. Inside this hook, we can make the api call. We need to call agent.Payments.paymentIntent and then we will receive basket as a response, this time, with paymentIntentId and the clientSecret, so we can dispatch the setbasket function to set the new basket. We also need dispatch so let's initialize it with useAppDispatch. Let's log the error for now and put dispatch as a dependency.
This page is a preview of The newline Guide to Fullstack ASP.NET Core and React