Integrating Khalt Payment Gateway in a React/Next js website. A Step-By-Step Guide
2023-04-23
Integrating Khalti payment gateway in website can be challenging task for developers, but this is very important to accept the payment securely and conveniently. "Khalti" helps business to accept the the payment easily and securely.
In this blog post, we will walk through the process of
integrating Khalti, a popular payment gateway Nepal into a React or Next js website
. Before diving into some technical stuff, let's understand how khalti payment gateway works.- When a user visits merchant's website to make a purchase, a unique purchase_order_id should be generated in the merchant's system(developers should write methods or function for generating unique purchase_order_id).
- Then, merchant sends a payment request to Khalti, which includes purchase_order_id, amount in paisa and return_url
- The user is then redirected to Khalti e-payment portal to complete the payment process.
- Once the payment is made,
a callback is made to the return_url
Technical Stuff
To get started with integrating Khalti payment gateway in the website, you
need to have a merchant account
. If you don't have one, you can sign up for a test account at https://test-admin.khalti.com/. For production access, you can visit https://admin.khalti.com. Once you have a merchant account, you can use Khalti API to initiate payment request.To initiate the payment request, you have to
send a server-side POST request
.API endpoints
API Authorization
To authorize API request, you need to use AUTH key, which should be used in the Headers of the request in following format.
During testing you should obtain LIVE_SECRET_KEY from https://test-admin.khalti.com/ and for production environment you should use LIVE_SECRET_KEY from khalti.com.
Sample Request Payload
Note : Remember that for testing amount must not exceed more than Rs.10 (10000 paisa). All the above fields are not required to proceed the payment request. But payload must contain following:
- return_url
- website_url
- amount
- purchase_order_id
- purchase_order_name
Server Side Request to Khalti API for payment request
You must remember one thing that you have to send POST request from the Backend. A sample request is shown below.
Success Response
Once you get the payment_url after successful response,
send the payment_url as a response to the frontend.
Use the payment_url to navigate to the Khalti e-payment portal after receiving response from the api/backend.After redirecting to the Khalti e-payment portal, fill the necessary details like mobile number and MPIN.
After successful transaction or payment, Khalti will redirect the user to return_url provided by merchant system during request along with query params. Sample callback request is given below.
You can use the query params send by Khalti to confirm the payment.
Thanks !