Online retail or ecommerce, customer satisfaction, and instilling trust while collecting payment are key goals. Authorize.Net is popular due to its reliable, secure, and flexible payment gateway service. Next.js is a React framework used to build web applications and supports server-side rendering, static website generation, and similar features.
These technologies have set a high level for solid and scalable online payment solutions. This detailed blog will teach you how to authorize.Net integration with Next.js and provide a good payment experience for your users. We have implemented it with the authorized net test sandbox.
How is Authorize.Net applicable in Next.js?
Authorize.Net:
- Security: These are improved in Authorize.Net as they observe all the required standards of security when transactions are made, including PCI-DSS. It provides secure handling of a transaction and tools that help detect fraud.
- Server Reliability: Authorize.Net is well known for its high uptime and reliability, and also for effective payment activities, especially payment processing.
- Flexibility: Accommodates several payment options and currencies, expanding even the smallest businesses’ resources at their disposal.
Next.js:
- Performance: Unlike traditional client-side rendering, balanced with SSR and SSG, this framework is faster and SEO-friendly.
- Scalability: Businesses can develop applications on a large scale using Next.js, perfectly suited for developing businesses.
- Developer Experience: Built-in APIs and automatic code splitting among other building blocks help to ease the development and raise the efficiency.
Using these technologies helps to deliver a highly performant, safe, and scalable payment system for the ecommerce platform.
Prerequisites
Before you start implementing Authorize.Net in your Next.js application, you need to have:
- Authorize.Net Account: Go to Authorize.Net and register and set your account to Authorize.Net.
- Next.js Application: Set up a working Next.js application. If you don’t have one, you can create a new project using npx create-next-app.
- API Credentials: Obtain your API login ID and transaction key from the Authorize.Net Merchant Interface.
File Structure
Organizing your files effectively is key to maintaining a clean and manageable codebase. Here’s a recommended file structure for your Next.js project integrating Authorize.Net:
//my-nextjs-app
│
├── /components
│ ├── CheckoutForm.js
│
├── /pages
│ ├── /api
│ │ ├── authPaymentToken.js
│ ├── checkout.js
│
├── /public
│ ├── IFrameCommunicator.html
│
├── .env
├── package.json
├── next.config.js
├── README.md
How to Integrate Authorize.Net with Next.js?
Step 1: Create the API Route
In Next.js, API routes allow you to build server-side functionality within your application. Create an API route to interact with Authorize.Net and request a payment token.
File: pages/api/authPaymentToken.js
javascript
import axios from 'axios';
import axios from 'axios';
export default async function handler(req, res) {
if (req.method === 'POST') {
try {
const response = await axios.post(process.env.NEXT_PUBLIC_AUTHORIZENET_TOKEN_API_URL, {
getHostedPaymentPageRequest: {
merchantAuthentication: {
name: process.env.NEXT_PUBLIC_MERCHANT_AUTH_NAME,
transactionKey: process.env.NEXT_PUBLIC_MERCHANT_TRANSACTION_KEY,
},
transactionRequest: {
transactionType: 'authCaptureTransaction',
amount: req?.body?.dataPrice,
},
hostedPaymentSettings: {
setting: [
{
settingName: 'hostedPaymentReturnOptions',
settingValue: JSON.stringify({
showReceipt: false,
})
},
{
settingName: "hostedPaymentButtonOptions",
settingValue: JSON.stringify({
text: "Pay"
})
},
{
settingName: "hostedPaymentStyleOptions",
settingValue: JSON.stringify({
bgColor: "008401"
})
},
{
settingName: "hostedPaymentPaymentOptions",
settingValue: JSON.stringify({
cardCodeRequired: false,
showCreditCard: true,
showBankAccount: false
})
},
{
settingName: "hostedPaymentSecurityOptions",
settingValue: JSON.stringify({
captcha: false
})
},
{
settingName: "hostedPaymentShippingAddressOptions",
settingValue: JSON.stringify({
show: false,
required: false
})
},
{
settingName: "hostedPaymentBillingAddressOptions",
settingValue: JSON.stringify({
show: false,
required: false
})
},
{
settingName: "hostedPaymentCustomerOptions",
settingValue: JSON.stringify({
showEmail: false,
requiredEmail: false,
addPaymentProfile: true
})
},
{
settingName: "hostedPaymentOrderOptions",
settingValue: JSON.stringify({
show: true,
merchantName: "G and S Questions Inc."
})
},
{
settingName: "hostedPaymentIFrameCommunicatorUrl",
settingValue: JSON.stringify({
url: "yoursite/IFrameCommunicator.html"
})
}
]
}
}
}, {
headers: {
'Content-Type': 'application/json',
},
});
const token = response.data.token;
res.status(200).json({ token });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch client token' });
}
} else {
res.status(405).json({ message: 'Method not allowed' });
}
}
Explanation:
- axios.post: Sends a POST request to Authorize.Net’s API to request a payment token.
- process.env.AUTHORIZENET_API_URL: URL for the Authorize.Net API.
- process.env.MERCHANT_AUTH_NAME and process.env.MERCHANT_TRANSACTION_KEY: Your Authorize.Net credentials.
- req.body.dataPrice: The amount to be charged.
Security Considerations:
- Ensure that sensitive information like API keys is stored securely in environment variables.
- Validate and sanitize inputs to prevent any security vulnerabilities.
Step 2: Fetch the Token on the Frontend
On the front end, request the payment token from your API route and use it to display the Authorize.Net payment form.
File: pages/checkout.js
import { useEffect, useState } from 'react';
import Axios from 'axios';
const CheckoutPage = () => {
const [token, setToken] = useState(null);
const dataPrice = 100.00; // Example cart total
useEffect(() => {
Axios.post('/api/authPaymentToken', { dataPrice })
.then(response => setToken(response.data.token))
.catch(error => console.error('Error fetching token:', error));
}, [dataPrice]);
const handleButtonClick = () => {
document.getElementById('send_token').submit();
};
return (
<div>
<button onClick={handleButtonClick}>Pay Now</button>
<iframe
id="add_payment"
name="add_payment"
style={{ display: 'none' }}
></iframe>
<form
id="send_token"
method="post"
target="add_payment"
action={process.env.NEXT_PUBLIC_AUTHORIZE_NET_PAYMENT_TOKEN_URL}
>
<input type="hidden" name="token" value={token} />
</form>
</div>
);
};
export default CheckoutPage;
Explanation:
- useEffect: Fetches the payment token from your API route when the component mounts.
- handleButtonClick: Submits the payment form when the user clicks the payment button.
User Experience Considerations:
- Loading States: Implement loading states to inform users that the token is being fetched.
- Error Handling: Display user-friendly error messages if the token retrieval fails.
Step 3: Handle Payment Responses
To process the payment response, listen for messages from the iframe where the payment form is loaded. Update the pages/checkout.js to handle these messages.
File: pages/checkout.js
import { useEffect, useState } from 'react';
import Axios from 'axios';
const CheckoutPage = () => {
const [token, setToken] = useState(null);
const dataPrice = 100.00; // Example amount
useEffect(() => {
Axios.post('/api/authPaymentToken', { dataPrice })
.then(response => setToken(response.data.token))
.catch(error => console.error('Error fetching token:', error));
}, [dataPrice]);
const handleButtonClick = () => {
document.getElementById('send_token').submit();
};
useEffect(() => {
const handleMessage = (event) => {
if (event.origin !== 'https://test.authorize.net') return;
if (event.data.includes('response=')) {
const responseData = event.data.split('response=')[1];
try {
const jsonObject = JSON.parse(responseData);
const transId = jsonObject?.transId;+
if (transId) {
console.log('Transaction ID:', transId);
}
} catch (error) {
console.error('Error parsing response:', error);
}
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, []);
return (
<div>
<button onClick={handleButtonClick}>Pay Now</button>
<iframe
id="add_payment"
name="add_payment"
style={{ display: 'none' }}
></iframe>
<form
id="send_token"
method="post"
target="add_payment"
action={process.env.NEXT_PUBLIC_AUTHORIZE_NET_PAYMENT_TOKEN_URL}
>
<input type="hidden" name="token" value={token} />
</form>
</div>
);
};
export default CheckoutPage;
Explanation:
- window.addEventListener(‘message’, handleMessage): Sets up an event listener for messages from the iframe.
- event.data.includes(‘response=’): Checks if the message contains payment response data.
Security Considerations:
- Validate the origin of the message to ensure it’s from a trusted source.
- Handle and log errors appropriately to debug issues and ensure a smooth payment process.
Step 4: Set Up IFrame Communicator
To communicate between the iframe and the parent window, create an HTML file that listens for messages and posts them to the parent window.
File: public/IFrameCommunicator.html
<!DOCTYPE html>
<html>
<head><title>Iframe Communicator</title></head>
<body>
<script>
function receiveMessage(event) {
if (event.origin === 'https://test.authorize.net') {
window.top.postMessage(event.data, '*');
}
}
window.addEventListener('message', receiveMessage);
</script>
</body>
</html>
Explanation:
- receiveMessage: This is a function that listens for messages from the iframe and forwards them to the parent window.
- event.origin: To ensure messages are only processed from the Authorize.Net domain.
Security Considerations:
- Ensure the communicator only processes messages from trusted sources to prevent cross-site scripting (XSS) attacks.
Environment Variables
Save sensitive information like API keys, secret keys, etc., into the.env file. In the root of your project, create a.env.local file and put:
NEXT_PUBLIC_AUTHORIZENET_API_URL=https://api2.authorize.net/xml/v1/request.api
NEXT_PUBLIC_MERCHANT_AUTH_NAME=your_merchant_auth_name
NEXT_PUBLIC_MERCHANT_TRANSACTION_KEY=your_merchant_transaction_key
NEXT_PUBLIC_AUTHORIZE_NET_PAYMENT_TOKEN_URL=https://accept.authorize.net/payment/payment
Security Considerations:
- Do not commit.env to your version control and do not expose other private keys (put this file into the.gitignore file if applicable).
- Make use of development tools or services that help in managing environment variables when in production.
Benefits of Authorize.Net Integration with Next.js
- Robust Security: The payment data is sent to the iframe hosted by Authorize.Net, which enables you to reduce the PCI-DSS scope and risk of gaining customer-sensitive information
- Again Faster: Distressing evolution page load times are high, and end-user courtesy is free with next.js using server-side rendering and static site generation.
- Scalability: Authorize.Net and Next.js are orientated towards adequate traffic and growth and remain efficient according to demand.
- Flexibility: The integration makes it so that as your business grows and changes, so do the payment capabilities, and to fit those changes into your business, it’s more flexible.
- Compliance: Using Authorize.Net helps ensure compliance with payment processing regulations, giving both merchants and customers confidence in transaction security.
Integrate Authorize.Net with Next.js for Secure Online Payments
Authorize.Net integration with Next.js provides a powerful and secure solution for handling online payments. By following this guide, you can set up a payment system that uses the strengths of the above-mentioned technologies. With Authorize.Net’s reliable payment processing and Next.js’s performance and scalability features, you can deliver a smooth payment experience that meets your customer’s needs and supports your business’s growth.
If you’re planning to build a new ecommerce site or revamp an existing one, this integration ensures that your payment processing is secure, efficient, and user-friendly. If you need expert advice, on Adobe commerce development or Bigcommerce development Services get in touch with Klizer to help you implement the perfect solution for your online business.
Reference :
https://developer.authorize.net/api/reference/features/accept-hosted.html