Платежные системы
Интеграция с различными платежными провайдерами для обработки онлайн-платежей.
ЮKassa (Яндекс.Касса)
Обзор
ЮKassa - ведущий российский сервис онлайн-платежей, поддерживающий все основные способы оплаты в России.
Настройка ЮKassa
interface YuKassaConfig {
shop_id: string;
secret_key: string;
webhook_secret?: string;
test_mode: boolean;
auto_capture: boolean;
locale: 'ru_RU' | 'en_US';
}
Создание платежа
import { YooCheckout } from '@yoomoney/checkout-js';
const checkout = new YooCheckout({
shopId: shopId,
secretKey: secretKey
});
const payment = await checkout.createPayment({
amount: {
value: '100.00',
currency: 'RUB'
},
payment_method_data: {
type: 'bank_card'
},
confirmation: {
type: 'redirect',
return_url: 'https://marketplace.com/payment/success'
},
description: `Оплата заказа #${orderNumber}`,
metadata: {
order_id: orderId,
user_id: userId
}
});
Поддерживаемые методы оплаты
- Банковские карты (Visa, MasterCard, МИР)
- Электронные кошельки (ЮMoney, QIWI, WebMoney)
- Интернет-банкинг (Сбербанк Онлайн, Альфа-Клик)
- Наличные (через терминалы)
- Мобильные платежи
- Installments (рассрочка)
Webhook обработка
const handleYuKassaWebhook = async (req: Request) => {
const signature = req.headers['signature'];
const body = JSON.stringify(req.body);
// Проверка подписи
const hash = crypto
.createHmac('sha256', webhookSecret)
.update(body)
.digest('hex');
if (signature !== hash) {
throw new Error('Invalid signature');
}
const { type, object } = req.body;
if (type === 'payment.succeeded') {
await processSuccessfulPayment(object);
} else if (type === 'payment.canceled') {
await processCanceledPayment(object);
}
};
Stripe
Обзор
Международная платежная платформа с поддержкой множества валют и способов оплаты.
Настройка Stripe
interface StripeConfig {
publishable_key: string;
secret_key: string;
webhook_secret: string;
api_version: string;
connect_account_id?: string;
}
Создание PaymentIntent
import Stripe from 'stripe';
const stripe = new Stripe(secretKey, {
apiVersion: '2023-10-16'
});
const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(orderTotal * 100), // сумма в копейках
currency: 'rub',
payment_method_types: ['card'],
metadata: {
order_id: orderId,
customer_id: customerId
},
description: `Order #${orderNumber}`,
receipt_email: customerEmail
});
Stripe Elements (фронтенд)
import { loadStripe } from '@stripe/stripe-js';
import {
Elements,
CardElement,
useStripe,
useElements
} from '@stripe/react-stripe-js';
const stripePromise = loadStripe(publishableKey);
const CheckoutForm = () => {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (event: FormEvent) => {
event.preventDefault();
if (!stripe || !elements) return;
const cardElement = elements.getElement(CardElement);
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: 'card',
card: cardElement!,
billing_details: {
name: customerName,
email: customerEmail
}
});
if (!error) {
// Отправка paymentMethod.id на сервер
await confirmPayment(paymentMethod.id);
}
};
};
Поддерживаемые методы
- Банковские карты
- Apple Pay / Google Pay
- SEPA Direct Debit
- Bancontact, iDEAL, Giropay
- Afterpay/Clearpay
- Klarna