Skip to main content

Платежные системы

Интеграция с различными платежными провайдерами для обработки онлайн-платежей.

Ю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

PayPal

Настройка PayPal

interface PayPalConfig {
client_id: string;
client_secret: string;
mode: 'sandbox' | 'live';
webhook_id: string;
}

Создание заказа PayPal

import paypal from '@paypal/checkout-server-sdk';

const client = new paypal.core.PayPalHttpClient(environment);

const request = new paypal.orders.OrdersCreateRequest();
request.requestBody({
intent: 'CAPTURE',
purchase_units: [{
amount: {
currency_code: 'USD',
value: orderTotal.toString()
},
reference_id: orderId,
description: `Order #${orderNumber}`
}],
application_context: {
return_url: 'https://marketplace.com/payment/success',
cancel_url: 'https://marketplace.com/payment/cancel',
brand_name: 'Marketplace',
landing_page: 'BILLING',
user_action: 'PAY_NOW'
}
});

const order = await client.execute(request);

Российские платежные системы

Сбербанк

interface SberbankConfig {
username: string;
password: string;
endpoint: string;
return_url: string;
fail_url: string;
}

const registerSberbankPayment = async (orderData: OrderData) => {
const params = {
userName: username,
password: password,
orderNumber: orderData.number,
amount: orderData.amount * 100, // в копейках
returnUrl: returnUrl,
failUrl: failUrl,
description: orderData.description
};

const response = await fetch(`${endpoint}/register.do`, {
method: 'POST',
body: new URLSearchParams(params)
});

return await response.json();
};

Тинькофф Эквайринг

interface TinkoffConfig {
terminal_key: string;
secret_key: string;
api_url: string;
}

const createTinkoffPayment = async (payment: PaymentData) => {
const token = generateTinkoffToken(payment, secretKey);

const requestData = {
TerminalKey: terminalKey,
Amount: payment.amount * 100,
OrderId: payment.orderId,
Description: payment.description,
NotificationURL: 'https://marketplace.com/webhooks/tinkoff',
SuccessURL: 'https://marketplace.com/payment/success',
FailURL: 'https://marketplace.com/payment/fail',
Token: token
};

const response = await fetch(`${apiUrl}/Init`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestData)
});

return await response.json();
};

Криптовалютные платежи

CoinGate

interface CoinGateConfig {
api_key: string;
environment: 'sandbox' | 'live';
receive_currency: 'USD' | 'EUR' | 'BTC';
}

const createCryptoPayment = async (orderData: CryptoOrderData) => {
const payment = {
order_id: orderData.orderId,
price_amount: orderData.amount,
price_currency: 'USD',
receive_currency: 'USD',
title: `Order #${orderData.orderNumber}`,
description: orderData.description,
callback_url: 'https://marketplace.com/webhooks/coingate',
success_url: 'https://marketplace.com/payment/success',
cancel_url: 'https://marketplace.com/payment/cancel'
};

const response = await fetch('https://api.coingate.com/v2/orders', {
method: 'POST',
headers: {
'Authorization': `Token ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payment)
});

return await response.json();
};

Мультивалютность

Конвертация валют

interface CurrencyConverter {
base_currency: string;
supported_currencies: string[];
exchange_rates: ExchangeRate[];
auto_update: boolean;
}

interface ExchangeRate {
from: string;
to: string;
rate: number;
last_updated: string;
}

const convertCurrency = (amount: number, from: string, to: string): number => {
if (from === to) return amount;

const rate = getExchangeRate(from, to);
return Math.round(amount * rate * 100) / 100;
};

Локализация платежей

interface PaymentLocalization {
country: string;
currency: string;
preferred_methods: PaymentMethod[];
tax_inclusive: boolean;
decimal_places: number;
}

const getLocalPaymentMethods = (countryCode: string): PaymentMethod[] => {
const localizations = {
'RU': ['yookassa', 'sberbank', 'tinkoff'],
'US': ['stripe', 'paypal', 'apple_pay'],
'DE': ['stripe', 'paypal', 'sepa'],
'CN': ['alipay', 'wechat_pay']
};

return localizations[countryCode] || ['stripe', 'paypal'];
};

Безопасность платежей

PCI DSS соответствие

interface SecurityConfig {
pci_compliant: boolean;
tokenization: boolean;
encryption: EncryptionSettings;
fraud_detection: FraudSettings;
}

interface FraudSettings {
enabled: boolean;
risk_threshold: number;
velocity_checks: boolean;
geo_blocking: string[];
blacklist: string[];
}

3D Secure

interface ThreeDSecureConfig {
enabled: boolean;
version: '1.0' | '2.0';
challenge_threshold: number;
exemptions: ThreeDSExemption[];
}

type ThreeDSExemption =
| 'low_value'
| 'trusted_merchant'
| 'secure_corporate'
| 'transaction_risk_analysis';

Возвраты и споры

Автоматические возвраты

interface RefundPolicy {
auto_refund: boolean;
refund_window: number; // дни
partial_refunds: boolean;
refund_methods: RefundMethod[];
}

const processRefund = async (paymentId: string, amount?: number) => {
const refund = await stripe.refunds.create({
payment_intent: paymentId,
amount: amount ? Math.round(amount * 100) : undefined,
reason: 'requested_by_customer',
metadata: {
refund_type: 'customer_request',
processed_by: 'auto_system'
}
});

// Обновление статуса заказа
await updateOrderStatus(orderId, 'refunded');

// Уведомление клиента
await sendRefundNotification(customerId, refund);

return refund;
};

Аналитика платежей

Метрики

interface PaymentAnalytics {
total_volume: number;
transaction_count: number;
success_rate: number;
average_transaction: number;
top_methods: PaymentMethodStats[];
geographic_distribution: GeoStats[];
time_series: TimeSeriesData[];
}

interface PaymentMethodStats {
method: string;
volume: number;
count: number;
success_rate: number;
average_amount: number;
}

Отчетность

interface PaymentReport {
period: DateRange;
summary: PaymentSummary;
details: PaymentDetail[];
reconciliation: ReconciliationData;
fees: FeeBreakdown;
}