yapaysdk

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2025 License: MIT Imports: 1 Imported by: 0

README

Yapay SDK 🚀

Version Status Go Version License

SDK для создания плагинов бекенд прокси платежной системы Яндекс Пэй

Создавайте индивидуальную логику обработки платежей для каждого клиента

ДокументацияБыстрый стартДорожная картаРучное развертываниеПоддержка


✨ Что делает Yapay SDK?

🔌 Плагинная архитектура - каждый клиент = отдельный плагин
🛡️ Полная изоляция - ошибка одного клиента не влияет на других
Готовые инструменты - отладка, тестирование, туннели для webhook'ов
🔧 ABI совместимость - плагины и сервер используют одинаковые зависимости

🚀 Быстрый старт

1️⃣ DevContainer (рекомендуется)
# Откройте в VS Code → Ctrl+Shift+P → "Dev Containers: Reopen in Container"
# Все готово к работе! 🎉
2️⃣ Ручная настройка
git clone https://github.com/metalmon/yapay-sdk.git
cd yapay-sdk
make check-compatibility  # Проверка готовности
3️⃣ Создание первого плагина
make new-plugin-my-plugin   # Создать плагин в src/
make build-plugins          # Собрать все плагины из src/
make test-plugins           # Протестировать

💡 Совет: Используйте DevContainer для максимального удобства разработки!

⚠️ ВАЖНО: Управление зависимостями

НЕ используйте go mod tidy или go get - это сломает ABI совместимость!

Используйте только:

  • go mod verify - проверка целостности
  • go mod why - анализ зависимостей
  • go list -m all - просмотр версий

При проблемах: скопируйте go.mod из examples/simple-plugin/

📚 Документация

🛠️ Основные команды

🔧 Плагины

make new-plugin-NAME          # Создать новый плагин
make build-plugins            # Собрать все плагины
make build-plugin-NAME        # Собрать конкретный плагин
make test-plugins             # Протестировать плагины

🚀 Разработка

make update-dev-image         # Обновить dev-образ (рекомендуется)
make check-compatibility      # Проверка окружения
make build-plugins            # Сборка плагинов
make debug-plugin-NAME        # Отладка плагина
make tunnel-start             # Туннель для webhook'ов

🔗 Полезные ссылки


🤝 Поддержка проекта

Поставьте звезду, если проект был полезен!

GitHub stars GitHub forks

Версия: 1.0.11 | Статус: ✅ Готов к использованию

Documentation

Index

Constants

View Source
const (
	SDKVersion       = "1.1.0"
	SDKVersionString = "v" + SDKVersion
)

SDKVersion represents the current SDK version

Variables

This section is empty.

Functions

func GetSDKVersion added in v1.0.7

func GetSDKVersion() string

GetSDKVersion returns the current SDK version as a string (e.g., "1.0.8") This is the recommended way for plugins to report their SDK version

Types

type CORSConfig added in v1.0.4

type CORSConfig struct {
	Origins []string `json:"origins" yaml:"origins"`
}

CORSConfig represents CORS-related settings for a merchant

type EmailConfig

type EmailConfig struct {
	Enabled  bool   `json:"enabled" yaml:"enabled"`
	SMTPHost string `json:"smtp_host" yaml:"smtp_host"`
	SMTPPort int    `json:"smtp_port" yaml:"smtp_port"`
	Username string `json:"username" yaml:"username"`
	Password string `json:"password" yaml:"password"`
	From     string `json:"from" yaml:"from"`
}

EmailConfig represents email notification configuration

type FieldLabels

type FieldLabels map[string]string

FieldLabels represents field labels for order metadata in notifications

type Merchant

type Merchant struct {
	ID            string                 `json:"id" yaml:"id"`
	Name          string                 `json:"name" yaml:"name"`
	Description   string                 `json:"description" yaml:"description"`
	Domain        string                 `json:"domain" yaml:"domain"`
	Enabled       bool                   `json:"enabled" yaml:"enabled"`
	SandboxMode   bool                   `json:"sandbox_mode" yaml:"sandbox_mode"`
	Security      SecurityConfig         `json:"security" yaml:"security"`
	Metadata      map[string]interface{} `json:"metadata,omitempty" yaml:"metadata,omitempty"`
	Yandex        YandexConfig           `json:"yandex" yaml:"yandex"`
	Notifications NotificationConfig     `json:"notifications" yaml:"notifications"`
	FieldLabels   FieldLabels            `json:"field_labels,omitempty" yaml:"field_labels,omitempty"`
	Plugin        PluginConfig           `json:"plugin,omitempty" yaml:"plugin,omitempty"`
}

Merchant represents a merchant configuration

type NewHandlerFunc

type NewHandlerFunc func(*Merchant, *logrus.Logger) interface{}

NewHandlerFunc is the function signature for creating a plugin handler This function must be exported from the plugin as "NewHandler"

type NewPaymentEventHandlerFunc added in v1.0.7

type NewPaymentEventHandlerFunc func(*Merchant, *logrus.Logger) PaymentEventHandler

NewPaymentEventHandlerFunc is the function signature for creating a payment event handler This function must be exported from the plugin as "NewPaymentEventHandler"

type NewPaymentGeneratorFunc

type NewPaymentGeneratorFunc func(*Merchant, *logrus.Logger) PaymentLinkGenerator

NewPaymentGeneratorFunc is the function signature for creating a payment generator This function must be exported from the plugin as "NewPaymentGenerator"

type NotificationConfig

type NotificationConfig struct {
	Telegram TelegramConfig       `json:"telegram" yaml:"telegram"`
	Email    EmailConfig          `json:"email" yaml:"email"`
	Messages NotificationMessages `json:"messages,omitempty" yaml:"messages,omitempty"`
}

NotificationConfig represents notification configuration

type NotificationMessages added in v1.1.0

type NotificationMessages struct {
	// Payment notifications
	PaymentCreatedTitle string `json:"payment_created_title,omitempty" yaml:"payment_created_title,omitempty"`
	PaymentSuccessTitle string `json:"payment_success_title,omitempty" yaml:"payment_success_title,omitempty"`
	PaymentFailedTitle  string `json:"payment_failed_title,omitempty" yaml:"payment_failed_title,omitempty"`

	// Request notifications
	RequestTitle        string            `json:"request_title,omitempty" yaml:"request_title,omitempty"`
	RequestDetailsTitle string            `json:"request_details_title,omitempty" yaml:"request_details_title,omitempty"`
	RequestTypeLabels   map[string]string `json:"request_type_labels,omitempty" yaml:"request_type_labels,omitempty"`
}

NotificationMessages represents customizable notification message templates

type Payment

type Payment struct {
	ID          string                 `json:"id"`
	OrderID     string                 `json:"order_id"`
	MerchantID  string                 `json:"merchant_id"` // Merchant ID from Yandex Pay (also serves as client ID)
	Amount      int                    `json:"amount"`
	Currency    string                 `json:"currency"`
	Description string                 `json:"description"`
	Status      string                 `json:"status"`
	ReturnURL   string                 `json:"return_url"`
	PaymentURL  string                 `json:"payment_url,omitempty"`
	Environment string                 `json:"environment,omitempty"` // Environment: "production" or "sandbox"
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt   string                 `json:"created_at,omitempty"`
	UpdatedAt   string                 `json:"updated_at,omitempty"`
}

Payment represents a payment

type PaymentEventHandler added in v1.0.7

type PaymentEventHandler interface {
	// OnPaymentCreated is called when a payment is created
	OnPaymentCreated(payment *Payment) error

	// OnPaymentSuccess is called when a payment succeeds
	OnPaymentSuccess(payment *Payment) error

	// OnPaymentFailed is called when a payment fails
	OnPaymentFailed(payment *Payment) error

	// OnPaymentCanceled is called when a payment is canceled
	OnPaymentCanceled(payment *Payment) error
}

PaymentEventHandler defines the interface for handling payment events This interface allows plugins to implement custom business logic for payment lifecycle events

type PaymentGenerationResult

type PaymentGenerationResult struct {
	PaymentData map[string]interface{} `json:"payment_data"`
	OrderID     string                 `json:"order_id"`
	Amount      int                    `json:"amount"`
	Currency    string                 `json:"currency"`
	Description string                 `json:"description"`
	ReturnURL   string                 `json:"return_url"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

PaymentGenerationResult represents the result of payment data generation

type PaymentLinkGenerator

type PaymentLinkGenerator interface {
	// Payment methods (existing)
	GeneratePaymentData(req *PaymentRequest) (*PaymentGenerationResult, error)
	ValidatePriceFromBackend(req *PaymentRequest) error
	GetPaymentSettings() *PaymentSettings
	CustomizeYandexPayload(payload map[string]interface{}) error

	// Request methods (new - for non-payment requests like consultations, callbacks)
	ProcessRequest(req *RequestData) (*RequestResult, error)
	ValidateRequestData(req *RequestData) error
	GetRequestSettings() *RequestSettings
}

PaymentLinkGenerator defines the interface for payment link generation

type PaymentRequest

type PaymentRequest struct {
	Amount      int                    `json:"amount"`
	Currency    string                 `json:"currency"`
	Description string                 `json:"description"`
	ReturnURL   string                 `json:"return_url"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

PaymentRequest represents a payment request

type PaymentSettings

type PaymentSettings struct {
	Currency           string                 `json:"currency"`
	SandboxMode        bool                   `json:"sandbox_mode"`
	AutoConfirmTimeout int                    `json:"auto_confirm_timeout"`
	CustomFields       map[string]interface{} `json:"custom_fields,omitempty"`
}

PaymentSettings represents payment settings for Yandex Pay

type PluginConfig added in v1.0.10

type PluginConfig struct {
	Type string `json:"type" yaml:"type"`                     // "builtin", "so", "grpc"
	Path string `json:"path,omitempty" yaml:"path,omitempty"` // Path to plugin file (for so/grpc)
}

PluginConfig represents plugin configuration

type RequestData added in v1.1.0

type RequestData struct {
	ID          string                 `json:"id"`
	ClientID    string                 `json:"client_id"`
	Type        string                 `json:"type"` // "consultation", "callback", "custom", etc.
	Description string                 `json:"description"`
	Metadata    map[string]interface{} `json:"metadata"`
	Status      string                 `json:"status"` // "pending", "processed", "cancelled"
	CreatedAt   string                 `json:"created_at,omitempty"`
	UpdatedAt   string                 `json:"updated_at,omitempty"`
}

RequestData represents a non-payment request (consultation, callback, etc.)

type RequestResult added in v1.1.0

type RequestResult struct {
	ID       string                 `json:"id"`
	Status   string                 `json:"status"`
	Message  string                 `json:"message"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

RequestResult represents the result of request processing

type RequestSettings added in v1.1.0

type RequestSettings struct {
	SendEmail       bool   `json:"send_email"`
	EmailTemplate   string `json:"email_template,omitempty"`
	NotifyWebhook   bool   `json:"notify_webhook"`
	WebhookURL      string `json:"webhook_url,omitempty"`
	AutoResponse    string `json:"auto_response,omitempty"`
	RequireApproval bool   `json:"require_approval"`
}

RequestSettings represents settings for request processing

type SecurityConfig added in v1.0.4

type SecurityConfig struct {
	// RequestEnforcement controls request validation policy: strict | origin | monitor
	RequestEnforcement string     `json:"request_enforcement" yaml:"request_enforcement"`
	RateLimit          int        `json:"rate_limit" yaml:"rate_limit"`
	CORS               CORSConfig `json:"cors" yaml:"cors"`
}

SecurityConfig represents per-merchant security configuration

type TelegramConfig

type TelegramConfig struct {
	Enabled  bool   `json:"enabled" yaml:"enabled"`
	ChatID   string `json:"chat_id" yaml:"chat_id"`
	BotToken string `json:"bot_token" yaml:"bot_token"`
}

TelegramConfig represents Telegram notification configuration

type VersionedPlugin added in v1.0.7

type VersionedPlugin interface {
	// GetSDKVersion returns the SDK version this plugin was built against
	GetSDKVersion() string
}

VersionedPlugin represents a plugin that can report its SDK version

type YandexConfig

type YandexConfig struct {
	MerchantID     string `json:"merchant_id" yaml:"merchant_id"`
	SecretKey      string `json:"secret_key" yaml:"secret_key"`
	SandboxMode    bool   `json:"sandbox_mode" yaml:"sandbox_mode"`
	Currency       string `json:"currency" yaml:"currency"`
	APIBaseURL     string `json:"api_base_url,omitempty" yaml:"api_base_url,omitempty"`
	OrdersEndpoint string `json:"orders_endpoint,omitempty" yaml:"orders_endpoint,omitempty"`
	JWKSEndpoint   string `json:"jwks_endpoint,omitempty" yaml:"jwks_endpoint,omitempty"`
	PrivateKeyPath string `json:"private_key_path,omitempty" yaml:"private_key_path,omitempty"`
}

YandexConfig represents Yandex API configuration

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL