Mastering Next JS E-Commerce: Payment Integration with Midtrans

riky_adiputra_88468e32c5

Riky Adi Putra

Posted on September 4, 2024

Mastering Next JS E-Commerce: Payment Integration with Midtrans

Midtrans is a leading payment service provider in Indonesia that enables businesses to accept online payments easily and securely. With various payment methods offered, including credit cards, bank transfers, and e-wallets, Midtrans provides flexibility for customers to complete their transactions. As part of Gojek, Midtrans has been trusted by many large and small companies to manage their payments.
Benefits of Using Midtrans

  • Diverse Payment Methods: Midtrans supports various payment methods, allowing customers to choose the most convenient way for them. This includes credit cards, bank transfers, and payments through e-wallet applications like OVO and Gopay.
  • Transaction Security: Midtrans employs advanced encryption technology and security monitoring to protect customer payment data. This provides a sense of security for users when conducting transactions.
  • Ease of Integration: Midtrans provides comprehensive documentation and an SDK (Software Development Kit) that makes it easy for developers to integrate payment services into their applications.
  • Reporting and Analytics: Midtrans offers reporting features that help business owners monitor transactions and sales performance, facilitating strategic decision-making.
  • Good Customer Support: The Midtrans support team is ready to assist you with any questions or issues that may arise during the use of their services.

Why Choose Midtrans?
Choosing Midtrans as your payment service provider offers many advantages, especially in terms of convenience and security. With easy integration and responsive support, Midtrans allows you to focus on developing your business without worrying about payment issues. Furthermore, with easy access to various payment methods, you can enhance user experience and sales potential.
OK, we will use midtrans in our e-commerce application, we are going to set up the payment gateway using Midtrans. This is the final overview of the project :

Image description
Image description
Image description
Image description
Image description
Image description
Image description
Image description

That’s the overview of the project later on. Alright, let’s dive straight into the workflow of Midtrans itself. Let’s gooo!

Image description

Actually, the concept of Midtrans itself is quite easy to understand. Here, I present a conceptual diagram that consists of just 3 steps in the Midtrans workflow.

In the first step, the client/web posts data to Midtrans, and Midtrans imposes certain required rules when posting data, such as the need for a Server Key, order_id, and gross_amount.

Image description

Then, in the second step, Midtrans responds by providing a token, which is used to display the payment layout from Midtrans itself in the third step.

The next step is to set up the Midtrans account to obtain the Client & Server Key.

Image description

First, visit ‘https://dashboard.midtrans.com/register' and register if you are new to Midtrans. If you have used it before, choose the login option.

Image description

The first screen that will appear after successfully registering or logging in is shown below.

Image description

Then, in the Environment section, please change it to Sandbox

Image description

Then, in the settings section, select the access key menu to obtain the Client and Server Key.

Image description

Congratulations, you have obtained your Client and Server Keys. Each key can be copied and pasted into our project, which we will save in a .env file

Image description

Okay, we have obtained the Client and Server Keys in our Midtrans accounts. The next steps will take us into the coding realm. Let’s gooo!

If you have reached this stage, I congratulate you if you have completed the first stage of integration with Midtrans, I hope your enthusiasm is still maintained because we will enter the most exciting part, namely the coding part. Don’t be too long, come on.

First, clone the repository using the following link: ‘https://github.com/RikyAdiPutra/rm/tree/bf3989645dd93d7eb93802d108e3e993ec9d1b68'." Then, we will start with coding the backend first. Let’s gooo

Image description

First of all, create a folder api/payment/route.js in this file, we will setup the back end needs to get the token

Image description
Then we create a POST function which is an http request method which is marked with the method name using all capital letters

Image description
After that, don’t forget to import NextResponse to control the HTTP response, then in the POST method function we call NextResponse with the response results in json form where there is a message property with the value “MIDTRANS” then run the project with npm run dev

Image description
To test whether the POST method is working correctly, we use a Thunder Client extension where we can test the API here. The first step is to change the method option to POST, then in the second step we enter the URL which leads to the api/payment folder. then in the third step we click the send button then in the fourth step we get a response that matches what we have created in the api/payment/route.js folder. Congratulations if you have reached this stage you have succeeded in creating a simple POST api which will we will use it later to get the midtrans token

Image description
Oh yes, if you don’t have the Thunder Client extension, you can install it in the extension menu then search for Thunder Client

Image description
The next step is to install the Midtrans client to integrate the backend application with the Midtrans payment service.

Image description
If it has been installed, you can see in the package.json file the dependencies midtrans-client

Image description
We go back to the route.js file, after we install midtrans-client, we first import midtrans from midtrans-client then we create a snap variable which contains the value of a new instance of the Snap class which allows us to create transactions , get payment tokens, etc. then in it there are 3 properties, namely isProduction, which determines whether to use the API in production mode or not because we are using mode sandbox, so we fill in isProduction to false then the serverKey and clientKey are obtained from the midtrans account that we created at the beginning which we will save later. in .env

Image description
We create an .env file where in it we will store the server and client keys from the Midtrans account that we created at the beginning

Image description

Image description
Now that we’ve created the snap variable, we will move on to the POST method, which we’ll edit to obtain the token. Earlier, we were just testing the method, but now we’ll try a real implementation.

In the POST function, we will use an async function that accepts the req parameter. Inside it, we’ll create a parameter variable that includes item_details and transaction_details. Then, we’ll create a token variable to store the token obtained later, using createTransactionToken with parameter as its argument. Finally, we’ll return the token using NextResponse.

Image description
After that, don’t forget to run the project with npm run dev.

Image description
Back to Thunder Client, as usual, change the method to POST, then enter the URL pointing to /api/payment and press send. You’ll receive the token as a result. Yayyy, congratulations, you've successfully obtained the token!

Image description
Earlier, we used static data in the POST method function, but this time, we’ll use dynamic data, where the data will be received from the front-end application. We will modify the code as shown below.

First, we create a data variable, which will be obtained from the front-end. Then, in the next line, we perform a check: if the data is empty, it will result in an error. Next, I create a variable itemDetails, which contains the data received from the front-end. We iterate over the data using the map method and return an object with five properties: key, id, name, price, and quantity.

Now, if you look at one of the properties, price, I'm using a built-in function from Lodash. You can import Lodash first by using import _ from 'lodash'. I used the ceil function, which is used to round numbers up (ceiling). Then, I created another variable, grossAmount, where I used another Lodash function called sumBy. This function is used for summing values, in this case, multiplying price by quantity, which is taken from the itemDetails variable.

In the final variable, I included two properties: item_details, with its value being the itemDetails variable, and transaction_details, which contains order_id — where I used Lodash’s random function — and gross_amount, which is taken from the grossAmount variable.

Finally, I created another variable to generate a token using the createTransactionToken method. This method is used in Midtrans integration to create a transaction token, which takes a parameter argument — a collection of data — and then returns the token using NextResponse.json({ token }).

Image description
Let’s go back to Thunder Client. We’ll manually test it by entering the data, as shown in the example below. After entering the data in the body section, change the method to POST, and set the URL to /api/payment. Then, click send, and you will receive the token.

Image description
If you are already at this stage, congratulations, you have completed the second stage of midtrans integration, you have succeeded in creating the back-end code, keep up the enthusiasm because in one more stage you will complete the integration and will have an application that can have payment features, which is cool, you know, let’s go to the next stage

Image description
First, let’s create a button that will later be used to POST data from the front-end. For now, we’ll keep it simple by just logging ‘test’ to the console which will be used for the checkout button

Image description

Image description
Then, in the layout.js file, we import Script from next/script, which is used to load and manage JavaScript scripts from Midtrans that are necessary for displaying and processing payments on the front-end of the application. This component accepts two props: src and data-client-key. The data-client-key is loaded from the variable in the .env file we created earlier, and the src is used to load the snap.js library from Midtrans.

Image description
Then we create a variable called data where we loop through the cart (which is a state management using Zustand; this cart is used to store data). I perform the iteration using the map method, where I return each property, namely id, name, image, price, and quantity. For the price property, I use the parseInt method to convert it to an integer and multiply it by 16,000.

Image description
Then, in the handleCheckout function, I will post the data to /api/payment with the data in the second argument. When the data is successfully posted, it will return res.data.data. If there is an error, it will display the error in the console.log. The window.snap.pay(response) is intended to show the payment layout from Midtrans.

Image description
Now, let’s open the website (I will select 2 items)

Image description

Image description

Image description

Image description
Click the checkout button

Image description
Here, I will choose to use BCA VA, then copy the VA number

Image description

Image description

Image description
Then visit https://simulator.sandbox.midtrans.com/ to test the payment integration without using real transactions. In the Virtual Account section, select BCA VA, then enter the VA number in the Virtual Account Number field, and click inquire.

Image description

Image description

Image description
Image description
The final view on the front end for the payment.

Image description

Congratulations! If you have reached this stage, it means you have successfully created an application that is integrated with payment partners like Midtrans.

If you want to see the final result of the code, you can access it here: https://github.com/RikyAdiPutra/rm. If you want to see the live website, you can access it here: my-commerce-peach.vercel.app.

See you in the next article!

💖 💪 🙅 🚩
riky_adiputra_88468e32c5
Riky Adi Putra

Posted on September 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related