create an endpoint to process a credit card sale including customer information and return a response in csharp

To create an endpoint to process a credit card sale, you can follow the below steps:

  1. Create a new Web API project in Visual Studio.

  2. Install the Stripe payment processing library via NuGet.

    main.cs
       Install-Package Stripe
    
    26 chars
    2 lines
  3. Add the following code in your Web API controller method:

     using Stripe;
    
     [HttpPost]
     public IHttpActionResult ProcessCreditCardSale([FromBody] Customer customer)
     {
         var options = new ChargeCreateOptions
         {
             Amount = 1000,
             Currency = "usd",
             Source = customer.Token
         };
    
         var service = new ChargeService();
         Charge charge = service.Create(options);
    
         if (charge.Status == "succeeded")
         {
             return Ok("Payment processed successfully.");
         }
         else
         {
             return BadRequest("Payment processing failed.");
         }
     }
    
    532 chars
    25 lines
  4. In the above code, the ProcessCreditCardSale endpoint is created with POST method that receives the customer information in the request body. The Stripe payment processing library is used to create a new charge for the provided credit card token. Once the payment is processed by Stripe, the response is checked for its status.

  5. Finally, you can start debugging your application and test the API endpoint by calling it with the customer information.

gistlibby LogSnag