Compare commits

...

3 Commits

17 changed files with 1001 additions and 186 deletions

24
Dockerfile Normal file
View File

@@ -0,0 +1,24 @@
FROM golang:1.26-alpine3.23 AS build
WORKDIR /payoutsbuild
RUN apk add --update --no-cache ca-certificates git
ENV GOBIN=/payoutsbuild/bin
ADD . /payoutsbuild
RUN cd /payoutsbuild && \
go mod download && \
go build ./cmd/...
FROM alpine:3.23
WORKDIR /app
COPY --from=build /payoutsbuild/payouts /app/
COPY --from=build /payoutsbuild/config/payouts.properties /app/
EXPOSE 8080
ENTRYPOINT [ "/app/payouts" ]

541
README.md
View File

@@ -1,177 +1,398 @@
# Payouts Service
## API Endpoints
A Go service for processing payouts via YooKassa, supporting SBP, YooMoney, bank card, and widget-based payout flows.
### User Management
---
#### Register User
- **Path**: `/api/v1/user/register`
- **Method**: POST
- **Request Parameters**:
```json
{
"tin": "string",
"phone": "string",
"password": "string",
"password_cfm": "string"
}
```
- **Response Parameters**:
```json
{
"status": "string"
}
```
- **Curl Example**:
```bash
curl -X POST http://localhost:8080/api/v1/user/register \
-H "Content-Type: application/json" \
-d '{"tin":"1234567890","phone":"+79991234567","password":"password123","password_cfm":"password123"}'
```
## API Reference
#### User Login
- **Path**: `/api/v1/user/login`
- **Method**: POST
- **Request Parameters**:
```json
{
"phone": "string",
"password": "string"
}
```
- **Response Parameters**:
```json
{
"token": "string",
"token_ttl": "integer"
}
```
- **Curl Example**:
```bash
curl -X POST http://localhost:8080/api/v1/user/login \
-H "Content-Type: application/json" \
-d '{"phone":"+79991234567","password":"password123"}'
```
### `GET /health`
### Payout Operations
Health check endpoint. Verifies database connectivity.
#### Get SBP Banks
- **Path**: `/api/v1/payout/sbp/banks`
- **Method**: GET
- **Request Parameters**: None
- **Response Parameters**:
```json
[
{
"bank_id": "string",
"name": "string",
"bic": "string"
}
**Request parameters:** None
**Response:**
| Status | Body |
|--------|------|
| `200 OK` | `{"OK": true}` |
| `503 Service Unavailable` | `{"OK": false, "Error": "error details"}` |
**Example:**
```bash
curl -s http://localhost:8080/health
```
---
### `GET /version`
Returns the application version.
**Request parameters:** None
**Response:** Plain text version string (e.g. `v1.0.0`). If version is `unknown`, the git commit hash from build info is appended.
**Example:**
```bash
curl -s http://localhost:8080/version
```
---
### `POST /api/v1/user/register`
Register a new user.
**Request body (JSON):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `tin` | string | yes | Tax identification number |
| `phone` | string | yes | Phone number (must be unique) |
| `password` | string | yes | Password |
| `password_cfm` | string | yes | Password confirmation (must match `password`) |
**Response:**
| Status | Description |
|--------|-------------|
| `201 Created` | User registered successfully (no body) |
| `400 Bad Request` | Validation error or phone already registered |
| `500 Internal Server Error` | Password hashing failure |
**Example:**
```bash
curl -s -X POST http://localhost:8080/api/v1/user/register \
-H "Content-Type: application/json" \
-d '{"tin":"123456789","phone":"+79001234567","password":"secret","password_cfm":"secret"}'
```
---
### `POST /api/v1/user/login`
Authenticate a user and obtain a session token.
**Request body (JSON):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `phone` | string | yes | Registered phone number |
| `password` | string | yes | Password |
**Response (200 OK):**
```json
{
"token": "550e8400-e29b-41d4-a716-446655440000",
"token_ttl": 1712000000
}
```
| Field | Type | Description |
|-------|------|-------------|
| `token` | string | UUID session token to use in subsequent requests |
| `token_ttl` | integer | Unix timestamp when the token expires |
**Error response:**
```json
{
"status": 401,
"message": "Unauthorized"
}
```
**Example:**
```bash
curl -s -X POST http://localhost:8080/api/v1/user/login \
-H "Content-Type: application/json" \
-d '{"phone":"+79001234567","password":"secret"}'
```
---
### `GET /api/v1/payout/sbp/banks`
Retrieve the list of banks available for SBP payouts.
**Request parameters:** None
**Authentication:** Not required
**Response (200 OK):**
```json
{
"type": "sbp_banks",
"items": [
{
"bank_id": "100000000111",
"name": "Тинькофф Банк",
"bic": "044525974"
}
]
```
- **Curl Example**:
```bash
curl -X GET http://localhost:8080/api/v1/payout/sbp/banks
```
}
```
#### Create Payout
- **Path**: `/api/v1/payout/create`
- **Method**: POST
- **Request Parameters: SBP**:
```json
{
"payout_type": "spb",
"bank_id": "string",
"amount": "float"
}
```
> **_NOTE:_**
> Phone number for SBP payout comes from user's profile
**Example:**
```bash
curl -s http://localhost:8080/api/v1/payout/sbp/banks
```
- **Request Parameters: YooMoney**:
```json
{
"payout_type": "yoo_money",
"account_number": "string",
"amount": "float"
}
```
- **Response Parameters**:
```json
{
"payout_id": "string",
"payout_status": "string"
}
```
- **Curl Example**:
```bash
curl -X POST http://localhost:8080/api/v1/payout/create \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <session_token>" \
-d '{"payout_type":"spb","bank_id":"123456","amount":10.00}'
```
---
#### Payout Callback
- **Path**: `/api/v1/payout/callback`
- **Method**: POST
- **Request Parameters**: YooKassa webhook data (JSON)
- **Response Parameters**: None
- **Curl Example**:
```bash
curl -X POST http://localhost:8080/api/v1/payout/callback \
-H "Content-Type: application/json" \
-d '{"id":"payout_123456","status":"succeeded","amount":{"value":"10.00","currency":"RUB"}}'
```
### `POST /api/v1/payout/create`
## Service Configuration
Create a payout. The `payout_type` determines which additional fields are required.
### Server Configuration
| Property | Description | Default Value |
|----------|-------------|---------------|
| Server.Tls.Enabled | Enable TLS for the server | false |
| Server.Tls.CertFile | Path to TLS certificate file | (empty) |
| Server.Tls.KeyFile | Path to TLS key file | (empty) |
| Server.Port | Server port | :8080 |
| Server.WriteTimeout | Write timeout for requests | 35s |
| Server.ReadTimeout | Read timeout for requests | 35s |
| Server.EnablePProfEndpoints | Enable pprof debug endpoints | false |
**Request headers:**
### Database Configuration
| Property | Description | Default Value |
|----------|-------------|---------------|
| Database.Type | Database type (sqlite, postgres) | (empty) |
| Database.Connection | Database connection string | (empty) |
| Database.LogLevel | Database logging level | Info |
| Database.TraceRequests | Enable request tracing | false |
| Header | Required | Description |
|--------|----------|-------------|
| `Authorization` | yes | `Bearer {token}` — session token from login |
| `Content-Type` | yes | `application/json` |
### YooKassa Configuration
| Property | Description | Default Value |
|----------|-------------|---------------|
| YooKassa.Test | Enable test mode | false |
| YooKassa.ApiBaseKey | YooKassa base API key | (empty) |
| YooKassa.ApiBaseSecret | YooKassa base API secret | (empty) |
| YooKassa.ApiPaymentKey | YooKassa payment API key | (empty) |
| YooKassa.ApiPaymentSecret | YooKassa payment API secret | (empty) |
| YooKassa.BaseUrl | YooKassa API base URL | https://api.yookassa.ru/v3 |
| YooKassa.Timeout | Request timeout | 2s |
| YooKassa.CheckAllowedCallbackAddress | Check callback IP addresses | true |
| YooKassa.AllowedCallbackSubnets | Allowed callback IP subnets | (list of allowed subnets) |
| YooKassa.CallbackProcessTimeout | Delay to process YooKassa allback | 1s |
| YooKassa.Retry.Enabled | Enable request retries | false |
| YooKassa.Retry.Count | Number of retry attempts | 3 |
| YooKassa.Retry.WaitTime | Initial wait time between retries | 200ms |
| YooKassa.Retry.MaxWaitTime | Maximum wait time between retries | 5s |
**Request body (JSON):**
### Cache Configuration
| Property | Description | Default Value |
|----------|-------------|---------------|
| Cache.TTL | Session TTL | 24h |
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `payout_type` | string | yes | One of: `spb`, `yoo_money`, `bank_card`, `widget` |
| `amount` | float | yes | Payout amount in rubles |
| `payout_token` | string | for `widget` | Token received from the YooKassa widget `success_callback` |
| `account_number` | string | for `yoo_money` | YooMoney wallet number or phone |
| `bank_id` | string | for `spb` | Bank identifier from `/api/v1/payout/sbp/banks` |
| `card_number` | string | for `bank_card` | Card number |
### Logging Configuration
| Property | Description | Default Value |
|----------|-------------|---------------|
| Log.Level | Log level | DEBUG |
| Log.FilePath | | ./logs/payouts.log
| Log.TextOutput | | false
| Log.StdoutEnabled | | true
| Log.FileEnabled | | false
> **Note:** For `spb`, the phone number is taken from the authenticated user's profile.
**Response (200 OK):**
```json
{
"payout_id": "po-285e5ee7-0022-5000-8000-01516a44b37d",
"payout_status": "succeeded"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `payout_id` | string | YooKassa payout identifier |
| `payout_status` | string | One of: `created`, `pending`, `succeeded`, `canceled`, `failed` |
**Error response:**
```json
{
"status": 401,
"message": "Unauthorized"
}
```
**Example (SBP payout):**
```bash
curl -s -X POST http://localhost:8080/api/v1/payout/create \
-H "Authorization: Bearer 550e8400-e29b-41d4-a716-446655440000" \
-H "Content-Type: application/json" \
-d '{"payout_type":"spb","amount":500.00,"bank_id":"100000000111"}'
```
**Example (widget payout):**
```bash
curl -s -X POST http://localhost:8080/api/v1/payout/create \
-H "Authorization: Bearer 550e8400-e29b-41d4-a716-446655440000" \
-H "Content-Type: application/json" \
-d '{"payout_type":"widget","amount":500.00,"payout_token":"pt-285e5ee7-0022-5000-8000-01516a44b37d"}'
```
---
### `POST /api/v1/payout/callback`
Webhook endpoint for YooKassa payout status notifications. Called by YooKassa when a payout status changes.
> **Note:** When `YooKassa.CheckAllowedCallbackAddress = true`, requests are validated against a CIDR whitelist of YooKassa IP ranges.
**Request body (JSON, sent by YooKassa):**
```json
{
"id": "po-285e5ee7-0022-5000-8000-01516a44b37d",
"status": "succeeded",
"amount": {
"value": "500.00",
"currency": "RUB"
},
"payout_destination": {
"type": "bank_card",
"card": {
"number": "220000******0001",
"first6": "220000",
"last4": "0001",
"card_type": "MIR",
"issuer_country": "RU",
"issuer_name": "Sberbank"
}
},
"description": "Payout description",
"created_at": "2024-01-01T12:00:00.000Z",
"succeeded_at": "2024-01-01T12:00:05.000Z",
"test": false
}
```
**Response:** `200 OK` (processing is asynchronous)
**Example:**
```bash
curl -s -X POST http://localhost:8080/api/v1/payout/callback \
-H "Content-Type: application/json" \
-d '{"id":"po-285e5ee7-0022-5000-8000-01516a44b37d","status":"succeeded","amount":{"value":"500.00","currency":"RUB"}}'
```
---
## Payout Widget: `/payout/widget`
`GET /payout/widget` serves an HTML page that embeds the [YooKassa Payout Widget](https://yookassa.ru/developers/payouts/making-payouts/bank-card/using-payout-widget/implementing-widget). The widget collects card details from the user and returns a one-time `payout_token` that must be passed to `/api/v1/payout/create`.
### Mobile App Integration
The widget page is designed to be loaded inside a **WebView** on Android or iOS. The widget communicates back to the native app via JavaScript bridge callbacks.
#### Widget Callbacks
The widget fires two callbacks:
**`success_callback(data)`** — called when the user successfully submits card details. The `data` object contains the `payout_token` and card metadata. See [YooKassa widget output parameters](https://yookassa.ru/developers/payouts/making-payouts/bank-card/using-payout-widget/implementing-widget#reference-output-parameters).
**`error_callback(error)`** — called when an error occurs in the widget. See [error output parameters](https://yookassa.ru/developers/payouts/making-payouts/bank-card/using-payout-widget/implementing-widget#reference-output-parameters-error).
#### Android
Expose a JavaScript interface named `AndroidCallback` on the WebView:
```kotlin
class AndroidBridge {
@JavascriptInterface
fun onWidgetData(dataJson: String) {
val data = JSONObject(dataJson)
val payoutToken = data.getString("payout_token")
// Call /api/v1/payout/create with payout_type "widget"
createPayout(payoutToken = payoutToken, amount = 500.0)
}
@JavascriptInterface
fun onWidgetError(errorJson: String) {
// Handle widget error
}
}
webView.addJavascriptInterface(AndroidBridge(), "AndroidCallback")
```
#### iOS (WKWebView)
Add a `WKScriptMessageHandler` named `iosCallback`:
```swift
class WidgetMessageHandler: NSObject, WKScriptMessageHandler {
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
guard let body = message.body as? String,
let data = body.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return }
if message.name == "onWidgetData" {
let payoutToken = json["payout_token"] as? String ?? ""
// Call /api/v1/payout/create with payout_type "widget"
createPayout(payoutToken: payoutToken, amount: 500.0)
} else if message.name == "onWidgetError" {
// Handle widget error
}
}
}
let contentController = WKUserContentController()
let handler = WidgetMessageHandler()
contentController.add(handler, name: "onWidgetData")
contentController.add(handler, name: "onWidgetError")
```
#### Payout Flow After Widget Callback
When `onWidgetData` fires, call `/api/v1/payout/create` with `payout_type = "widget"` and the received `payout_token`:
```bash
curl -s -X POST https://your-service/api/v1/payout/create \
-H "Authorization: Bearer {session_token}" \
-H "Content-Type: application/json" \
-d '{
"payout_type": "widget",
"amount": 500.00,
"payout_token": "{payout_token_from_widget}"
}'
```
---
## Configuration
Configuration is loaded from a `.properties` file (default: `config/payouts.properties`).
### YooKassa
| Property | Default | Description |
|----------|---------|-------------|
| `YooKassa.BaseUrl` | `https://api.yookassa.ru/v3` | YooKassa API base URL |
| `YooKassa.Timeout` | `2s` | HTTP request timeout |
| `YooKassa.Test` | `false` | Enable test mode |
| `YooKassa.ApiBaseKey` | — | Base API key (used for SBP bank list) |
| `YooKassa.ApiBaseSecret` | — | Base API secret |
| `YooKassa.ApiPayoutKey` | — | Payouts API key (gateway account ID; also used as `account_id` in the widget) |
| `YooKassa.ApiPayoutSecret` | — | Payouts API secret |
| `YooKassa.Retry.Enabled` | `false` | Enable automatic request retries |
| `YooKassa.Retry.Count` | `3` | Total attempt count (including the initial request) |
| `YooKassa.Retry.WaitTime` | `200ms` | Initial delay between retries |
| `YooKassa.Retry.MaxWaitTime` | `5s` | Maximum delay (exponential backoff cap) |
| `YooKassa.CheckAllowedCallbackAddress` | `true` | Validate callback source IP against whitelist |
| `YooKassa.AllowedCallbackSubnets` | YooKassa IP ranges | Comma-separated CIDR subnets allowed to send callbacks |
| `YooKassa.CallbackProcessTimeout` | `1s` | Timeout for async callback processing |
| `YooKassa.WidgetVersion` | `3.1.0` | YooKassa widget JS version loaded on `/payout/widget` |
### Database
| Property | Default | Description |
|----------|---------|-------------|
| `Database.Type` | — | Database driver: `sqlite` or `postgres` |
| `Database.Connection` | — | Connection string. SQLite: `payouts.db`. PostgreSQL: `host=127.0.0.1 user=gorm password=gorm dbname=gorm port=5432 sslmode=disable` |
| `Database.LogLevel` | `Info` | GORM log level: `Debug`, `Info`, `Warn`, `Error` |
| `Database.TraceRequests` | `false` | Log all SQL queries |
### Session Cache
| Property | Default | Description |
|----------|---------|-------------|
| `Cache.TTL` | `24h` | Session token time-to-live (Go duration string) |
### Server
| Property | Default | Description |
|----------|---------|-------------|
| `Server.Port` | `:8080` | Listening address and port |
| `Server.WriteTimeout` | `35s` | Response write timeout |
| `Server.ReadTimeout` | `35s` | Request read timeout |
| `Server.EnablePProfEndpoints` | `false` | Expose `/debug/pprof` endpoints |
| `Server.Tls.Enabled` | `false` | Enable TLS |
| `Server.Tls.CertFile` | — | Path to TLS certificate file |
| `Server.Tls.KeyFile` | — | Path to TLS private key file |
### Logging
| Property | Default | Description |
|----------|---------|-------------|
| `Log.Level` | `DEBUG` | Log level: `DEBUG`, `INFO`, `WARN`, `ERROR` |
| `Log.FilePath` | `./logs/payouts.log` | Log file path |
| `Log.TextOutput` | `false` | Use plain text output instead of JSON |
| `Log.StdoutEnabled` | `true` | Write logs to stdout |
| `Log.FileEnabled` | `false` | Write logs to file |

View File

@@ -55,8 +55,10 @@ YooKassa.AllowedCallbackSubnets = 185.71.76.0/27,185.71.77.0/27,77.75.153.0/25,7
# Base API key/secret
YooKassa.ApiBaseKey =
YooKassa.ApiBaseSecret =
# Payments API key/secret
YooKassa.ApiPaymentKey =
YooKassa.ApiPaymentSecret =
# Payouts API key/secret
YooKassa.ApiPayoutKey =
YooKassa.ApiPayoutSecret =
# Timeout to process yookassa callback
YooKassa.CallbackProcessTimeout = 1s
# Widget version
YooKassa.WidgetVersion = 3.1.0

View File

@@ -156,8 +156,8 @@ variables. Variable names are the uppercased property key with `.` replaced by `
| `DATABASE_CONNECTION` | `Database.Connection` |
| `YOOKASSA_APIBASEKEY` | `YooKassa.ApiBaseKey` |
| `YOOKASSA_APIBASESECRET` | `YooKassa.ApiBaseSecret` |
| `YOOKASSA_APIPAYMENTKEY` | `YooKassa.ApiPaymentKey` |
| `YOOKASSA_APIPAYMENTSECRET` | `YooKassa.ApiPaymentSecret` |
| `YOOKASSA_APIPAYOUTKEY` | `YooKassa.ApiPayoutKey` |
| `YOOKASSA_APIPAYOUTSECRET` | `YooKassa.ApiPayoutSecret` |
Provide secrets at install/upgrade time:
@@ -166,8 +166,8 @@ helm install payouts ./helm \
--set secrets.DATABASE_CONNECTION="host=127.0.0.1 user=app password=s3cr3t dbname=payouts port=5432 sslmode=disable" \
--set secrets.YOOKASSA_APIBASEKEY="<key>" \
--set secrets.YOOKASSA_APIBASESECRET="<secret>" \
--set secrets.YOOKASSA_APIPAYMENTKEY="<key>" \
--set secrets.YOOKASSA_APIPAYMENTSECRET="<secret>"
--set secrets.YOOKASSA_APIPAYOUTKEY="<key>" \
--set secrets.YOOKASSA_APIPAYOUTSECRET="<secret>"
```
Or keep them in a separate values file that is **not committed to version control**:
@@ -180,11 +180,11 @@ Example `secrets.values.yaml`:
```yaml
secrets:
DATABASE_CONNECTION: "host=127.0.0.1 user=app password=s3cr3t dbname=payouts port=5432 sslmode=disable"
DATABASE_CONNECTION: "host=127.0.0.1 user=payouts password=password dbname=payouts port=5432 sslmode=disable"
YOOKASSA_APIBASEKEY: "<key>"
YOOKASSA_APIBASESECRET: "<secret>"
YOOKASSA_APIPAYMENTKEY: "<key>"
YOOKASSA_APIPAYMENTSECRET: "<secret>"
YOOKASSA_APIPAYOUTKEY: "<key>"
YOOKASSA_APIPAYOUTSECRET: "<secret>"
```
### Ingress example

View File

@@ -31,15 +31,15 @@
3. Secret environment variables are injected from Secret {{ include "payouts.fullname" . }}:
{{- end }}
DATABASE_CONNECTION, YOOKASSA_APIBASEKEY, YOOKASSA_APIBASESECRET,
YOOKASSA_APIPAYMENTKEY, YOOKASSA_APIPAYMENTSECRET
YOOKASSA_APIPAYOUTKEY, YOOKASSA_APIPAYOUTSECRET
Before deploying to production, populate these values:
helm upgrade {{ .Release.Name }} ./helm \
--set secrets.DATABASE_CONNECTION="host=... dbname=..." \
--set secrets.YOOKASSA_APIBASEKEY="<key>" \
--set secrets.YOOKASSA_APIBASESECRET="<secret>" \
--set secrets.YOOKASSA_APIPAYMENTKEY="<key>" \
--set secrets.YOOKASSA_APIPAYMENTSECRET="<secret>"
--set secrets.YOOKASSA_APIPAYOUTKEY="<key>" \
--set secrets.YOOKASSA_APIPAYOUTSECRET="<secret>"
Or use a separate values file that is not committed to version control:
helm upgrade {{ .Release.Name }} ./helm -f secrets.values.yaml

View File

@@ -101,5 +101,5 @@ secrets:
DATABASE_CONNECTION: ""
YOOKASSA_APIBASEKEY: ""
YOOKASSA_APIBASESECRET: ""
YOOKASSA_APIPAYMENTKEY: ""
YOOKASSA_APIPAYMENTSECRET: ""
YOOKASSA_APIPAYOUTKEY: ""
YOOKASSA_APIPAYOUTSECRET: ""

View File

@@ -15,6 +15,7 @@ import (
"payouts/internal/api/payout"
"payouts/internal/api/user"
"payouts/internal/api/version"
"payouts/internal/api/widget"
appConfig "payouts/internal/config"
"payouts/internal/service/monitoring"
)
@@ -25,6 +26,7 @@ var Module = fx.Options(
health.Module,
payout.Module,
version.Module,
widget.Module,
monitoring.Module,
fx.Invoke(RegisterRoutes),
@@ -41,8 +43,9 @@ type Params struct {
PayoutHandler payout.Handler
UserHandler user.Handler
Version version.Handler
HealthHandler health.Handler
Version version.Handler
Widget widget.Handler
Metrics monitoring.Metrics
}
@@ -77,6 +80,9 @@ func RegisterRoutes(p Params, lc fx.Lifecycle) {
payoutRouter.HandleFunc(payout.CreateRoute, p.PayoutHandler.PayoutCreate).Methods(http.MethodPost)
payoutRouter.HandleFunc(payout.CallbackRoute, p.PayoutHandler.PayoutCallback).Methods(http.MethodPost)
// Widget endpoint
router.HandleFunc(widget.WidgetPage, p.Widget.WidgetHandler).Methods(http.MethodGet)
// collect api metrics
apiRouter.Use(p.Metrics.GetMiddleware())

View File

@@ -122,7 +122,7 @@ func (p *payoutHandler) GetSbpBanks(w http.ResponseWriter, r *http.Request) {
}
}
// PaymentCreate implements [Handler].
// PayoutCreate implements [Handler].
func (p *payoutHandler) PayoutCreate(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
@@ -203,7 +203,7 @@ func (p *payoutHandler) delayedPayoutUpdate(ctx context.Context, payoutData *yoo
}
}
// PaymentCallback implements [Handler].
// PayoutCallback implements [Handler].
func (p *payoutHandler) PayoutCallback(w http.ResponseWriter, r *http.Request) {
// todo: check also the X-real-ip and/or X-Forwarded-For
if p.yookassaConf.CheckAllowedCallbackAddress && !p.checkAllowedIpCallback(r.RemoteAddr) {

View File

@@ -0,0 +1,9 @@
package widget
import (
"go.uber.org/fx"
)
var Module = fx.Options(
fx.Provide(NewWidgetHandler),
)

View File

@@ -0,0 +1,55 @@
package widget
import (
"html/template"
"net/http"
"go.uber.org/fx"
"payouts/internal/service/yookassa"
yookassaConf "payouts/internal/service/yookassa/config"
"payouts/internal/templates"
)
const WidgetPage = "/payout/widget"
type Handler interface {
WidgetHandler(http.ResponseWriter, *http.Request)
}
type widgetHandler struct {
template *template.Template
config yookassaConf.YooKassa
}
// Params represents the module input params
type Params struct {
fx.In
YookassaService yookassa.Service
}
func NewWidgetHandler(p Params) (Handler, error) {
return &widgetHandler{
template: templates.Templates,
config: p.YookassaService.GetConfig(),
}, nil
}
// WidgetHandler renders the payouts widget page
func (h *widgetHandler) WidgetHandler(w http.ResponseWriter, r *http.Request) {
data := struct {
ApiPayoutKey string
WidgetVersion string
}{
ApiPayoutKey: h.config.ApiPayoutKey,
WidgetVersion: h.config.WidgetVersion,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := h.template.ExecuteTemplate(w, "payouts-widget.html", data)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
}

View File

@@ -10,6 +10,8 @@ type PayoutType int64
const (
TypeSBP PayoutType = iota
TypeYooMoney
TypeCard
TypeCardWidget
)
func (r PayoutType) String() string {
@@ -18,6 +20,10 @@ func (r PayoutType) String() string {
return "spb"
case TypeYooMoney:
return "yoo_money"
case TypeCard:
return "bank_card"
case TypeCardWidget:
return "widget"
}
return "unknown"
}
@@ -33,8 +39,12 @@ func (r *PayoutType) UnmarshalText(text []byte) (err error) {
*r = TypeSBP
case "yoo_money":
*r = TypeYooMoney
case "bank_card":
*r = TypeCard
case "widget":
*r = TypeCardWidget
default:
err = fmt.Errorf("invalid payment type: %s", s)
err = fmt.Errorf("invalid payout type: %s", s)
}
return err
}
@@ -83,7 +93,7 @@ func (r *PayoutStatus) UnmarshalText(text []byte) (err error) {
case "failed":
*r = StatusFailed
default:
err = fmt.Errorf("invalid payment type: %s", s)
err = fmt.Errorf("invalid payout type: %s", s)
}
return err
}
@@ -96,8 +106,10 @@ type SBPBank struct {
type PayoutReq struct {
PayoutType PayoutType `json:"payout_type"`
PayoutToken string `json:"payout_token"`
AccountNumber string `json:"account_number"`
BankID string `json:"bank_id"`
CardNumber string `json:"card_number"`
Amount float32 `json:"amount"`
}

View File

@@ -13,8 +13,9 @@ type YooKassa struct {
ApiBaseKey string
ApiBaseSecret string
ApiPaymentKey string
ApiPaymentSecret string
ApiPayoutKey string
ApiPayoutSecret string
WidgetVersion string
CallbackProcessTimeout time.Duration
}

View File

@@ -39,7 +39,8 @@ type Metadata map[string]any
type PayoutRequest struct {
Amount Amount `json:"amount"`
PayoutDestinationData PayoutDestination `json:"payout_destination_data"`
PayoutToken string `json:"payout_token,omitempty"`
PayoutDestinationData PayoutDestination `json:"payout_destination_data,omitzero"`
Description string `json:"description"`
Metadata Metadata `json:"metadata"`
Test bool `json:"test"`

View File

@@ -26,7 +26,7 @@ type yookassaService struct {
func NewYookassaService(conf config.YooKassa) (Service, error) {
client := resty.New()
client.SetBaseURL(conf.BaseUrl)
client.SetBasicAuth(conf.ApiPaymentKey, conf.ApiPaymentSecret)
client.SetBasicAuth(conf.ApiPayoutKey, conf.ApiPayoutSecret)
client.SetTimeout(conf.Timeout)
if conf.Retry.Enabled {
@@ -110,10 +110,23 @@ func (y *yookassaService) CreatePayout(req models.PayoutReq, userSession *orm.Us
switch req.PayoutType {
case models.TypeSBP:
yReq.PayoutDestinationData.Phone = userSession.Phone
yReq.PayoutDestinationData.BankID = req.BankID
yReq.PayoutDestinationData = PayoutDestination{
Phone: userSession.Phone,
BankID: req.BankID,
}
case models.TypeYooMoney:
yReq.PayoutDestinationData.AccountNumber = req.AccountNumber
case models.TypeCard:
yReq.PayoutDestinationData.Card = Card{
Number: req.CardNumber,
}
case models.TypeCardWidget:
yReq.PayoutToken = req.PayoutToken
yReq.PayoutDestinationData = PayoutDestination{}
default:
return nil, errors.New("unsupported payout type")
}

View File

@@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payouts Page</title>
<script src="https://yookassa.ru/payouts-data/{{ .WidgetVersion }}/widget.js"></script>
<style>
</style>
</head>
<body>
<div id="payout-form"></div>
<script>
// Инициализация виджета. Все параметры обязательные.
const payoutsData = new window.PayoutsData({
type: 'payout',
account_id: '{{ .ApiPayoutKey }}', // Идентификатор шлюза (agentId в личном кабинете)
success_callback: function(data) {
// https://yookassa.ru/developers/payouts/making-payouts/bank-card/using-payout-widget/implementing-widget#reference-output-parameters
if (window.AndroidCallback) {
window.AndroidCallback.onWidgetData(JSON.stringify(data));
} else if (window.webkit && window.webkit.messageHandlers.iosCallback) {
window.webkit.messageHandlers.iosCallback.onWidgetData(JSON.stringify(data));
}
},
error_callback: function(error) {
// https://yookassa.ru/developers/payouts/making-payouts/bank-card/using-payout-widget/implementing-widget#reference-output-parameters-error
if (window.AndroidCallback) {
window.AndroidCallback.onWidgetError(JSON.stringify(error));
} else if (window.webkit && window.webkit.messageHandlers.iosCallback) {
window.webkit.messageHandlers.iosCallback.onWidgetError(JSON.stringify(error));
}
}
});
//Отображение формы в контейнере
payoutsData.render('payout-form')
//Метод возвращает Promise, исполнение которого говорит о полной загрузке формы сбора данных (можно не использовать).
.then(() => {
//Код, который нужно выполнить после отображения формы.
});
</script>
</body>
</html>

View File

@@ -0,0 +1,11 @@
package templates
import (
"embed"
"html/template"
)
//go:embed *.html
var FS embed.FS
var Templates = template.Must(template.ParseFS(FS, "*.html"))

415
openapi.yaml Normal file
View File

@@ -0,0 +1,415 @@
openapi: 3.1.0
info:
title: Payouts Service API
description: API for managing user registrations, authentication, and payouts via YooKassa.
version: 1.0.0
servers:
- url: /
tags:
- name: user
description: User registration and authentication
- name: payout
description: Payout operations
- name: system
description: Health and version endpoints
paths:
/api/v1/user/register:
post:
tags: [user]
summary: Register a new user
operationId: userRegister
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserRegisterRequest'
responses:
'201':
description: User created successfully
'400':
description: Invalid input (empty fields or password mismatch)
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/v1/user/login:
post:
tags: [user]
summary: Authenticate a user and obtain a session token
operationId: userLogin
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserLoginRequest'
responses:
'200':
description: Login successful
content:
application/json:
schema:
$ref: '#/components/schemas/UserLoginResponse'
'400':
description: Invalid input (empty phone or password)
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Invalid credentials
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/v1/payout/sbp/banks:
get:
tags: [payout]
summary: Get list of SBP (Fast Payment System) banks
operationId: getSbpBanks
responses:
'200':
description: List of SBP banks
content:
application/json:
schema:
$ref: '#/components/schemas/SBPBankListResponse'
'400':
description: Bad request (YooKassa API error)
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/v1/payout/create:
post:
tags: [payout]
summary: Create a new payout
operationId: createPayout
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PayoutRequest'
responses:
'200':
description: Payout created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/PayoutResponse'
'400':
description: Invalid payout data
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Unauthorized (missing or invalid token)
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/v1/payout/callback:
post:
tags: [payout]
summary: Receive payout status callback from YooKassa
description: |
Called by YooKassa to notify of payout status changes.
If IP validation is enabled, the request must originate from an allowed subnet.
Status updates are processed asynchronously.
operationId: payoutCallback
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PayoutResponse'
responses:
'200':
description: Callback received and queued for processing
'400':
description: Invalid JSON payload
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'403':
description: Forbidden (IP address not in allowed subnets)
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/payout/widget:
get:
tags: [payout]
summary: Serve the payout widget HTML page
operationId: getPayoutWidget
responses:
'200':
description: Widget HTML page
content:
text/html:
schema:
type: string
'500':
description: Template rendering error
/health:
get:
tags: [system]
summary: Health check
description: Verifies database connectivity.
operationId: healthCheck
responses:
'200':
description: Service is healthy
content:
application/json:
schema:
$ref: '#/components/schemas/HealthResponse'
'503':
description: Service unavailable (database connection failed)
content:
application/json:
schema:
$ref: '#/components/schemas/HealthResponse'
/version:
get:
tags: [system]
summary: Get service version
operationId: getVersion
responses:
'200':
description: Version string (optionally including git commit hash)
content:
text/plain:
schema:
type: string
example: v1.2.3
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
description: UUID session token obtained from the login endpoint
schemas:
UserRegisterRequest:
type: object
required: [tin, phone, password, password_cfm]
properties:
tin:
type: string
description: Taxpayer Identification Number
example: "1234567890"
phone:
type: string
description: User phone number
example: "+79001234567"
password:
type: string
format: password
description: User password
password_cfm:
type: string
format: password
description: Password confirmation (must match password)
UserLoginRequest:
type: object
required: [phone, password]
properties:
phone:
type: string
description: Registered phone number
example: "+79001234567"
password:
type: string
format: password
UserLoginResponse:
type: object
properties:
token:
type: string
format: uuid
description: Session token (UUID)
example: "550e8400-e29b-41d4-a716-446655440000"
token_ttl:
type: integer
format: int64
description: Token expiration as Unix timestamp
example: 1711958400
SBPBankListResponse:
type: object
properties:
type:
type: string
example: "list"
items:
type: array
items:
$ref: '#/components/schemas/SBPBank'
SBPBank:
type: object
properties:
bank_id:
type: string
description: Bank identifier
example: "100000000111"
name:
type: string
description: Human-readable bank name
example: "Sberbank"
bic:
type: string
description: Bank Identification Code
example: "044525225"
PayoutType:
type: string
enum: [spb, yoo_money, bank_card, widget]
description: |
Payout method:
- `spb` — Fast Payment System (SBP)
- `yoo_money` — YooMoney wallet
- `bank_card` — bank card
- `widget` — card via widget
PayoutRequest:
type: object
required: [payout_type, amount]
properties:
payout_type:
$ref: '#/components/schemas/PayoutType'
payout_token:
type: string
description: Payment token (used for widget/card payouts)
example: "pt_xxxxxxxxxxxxxxxxxxxx"
account_number:
type: string
description: Account/phone number for SBP or YooMoney payouts
example: "+79001234567"
bank_id:
type: string
description: Bank identifier (required for SBP payouts)
example: "100000000111"
card_number:
type: string
description: Card number (for bank_card payout type)
example: "4111111111111111"
amount:
type: number
format: float
description: Payout amount in RUB
example: 1000.00
PayoutStatus:
type: string
enum: [created, pending, succeeded, canceled, failed]
Amount:
type: object
properties:
value:
type: string
description: Amount as a decimal string
example: "1000.00"
currency:
type: string
description: ISO 4217 currency code
example: "RUB"
PayoutDestination:
type: object
description: Payout destination details (structure depends on payout type)
additionalProperties: true
PayoutResponse:
type: object
properties:
id:
type: string
description: YooKassa payout ID
example: "po_1da5c87d-0984-50e8-a7f3-8de646dd9ec9"
status:
$ref: '#/components/schemas/PayoutStatus'
amount:
$ref: '#/components/schemas/Amount'
payout_destination:
$ref: '#/components/schemas/PayoutDestination'
description:
type: string
example: "Payout for order #42"
created_at:
type: string
format: date-time
example: "2024-04-02T12:00:00Z"
succeeded_at:
type: string
format: date-time
example: "2024-04-02T12:01:00Z"
metadata:
type: object
additionalProperties: true
description: Arbitrary key-value metadata
test:
type: boolean
description: Whether this is a test payout
example: false
HealthResponse:
type: object
properties:
OK:
type: boolean
description: Whether the service is healthy
Error:
type: string
description: Error message (only present when OK is false)
ErrorResponse:
type: object
properties:
status:
type: integer
description: HTTP status code
example: 400
message:
type: string
description: Human-readable error message
example: "Bad Request"