TypeScript React 앱에 Juspay를 통합하기 위한 간단한 가이드

DDD
풀어 주다: 2024-09-18 19:37:10
원래의
400명이 탐색했습니다.

이 가이드는 결제 프로세스의 프런트엔드 및 백엔드 부분 모두에 대해 TypeScript를 사용하여 Juspay를 React 앱에 통합하는 방법에 대한 단계별 지침을 제공합니다.

전제 조건

Juspay에 대해 다음 자격 증명이 있는지 확인하세요.

  • 판매자ID
  • 클라이언트 ID
  • API 키

통합 흐름

Juspay를 이용한 결제 통합 흐름은 다음과 같습니다.

Simple Guide to Integrate Juspay in Your TypeScript React App

TypeScript 통합 단계

1. 결제 세션 생성(TypeScript의 서버측)

TypeScript와 함께 Node.js/Express를 사용하여 Juspay의 API를 사용하여 결제 세션을 생성하세요.

응답을 입력하려면 TypeScript PaymentSession 인터페이스를 생성하세요.

interface PaymentSession {
  payment_link: string;
  order_id: string;
  status: string;
}
로그인 후 복사

세션 생성을 위한 TypeScript 코드:

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 인터페이스는 세션 응답의 유형 안전성을 보장합니다.
  • TypeScript의 유형 어설션은 정확한 오류 처리(오류를 오류로 표시)를 보장합니다.

2. React 클라이언트(TypeScript)에서 결제 시작

React 클라이언트에서 useEffect 후크와 API 요청용 Axios를 사용하여 결제 프로세스를 시작하는 구성 요소를 만듭니다.

세션 응답에 대한 인터페이스를 정의합니다.

interface PaymentSession {
  payment_link: string;
  order_id: string;
}
로그인 후 복사

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>Initiate Payment</h1>
      <button onClick={initiatePayment}>Pay Now</button>
      {paymentUrl && (
        <div>
          <a href={paymentUrl} target="_blank" rel="noopener noreferrer">
            Complete Payment
          </a>
        </div>
      )}
    </div>
  );
};

export default PaymentPage;
로그인 후 복사

이 코드에서는:

  • PaymentSession은 백엔드 응답의 예상 구조를 보장합니다.
  • initiatePayment 함수는 결제 시작 요청을 보내고 응답을 처리합니다.

3. 반품URL 처리 및 결제현황 확인

결제 후 다시 리다이렉트 되는 경우 결제현황을 확인하고 표시해야 합니다.

결제 상태에 대한 TypeScript 인터페이스:

interface PaymentStatus {
  status: string;
  order_id: string;
  amount: number;
}
로그인 후 복사

결제 상태를 처리하기 위한 React 구성요소:

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>Payment Status</h1>
      {paymentStatus ? (
        <p>Payment Status: {paymentStatus}</p>
      ) : (
        <p>Checking payment status...</p>
      )}
    </div>
  );
};

export default PaymentStatusPage;
로그인 후 복사

이 구성요소의 내용:

  • 결제 상태를 확인하려면 order_id를 백엔드로 보냅니다.
  • 백엔드는 Juspay API의 응답을 기반으로 상태를 반환해야 합니다.

4. TypeScript로 웹훅 처리(백엔드)

Juspay는 결제 상태 변경을 알리기 위해 웹훅을 보냅니다. TypeScript 환경에서 이를 처리하는 방법은 다음과 같습니다.

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. 200 OK(백엔드)로 Juspay에 응답합니다.

웹훅 알림 수신을 확인하려면 서버가 200 OK 상태를 반환해야 합니다.

app.post('/api/webhook', (req: Request, res: Response) => {
  // Acknowledge the webhook
  res.status(200).send('OK');
});
로그인 후 복사

결론

다음 단계를 따르고 클라이언트 측 코드와 서버 측 코드 모두에 TypeScript를 활용하면 Juspay를 React 앱에 효율적이고 안전하게 통합할 수 있습니다. TypeScript는 유형 안전성의 이점을 추가하여 오류를 줄이고 통합이 원활하도록 보장합니다.

  • 클라이언트 측: React 구성 요소를 사용하여 결제를 시작하고 상태를 확인합니다.
  • 서버 측: Node.js/Express 백엔드는 결제 세션, 상태 및 웹훅 알림을 처리합니다.

이 가이드는 TypeScript를 사용하여 Juspay를 최신 웹 스택에 통합하는 방법에 대한 전체 개요를 제공합니다.

위 내용은 TypeScript React 앱에 Juspay를 통합하기 위한 간단한 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!