Next.js Functions

 

International Payments in NEXT.js with Stripe

In today’s globalized world, businesses need to cater to customers from all corners of the globe. Whether you’re running an e-commerce store, a subscription service, or a digital marketplace, accepting international payments is crucial to expanding your customer base and increasing revenue. One of the most reliable and developer-friendly tools for handling online payments is Stripe, and when it comes to building modern web applications, NEXT.js is a popular choice.

International Payments in NEXT.js with Stripe

In this comprehensive guide, we’ll walk you through the process of implementing international payments in a NEXT.js application using Stripe. By the end of this tutorial, you’ll have a solid understanding of how to set up Stripe, handle currency conversions, and create a seamless payment experience for your global audience.

1. Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites in place:

1.1. Node.js and npm/yarn

You’ll need Node.js installed on your development machine. If you haven’t already, download and install it from the official Node.js website.

1.2. NEXT.js Application

Create a NEXT.js application if you haven’t already. You can do this using the following command:

bash
npx create-next-app my-next-app

1.3. Stripe Account

Sign up for a Stripe account at https://stripe.com/. Once you have an account, obtain your API keys from the Stripe dashboard.

2. Setting Up Stripe

Now that you have your development environment ready let’s set up Stripe in your NEXT.js application.

2.1. Install Stripe Dependencies

In your NEXT.js project directory, open a terminal and install the stripe package:

bash
npm install stripe
# or
yarn add stripe

2.2. Add Stripe API Keys

In your project directory, create a .env.local file to store your Stripe API keys. Add the following lines to the file:

plaintext
STRIPE_SECRET_KEY=your_secret_key_here
STRIPE_PUBLIC_KEY=your_public_key_here

Replace your_secret_key_here and your_public_key_here with your actual Stripe API keys. Make sure to keep these keys secret and never expose them in your client-side code.

2.3. Initialize Stripe

Now, let’s initialize Stripe in your NEXT.js application. Create a file called stripe.js in your project’s root directory and add the following code:

javascript
// stripe.js

import { loadStripe } from '@stripe/stripe-js';

const stripePromise = loadStripe(process.env.STRIPE_PUBLIC_KEY);

export default stripePromise;

This code initializes Stripe with your public key from the .env.local file.

3. Creating a Payment Page

With Stripe set up, it’s time to create a payment page in your NEXT.js application. This page will allow users to enter their payment information and complete transactions.

3.1. Create a New Page

Inside your project’s pages directory, create a new file called payment.js. This will be the payment page where users make their payments.

bash
touch pages/payment.js

3.2. Add Payment Form

In the payment.js file, you can create a basic payment form with fields for card details and a “Pay” button. Here’s an example:

jsx
// pages/payment.js

import { useEffect } from 'react';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import stripePromise from '../stripe';

function Payment() {
  useEffect(() => {
    // Initialize Stripe.js only once on component mount
    const stripe = loadStripe(process.env.STRIPE_PUBLIC_KEY);

    // You can add additional Stripe.js configuration here
  }, []);

  return (
    <div>
      <h1>Payment Page</h1>
      <Elements stripe={stripePromise}>
        {/* Your payment form components go here */}
      </Elements>
    </div>
  );
}

export default Payment;

In this example, we’re using the @stripe/react-stripe-js library to handle the payment form. We also load the Stripe.js instance using the stripePromise from the stripe.js file.

3.3. Create Payment Logic

Next, you’ll need to add the logic to handle payments when the user submits the form. You can use the useStripe and useElements hooks provided by Stripe to interact with the Stripe API. Here’s a simplified example:

jsx
// pages/payment.js

import { useEffect } from 'react';
import { Elements, useStripe, useElements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import stripePromise from '../stripe';

function Payment() {
  const stripe = useStripe();
  const elements = useElements();

  useEffect(() => {
    // Initialize Stripe.js only once on component mount
    const stripe = loadStripe(process.env.STRIPE_PUBLIC_KEY);

    // You can add additional Stripe.js configuration here
  }, []);

  const handlePayment = async (event) => {
    event.preventDefault();

    if (!stripe || !elements) {
      // Stripe.js has not yet loaded.
      // Make sure to disable form submission until Stripe.js has loaded.
      return;
    }

    // Handle payment processing here
    // You can create a PaymentIntent and confirm the payment
  };

  return (
    <div>
      <h1>Payment Page</h1>
      <Elements stripe={stripePromise}>
        <form onSubmit={handlePayment}>
          {/* Payment form fields */}
          {/* Card details, billing address, etc. */}
          <button type="submit">Pay</button>
        </form>
      </Elements>
    </div>
  );
}

export default Payment;

In the handlePayment function, you can use Stripe.js to create a PaymentIntent and confirm the payment when the user submits the form. This is where you can specify the amount, currency, and other payment details.

4. Handling Currency Conversion

When dealing with international payments, it’s essential to handle currency conversion properly. Stripe provides built-in support for multiple currencies, and you can specify the currency for each payment. However, you may also want to display prices in the user’s preferred currency and handle any necessary currency conversion on your end.

4.1. Fetch Exchange Rates

To handle currency conversion, you’ll need to fetch exchange rates from a reliable source. You can use a service like Open Exchange Rates or Fixer to obtain up-to-date exchange rate data.

4.2. Display Prices in User’s Currency

Once you have the exchange rate data, you can use it to display prices in the user’s preferred currency. You can do this on product pages or in the shopping cart. Here’s an example of how you might convert a price from a base currency to the user’s currency:

javascript
// Convert a price to the user's currency
function convertToUserCurrency(price, exchangeRate) {
  return (price * exchangeRate).toFixed(2);
}

4.3. Update Payment Amount

When the user proceeds to the payment page, make sure to pass the payment amount in the correct currency to Stripe. You can use the exchange rate to convert the price if needed.

jsx
// pages/payment.js

import { useEffect, useState } from 'react';
import { Elements, useStripe, useElements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import stripePromise from '../stripe';

function Payment() {
  const stripe = useStripe();
  const elements = useElements();
  const [exchangeRate, setExchangeRate] = useState(1.0);

  useEffect(() => {
    // Initialize Stripe.js only once on component mount
    const stripe = loadStripe(process.env.STRIPE_PUBLIC_KEY);

    // Fetch exchange rate data from your chosen source
    // Update the exchangeRate state with the fetched data
    // You can use a library like Axios or the Fetch API to make the request
    // For demonstration purposes, we'll use a mock exchange rate of 1.2
    const mockExchangeRate = 1.2;
    setExchangeRate(mockExchangeRate);

    // You can add additional Stripe.js configuration here
  }, []);

  const handlePayment = async (event) => {
    event.preventDefault();

    if (!stripe || !elements) {
      // Stripe.js has not yet loaded.
      // Make sure to disable form submission until Stripe.js has loaded.
      return;
    }

    // Calculate the payment amount in the user's currency
    const baseAmount = 100; // Amount in the base currency (e.g., USD)
    const userAmount = convertToUserCurrency(baseAmount, exchangeRate);

    // Create a PaymentIntent with the user's currency and amount
    const { paymentIntent, error } = await stripe.createPaymentIntent({
      amount: userAmount,
      currency: 'EUR', // Replace with the user's selected currency
    });

    if (error) {
      // Handle payment error
    } else {
      // Confirm the payment using paymentIntent.client_secret
      const result = await stripe.confirmCardPayment(paymentIntent.client_secret);

      if (result.error) {
        // Handle payment confirmation error
      } else {
        // Payment succeeded
      }
    }
  };

  // Convert a price to the user's currency
  function convertToUserCurrency(price, exchangeRate) {
    return (price * exchangeRate).toFixed(2);
  }

  return (
    <div>
      <h1>Payment Page</h1>
      <p>Total Amount: {convertToUserCurrency(100, exchangeRate)} EUR</p>
      <Elements stripe={stripePromise}>
        <form onSubmit={handlePayment}>
          {/* Payment form fields */}
          {/* Card details, billing address, etc. */}
          <button type="submit">Pay</button>
        </form>
      </Elements>
    </div>
  );
}

export default Payment;

In this example, we mock the exchange rate for demonstration purposes. In a real-world scenario, you would fetch the exchange rate data from your chosen source and update the exchangeRate state accordingly.

Conclusion

Implementing international payments in a NEXT.js application using Stripe is a crucial step in reaching a global audience and expanding your business. By following the steps outlined in this guide, you can create a seamless payment experience for customers worldwide, handle currency conversion, and ensure the security of their transactions.

Remember to keep your Stripe API keys secure, adhere to best practices for handling payments, and stay informed about any regulatory requirements for international transactions in your region. With the right setup and attention to detail, you can provide a top-notch payment experience that boosts customer trust and satisfaction.

Start integrating Stripe into your NEXT.js application today, and watch your business thrive on a global scale. Happy coding!

This comprehensive guide has walked you through the process of implementing international payments in a NEXT.js application using Stripe. We covered setting up Stripe, creating a payment page, and handling currency conversion. Now, you have the knowledge and tools to provide a seamless payment experience to customers from around the world.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Accomplished Senior Software Engineer with Next.js expertise. 8 years of total experience. Proficient in React, Python, Node.js, MySQL, React Hooks, and more.