Web Development

How to Integrate Authorize.Net Payment Gateway in a MERN Application

Introduction

If you’re building an eCommerce or service-based platform using the MERN (MongoDB, Express, React, Node.js) stack, integrating a secure and reliable payment gateway is crucial. One of the best choices for accepting online payments is Authorize.Net, a widely trusted payment gateway that provides secure transactions with advanced fraud protection.

In this guide,(Integrate Authorize.Net in MERN) I’ll walk you through the step-by-step process of integrating Authorize.Net into your MERN stack application. By the end, you’ll have a working payment system that allows users to make transactions seamlessly.

Step 1: Set Up an Authorize.Net Developer Account

Before you begin coding, you need to create a sandbox account on Authorize.Net for testing.

  1. Go to Authorize.Net Developer and sign up for a sandbox account.
  2. After signing up, note down your API Login ID and Transaction Key from the dashboard.
  3. Ensure you switch your account to sandbox mode for testing.

Step 2: Install Required Dependencies

To integrate Authorize.Net in your MERN app, you’ll need the official Authorize.Net SDK. Install it in your Node.js backend by running:

npm install authorizenet dotenv cors express body-parser

These packages help with API requests, environment variables, and handling CORS policies.

Step 3: Configure the Backend (Node.js & Express)

Now, let’s set up the backend to process payments.

Create a .env File

First, store your API credentials securely in a .env file:

API_LOGIN_ID=your_login_id_here
TRANSACTION_KEY=your_transaction_key_here

Create an Express Server

Now, create a server.js file and add the following code:

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { APIContracts, APIControllers } = require('authorizenet');

const app = express();
app.use(cors());
app.use(bodyParser.json());

const API_LOGIN_ID = process.env.API_LOGIN_ID;
const TRANSACTION_KEY = process.env.TRANSACTION_KEY;

app.post('/api/payment', (req, res) => {
    const { cardNumber, expDate, cvv, amount } = req.body;

    const merchantAuth = new APIContracts.MerchantAuthenticationType();
    merchantAuth.setName(API_LOGIN_ID);
    merchantAuth.setTransactionKey(TRANSACTION_KEY);

    const creditCard = new APIContracts.CreditCardType();
    creditCard.setCardNumber(cardNumber);
    creditCard.setExpirationDate(expDate);
    creditCard.setCardCode(cvv);

    const paymentType = new APIContracts.PaymentType();
    paymentType.setCreditCard(creditCard);

    const transactionRequest = new APIContracts.TransactionRequestType();
    transactionRequest.setTransactionType(APIContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION);
    transactionRequest.setAmount(amount);
    transactionRequest.setPayment(paymentType);

    const createRequest = new APIContracts.CreateTransactionRequest();
    createRequest.setMerchantAuthentication(merchantAuth);
    createRequest.setTransactionRequest(transactionRequest);

    const ctrl = new APIControllers.CreateTransactionController(createRequest);
    ctrl.execute(() => {
        const apiResponse = ctrl.getResponse();
        const response = new APIContracts.CreateTransactionResponse(apiResponse);

        if (response && response.getMessages()) {
            res.json({ success: true, message: "Transaction Successful!", response });
        } else {
            res.json({ success: false, message: "Transaction Failed!" });
        }
    });
});

app.listen(5000, () => console.log('Server running on port 5000'));

This backend handles payment requests, processes credit card transactions, and sends responses accordingly.

Step 4: Set Up the Frontend (React.js)

Now, let’s create a simple payment form in React to collect user payment details.

Install Axios

Run the following command in your React project to make API requests:

npm install axios

Create a Payment Component

Create a PaymentForm.js file and add this code:

import React, { useState } from 'react';
import axios from 'axios';

const PaymentForm = () => {
    const [cardNumber, setCardNumber] = useState('');
    const [expDate, setExpDate] = useState('');
    const [cvv, setCvv] = useState('');
    const [amount, setAmount] = useState('');
    const [message, setMessage] = useState('');

    const handlePayment = async (e) => {
        e.preventDefault();
        try {
            const response = await axios.post('http://localhost:5000/api/payment', {
                cardNumber, expDate, cvv, amount
            });
            setMessage(response.data.message);
        } catch (error) {
            setMessage('Payment Failed');
        }
    };

    return (
        <div>
            <h2>Make a Payment</h2>
            <form onSubmit={handlePayment}>
                <input type="text" placeholder="Card Number" value={cardNumber} onChange={(e) => setCardNumber(e.target.value)} required />
                <input type="text" placeholder="Expiry Date (MMYY)" value={expDate} onChange={(e) => setExpDate(e.target.value)} required />
                <input type="text" placeholder="CVV" value={cvv} onChange={(e) => setCvv(e.target.value)} required />
                <input type="text" placeholder="Amount" value={amount} onChange={(e) => setAmount(e.target.value)} required />
                <button type="submit">Pay Now</button>
            </form>
            <p>{message}</p>
        </div>
    );
};

export default PaymentForm;

This component collects payment details and sends them to the backend for processing.

Step 5: Test the Payment System

  1. Start your backend:
node server.js

2. Start your React frontend:

npm start

3. Enter test card details from Authorize.Net’s test credentials and submit the form.

4. Check the console/logs for the transaction response.

    Step 6: Move to Production

    Once testing is complete, switch to the live API Login ID and Transaction Key, and update your frontend to call the live API endpoint. Also, make sure your server is secured using HTTPS before processing real transactions.

    Integrating Authorize.Net with a MERN application ensures smooth and secure online transactions. This step-by-step guide covered everything from setting up a sandbox account to handling payments via Node.js and React.

    If you’re looking for professional web development assistance, CodeHunger provides expert solutions for secure and scalable applications.

    Related Articles

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Back to top button