This guide provides step-by-step instructions on how to integrate Juspay into a React app using TypeScript for both front-end and back-end parts of the payment process.
Prerequisites
Ensure you have the following credentials for Juspay:
- Merchant ID
- Client ID
- API Key
Integration Flow
Here is the flow of payment integration using Juspay:
Steps for TypeScript Integration
1. Create Payment Session (Server-Side in TypeScript)
Use Node.js/Express with TypeScript to create the payment session using Juspay's API.
Create a TypeScript PaymentSession interface to type your response:
interface PaymentSession { payment_link: string; order_id: string; status: string; }
TypeScript code for creating a session:
import axios from 'axios'; import base64 from 'base-64'; import { Request, Response } from 'express'; const createSession = async (req: Request, res: Response) => { const apiKey = 'your_api_key'; const authHeader = base64.encode(`${apiKey}:`); try { const response = await axios.post<paymentsession>( 'https://api.juspay.in/session', { customer_id: 'customer_id_here', amount: 10000, // Amount in paise (100 INR) currency: 'INR', }, { headers: { Authorization: `Basic ${authHeader}`, }, } ); res.json(response.data); } catch (error) { res.status(500).json({ error: (error as Error).message }); } }; export default createSession; </paymentsession>
In this code:
- PaymentSession interface ensures type safety for the session response.
- TypeScript's type assertions ensure accurate error handling (error as Error).
2. Initiate Payment from React Client (TypeScript)
In the React client, create a component that initiates the payment process using a useEffect hook and Axios for API requests.
Define an interface for the session response:
interface PaymentSession { payment_link: string; order_id: string; }
Component in TypeScript:
import React, { useState } from 'react'; import axios from 'axios'; const PaymentPage: React.FC = () => { const [paymentUrl, setPaymentUrl] = useState<string null>(null); const initiatePayment = async () => { try { const response = await axios.post<paymentsession>('/api/create-session', { amount: 10000, // Amount in paise (100 INR) currency: 'INR', customer_id: 'your-customer-id', }); setPaymentUrl(response.data.payment_link); } catch (error) { console.error('Error initiating payment:', error); } }; return ( <div> <h1 id="Initiate-Payment">Initiate Payment</h1> <button onclick="{initiatePayment}">Pay Now</button> {paymentUrl && ( <div> <a href="%7BpaymentUrl%7D" target="_blank" rel="noopener noreferrer"> Complete Payment </a> </div> )} </div> ); }; export default PaymentPage; </paymentsession></string>
In this code:
- PaymentSession ensures the expected structure of the response from the backend.
- The initiatePayment function sends the request to initiate the payment and handles the response.
3. Handling Return URL and Checking Payment Status
When the user is redirected back after the payment, you need to check the payment status and display it.
TypeScript Interface for Payment Status:
interface PaymentStatus { status: string; order_id: string; amount: number; }
React Component to Handle Payment Status:
import React, { useEffect, useState } from 'react'; import axios from 'axios'; const PaymentStatusPage: React.FC = () => { const [paymentStatus, setPaymentStatus] = useState<string null>(null); useEffect(() => { const checkPaymentStatus = async () => { try { const response = await axios.get<paymentstatus>('/api/check-status', { params: { order_id: 'your-order-id' }, }); setPaymentStatus(response.data.status); } catch (error) { console.error('Error fetching payment status:', error); } }; checkPaymentStatus(); }, []); return ( <div> <h1 id="Payment-Status">Payment Status</h1> {paymentStatus ? ( <p>Payment Status: {paymentStatus}</p> ) : ( <p>Checking payment status...</p> )} </div> ); }; export default PaymentStatusPage; </paymentstatus></string>
In this component:
- You send the order_id to your backend to check the payment status.
- The backend should return the status based on the response from Juspay's API.
4. Handling Webhooks with TypeScript (Backend)
Juspay will send a webhook to notify you of payment status changes. Below is how to handle this in a TypeScript environment.
import { Request, Response } from 'express'; interface JuspayWebhook { order_id: string; status: string; amount: number; currency: string; } const handleWebhook = (req: Request, res: Response) => { const paymentUpdate: JuspayWebhook = req.body; console.log('Payment Update Received:', paymentUpdate); // Process the payment update (e.g., update your database) // Respond to Juspay to confirm receipt res.status(200).send('Webhook received'); }; export default handleWebhook;
5. Respond to Juspay with a 200 OK (Backend)
To confirm receipt of the webhook notification, your server should return a 200 OK status:
app.post('/api/webhook', (req: Request, res: Response) => { // Acknowledge the webhook res.status(200).send('OK'); });
Conclusion
By following these steps and leveraging TypeScript for both client and server-side code, you can integrate Juspay into your React app efficiently and safely. TypeScript adds the benefit of type safety, reducing errors and ensuring your integration is smooth.
- Client Side: You initiate payment using React components and check the status.
- Server Side: Your Node.js/Express backend handles the payment session, status, and webhook notifications.
This guide provides a complete overview of how to integrate Juspay into a modern web stack using TypeScript.
The above is the detailed content of Simple Guide to Integrate Juspay in Your TypeScript React App. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
