228 lines
6.4 KiB
Go
228 lines
6.4 KiB
Go
package payout
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"regexp"
|
|
|
|
"github.com/google/uuid"
|
|
"go.uber.org/fx"
|
|
|
|
"payouts/internal/api/common"
|
|
"payouts/internal/config"
|
|
"payouts/internal/models"
|
|
"payouts/internal/service/cache"
|
|
"payouts/internal/service/database"
|
|
"payouts/internal/service/database/orm"
|
|
"payouts/internal/service/yookassa"
|
|
yookassaConf "payouts/internal/service/yookassa/config"
|
|
)
|
|
|
|
const (
|
|
BaseRoute = "/payout"
|
|
CreateRoute = "/create"
|
|
CallbackRoute = "/callback"
|
|
BanksRoute = "/sbp/banks"
|
|
)
|
|
|
|
var authHeaderRe = regexp.MustCompile(`^Bearer\s+(.*)$`)
|
|
|
|
type payoutHandler struct {
|
|
dbService database.Service
|
|
cacheService cache.Service
|
|
yooKassa yookassa.Service
|
|
yookassaConf yookassaConf.YooKassa
|
|
}
|
|
|
|
// Params represents the module input params
|
|
type Params struct {
|
|
fx.In
|
|
|
|
AppConfig *config.App
|
|
DbService database.Service
|
|
YooKassa yookassa.Service
|
|
CacheService cache.Service
|
|
}
|
|
|
|
func NewPayoutHandler(p Params) (Handler, error) {
|
|
return &payoutHandler{
|
|
dbService: p.DbService,
|
|
cacheService: p.CacheService,
|
|
yooKassa: p.YooKassa,
|
|
yookassaConf: p.YooKassa.GetConfig(),
|
|
}, nil
|
|
}
|
|
|
|
func (p *payoutHandler) getSession(r *http.Request) (*orm.User, error) {
|
|
authHeaderValue := r.Header.Get("Authorization")
|
|
if len(authHeaderValue) == 0 {
|
|
return nil, errors.New("no valid auth header")
|
|
}
|
|
|
|
matches := authHeaderRe.FindStringSubmatch(authHeaderValue)
|
|
if matches == nil {
|
|
return nil, errors.New("no valid auth header")
|
|
}
|
|
|
|
sessionId := matches[1]
|
|
userSession, err := p.cacheService.GetSession(sessionId)
|
|
if err != nil {
|
|
return nil, errors.New("session not found")
|
|
}
|
|
return &userSession, nil
|
|
|
|
}
|
|
|
|
func (p *payoutHandler) checkAllowedIpCallback(ipStr string) bool {
|
|
ipWithoutPort, _, _ := net.SplitHostPort(ipStr)
|
|
|
|
ip := net.ParseIP(ipWithoutPort)
|
|
if ip == nil {
|
|
slog.Error(fmt.Sprintf("Invalid IP: %s", ipStr))
|
|
return false
|
|
}
|
|
for _, subnetStr := range p.yookassaConf.AllowedCallbackSubnets {
|
|
_, ipNet, err := net.ParseCIDR(subnetStr)
|
|
if err != nil {
|
|
slog.Error(fmt.Sprintf("Invalid subnet CIDR: %v", err))
|
|
continue
|
|
}
|
|
if ipNet.Contains(ip) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// GetSbpBanks implements [Handler].
|
|
func (p *payoutHandler) GetSbpBanks(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-type", "application/json")
|
|
|
|
banksResp, err := p.yooKassa.GetSbpBanks(yookassa.WithContext(r.Context()))
|
|
|
|
if err != nil {
|
|
status := http.StatusBadRequest
|
|
var yError *yookassa.Error
|
|
if errors.As(err, &yError) {
|
|
status = yError.Status
|
|
}
|
|
common.ErrorResponse(w, "failed to retrieve sbp banks", err, status)
|
|
return
|
|
}
|
|
|
|
encoder := json.NewEncoder(w)
|
|
err = encoder.Encode(banksResp)
|
|
if err != nil {
|
|
common.ErrorResponse(w, "failed to encode response", err, http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
// PaymentCreate implements [Handler].
|
|
func (p *payoutHandler) PayoutCreate(w http.ResponseWriter, r *http.Request) {
|
|
defer r.Body.Close()
|
|
|
|
w.Header().Set("Content-type", "application/json")
|
|
|
|
userSession, err := p.getSession(r)
|
|
if err != nil {
|
|
common.ErrorResponse(w, "unauthorized", err, http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
payoutReq := models.PayoutReq{
|
|
PayoutType: models.TypeSBP,
|
|
}
|
|
decoder := json.NewDecoder(r.Body)
|
|
err = decoder.Decode(&payoutReq)
|
|
if err != nil {
|
|
common.ErrorResponse(w, "failed to decode request body", err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
idempotenceKey := uuid.New().String()
|
|
payoutModel := &orm.Payout{
|
|
User: *userSession,
|
|
IdempotenceKey: idempotenceKey,
|
|
Type: payoutReq.PayoutType.String(),
|
|
Amount: payoutReq.Amount,
|
|
Status: models.StatusCreated.String(),
|
|
}
|
|
err = p.dbService.CreatePayout(payoutModel, database.WithContext(r.Context()))
|
|
if err != nil {
|
|
common.ErrorResponse(w, "failed to create payout data", err, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
slog.Debug(fmt.Sprintf("Received create payload request: %v from user %v", payoutReq, userSession))
|
|
|
|
payoutResp, err := p.yooKassa.CreatePayout(payoutReq, userSession, idempotenceKey, yookassa.WithContext(r.Context()))
|
|
if err != nil {
|
|
status := http.StatusBadRequest
|
|
var yError *yookassa.Error
|
|
if errors.As(err, &yError) {
|
|
status = yError.Status
|
|
}
|
|
common.ErrorResponse(w, "failed to create payout request", err, status)
|
|
return
|
|
}
|
|
|
|
updatedRows, err := p.dbService.UpdatePayoutById(payoutModel.ID, orm.Payout{
|
|
PayoutID: payoutResp.ID,
|
|
Status: payoutResp.Status.String(),
|
|
}, database.WithContext(r.Context()))
|
|
|
|
if err != nil || updatedRows == 0 {
|
|
common.ErrorResponse(w, "failed to update payout data", err, http.StatusInternalServerError, slog.String("id", fmt.Sprintf("%d", payoutModel.ID)))
|
|
return
|
|
}
|
|
|
|
encoder := json.NewEncoder(w)
|
|
err = encoder.Encode(payoutResp)
|
|
if err != nil {
|
|
common.ErrorResponse(w, "failed to encode response", err, http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
func (p *payoutHandler) delayedPayoutUpdate(ctx context.Context, payoutData *yookassa.PayoutResponse) {
|
|
<-ctx.Done()
|
|
slog.Info("Updating payout data received from callback")
|
|
|
|
updatedRows, err := p.dbService.UpdatePayoutByPayoutID(payoutData.ID, orm.Payout{
|
|
Status: payoutData.Status.String(),
|
|
}, database.WithContext(context.Background()))
|
|
|
|
if err != nil || updatedRows == 0 {
|
|
slog.Error("Failed to update paylout data", slog.String("error", fmt.Sprintf("%v", err)), slog.Int("rows_updated", updatedRows))
|
|
} else {
|
|
slog.Info("Successfully updated payout data", slog.String("payout_id", payoutData.ID), slog.String("new_status", payoutData.Status.String()))
|
|
}
|
|
}
|
|
|
|
// PaymentCallback 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) {
|
|
common.ErrorResponse(w, "unallowed", nil, http.StatusForbidden, common.Reason("Callback came from unallowed ip: %s", r.RemoteAddr))
|
|
return
|
|
}
|
|
|
|
payoutData := &yookassa.PayoutResponse{}
|
|
decoder := json.NewDecoder(r.Body)
|
|
err := decoder.Decode(payoutData)
|
|
|
|
if err != nil {
|
|
common.ErrorResponse(w, "bad request", nil, http.StatusBadRequest, common.Reason("Failed to decode payload data: %v", err))
|
|
return
|
|
}
|
|
|
|
ctx, _ := context.WithTimeout(context.Background(), p.yookassaConf.CallbackProcessTimeout)
|
|
go p.delayedPayoutUpdate(ctx, payoutData)
|
|
|
|
slog.Debug(fmt.Sprintf("Received callback from %s with object %v with headers %v", r.RemoteAddr, payoutData, r.Header))
|
|
}
|