Как написать полный код интеграции платёжного модуля (Stripe/ЮKassa) для React-приложения?

Интеграция платёжного модуля в React-приложение — задача, требующая внимания к безопасности, UX и серверной части. Рассмотрим оба варианта.

## Интеграция Stripe в React

### 1. Установка зависимостей
bash
npm install @stripe/stripe-js @stripe/react-stripe-js

### 2. Серверная часть (Node.js/Express)
js
const express = require(‘express’);
const stripe = require(‘stripe’)(process.env.STRIPE_SECRET_KEY);
const app = express();
app.use(express.json());

app.post(‘/create-payment-intent’, async (req, res) => {
const { amount, currency } = req.body;
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: currency || ‘usd’,
});
res.json({ clientSecret: paymentIntent.client_secret });
});

app.listen(4000);

### 3. React-компонент оплаты
jsx
import React, { useState, useEffect } from ‘react’;
import { loadStripe } from ‘@stripe/stripe-js’;
import { Elements, CardElement, useStripe, useElements } from ‘@stripe/react-stripe-js’;

const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);

function CheckoutForm({ amount }) {
const stripe = useStripe();
const elements = useElements();
const [clientSecret, setClientSecret] = useState(»);
const [message, setMessage] = useState(»);

useEffect(() => {
fetch(‘/create-payment-intent’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ amount }),
})
.then(res => res.json())
.then(data => setClientSecret(data.clientSecret));
}, [amount]);

const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) return;

const result = await stripe.confirmCardPayment(clientSecret, {
payment_method: { card: elements.getElement(CardElement) },
});

if (result.error) {
setMessage(result.error.message);
} else if (result.paymentIntent.status === ‘succeeded’) {
setMessage(‘Оплата прошла успешно!’);
}
};

return (


{message &&

{message}

}

);
}

export default function StripePayment() {
return (

);
}

## Интеграция ЮKassa в React

### 1. Серверная часть (Node.js)
js
const { YooCheckout } = require(‘@a2seven/yoo-checkout’);
const checkout = new YooCheckout({
shopId: process.env.YOOKASSA_SHOP_ID,
secretKey: process.env.YOOKASSA_SECRET_KEY,
});

app.post(‘/create-yookassa-payment’, async (req, res) => {
const { amount, description } = req.body;
const payment = await checkout.createPayment({
amount: { value: amount, currency: ‘RUB’ },
confirmation: { type: ‘redirect’, return_url: ‘https://yoursite.com/success’ },
description,
capture: true,
});
res.json({ confirmationUrl: payment.confirmation.confirmation_url });
});

### 2. React-компонент для ЮKassa
jsx
import React from ‘react’;

export default function YooKassaPayment({ amount, description }) {
const handlePay = async () => {
const res = await fetch(‘/create-yookassa-payment’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ amount, description }),
});
const data = await res.json();
window.location.href = data.confirmationUrl;
};

return ;
}

## Важные советы по безопасности
— Никогда не храните секретные ключи на фронтенде.
— Используйте переменные окружения (.env).
— Проверяйте подписи вебхуков на сервере.
— Всегда используйте HTTPS.
— Логируйте все транзакции и обрабатывайте ошибки.

Оба решения легко масштабируются и подходят для production-приложений.


Задайте вопрос нейросети

Не нашли ответ? Спросите ИИ — он подготовит развёрнутую статью.