Skip to Content

Stripe Payment using .NET 8 Core Microservice and React JS

#Stripe#ASP.NET Core#.Net 8 Core#Microservice#React.js#React Hooks

In this blog, we will walk through the process of integrating Stripe payments into a .NET 8 Core Microservice architecture with a React JS front-end. This will cover both the backend API for processing payments and the React component for capturing customer details and initiating payments.

Prerequisites

  1. Stripe Account: Sign up for a Stripe account.
  2. Stripe API Keys: Get your publishable and secret keys from the Stripe Dashboard.
  3. .NET 8 SDK: Ensure you have the latest version of the .NET 8 SDK installed.
  4. React JS: Basic knowledge of React JS and how to set up a React application.

Setting Up the .NET 8 Core Microservice

1. Create a New .NET 8 API Project

dotnet new webapi -n StripePaymentService
cd StripePaymentService

2. Install Stripe SDK

Add the Stripe NuGet package to your project:

dotnet add package Stripe.net --version 42.0.0

3. Configure Stripe in appsettings.json

In the appsettings.json file, add your Stripe secret key.

{
  "Stripe": {
    "SecretKey": "your-stripe-secret-key",
    "PublishableKey": "your-stripe-publishable-key"
  }
}

4. Setup Stripe Service in .NET 8 Core

In the Program.cs file, configure Stripe services:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.Configure<StripeSettings>(builder.Configuration.GetSection("Stripe"));

builder.Services.AddSingleton<IStripeClient, StripeClient>(sp =>
{
    var config = sp.GetRequiredService<IOptions<StripeSettings>>().Value;
    return new StripeClient(config.SecretKey);
});

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

5. Create a Stripe Payment Controller

Create a new controller named PaymentController.cs to handle the payment request.

[ApiController]
[Route("api/[controller]")]
public class PaymentController : ControllerBase
{
    private readonly IStripeClient _stripeClient;

    public PaymentController(IStripeClient stripeClient)
    {
        _stripeClient = stripeClient;
    }

    [HttpPost("create-payment-intent")]
    public async Task<IActionResult> CreatePaymentIntent([FromBody] PaymentIntentRequest request)
    {
        var options = new PaymentIntentCreateOptions
        {
            Amount = request.Amount,
            Currency = request.Currency,
            PaymentMethodTypes = new List<string> { "card" }
        };

        var service = new PaymentIntentService(_stripeClient);
        var paymentIntent = await service.CreateAsync(options);

        return Ok(new { clientSecret = paymentIntent.ClientSecret });
    }
}

public class PaymentIntentRequest
{
    public long Amount { get; set; }
    public string Currency { get; set; }
}

6. Test the API

You can test the API using Postman or another API testing tool. Send a POST request to https://localhost:5001/api/payment/create-payment-intent with the following JSON payload:

{
    "amount": 2000,
    "currency": "usd"
}

If successful, it will return a clientSecret which you will use in the front-end to complete the payment.


React JS Frontend Integration

1. Install Stripe React and Stripe.js

In your React project, install the necessary Stripe packages:

npm install @stripe/react-stripe-js @stripe/stripe-js

2. Configure Stripe in React

Set up the StripeProvider and Elements in your App.js:

import React from 'react';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import PaymentForm from './PaymentForm';

const stripePromise = loadStripe('your-publishable-key');

function App() {
  return (
    <Elements stripe={stripePromise}>
      <PaymentForm />
    </Elements>
  );
}

export default App;

3. Create Payment Form Component

Create a new component PaymentForm.js that will handle the payment process:

import React, { useState } from 'react';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';

const PaymentForm = () => {
  const [amount, setAmount] = useState(2000); // Amount in cents
  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async (event) => {
    event.preventDefault();
    const { error, paymentIntent } = await createPaymentIntent(amount);

    if (!error && stripe && elements) {
      const { error: stripeError } = await stripe.confirmCardPayment(paymentIntent.clientSecret, {
        payment_method: {
          card: elements.getElement(CardElement)
        }
      });

      if (stripeError) {
        console.error('Payment failed', stripeError);
      } else {
        console.log('Payment successful');
      }
    }
  };

  const createPaymentIntent = async (amount) => {
    const response = await fetch('https://localhost:5001/api/payment/create-payment-intent', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ amount, currency: 'usd' })
    });
    return await response.json();
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardElement />
      <button type="submit" disabled={!stripe}>Pay</button>
    </form>
  );
};

export default PaymentForm;

4. Test the Frontend

Run your React application and test the payment flow by entering card details such as:

  • Card Number: 4242 4242 4242 4242
  • Expiration Date: Any future date
  • CVC: Any 3-digit number

If everything is configured correctly, you should see a successful payment response in your browser.


Conclusion

Integrating Stripe payments with a .NET 8 Core Microservice and React JS is a powerful way to handle secure transactions. The combination of .NET for backend processing and React for handling frontend interactions ensures a smooth and efficient payment experience.

This blog demonstrated setting up a microservice, processing payments with Stripe, and building a frontend interface for users. Happy coding!

Praful's Newsletter 🚀

Join 3900+ Engineers to Level Up Your Skills!
Subscribe to my Software Engineering Deep Dive Series covering ReactJS, Redux, ASP.NET Core, and Clean Architecture. Get 1 insightful email each week to enhance your development journey.