Connect customer quotations and payment execution to Sendico (#50)
This commit is contained in:
1 parent
5d67c25c8e
commit
7a6510d1a8
45 files changed
+2696
-45
No files matched your search
@@ -0,0 +1,84 @@
|
||||
package paymenthttp
|
||||
|
||||
import (
|
||||
"git.sendico.io/tech/sxchnge/product/payments"
|
||||
factor "git.sendico.io/tech/sxchnge/product/twofactor/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type requestDTO struct {
|
||||
Kind string `json:"kind"`
|
||||
Source string `json:"source"`
|
||||
Destination string `json:"destination"`
|
||||
Recipient string `json:"recipient"`
|
||||
Amount int64 `json:"amount"`
|
||||
}
|
||||
|
||||
func (d requestDTO) model() payments.Request {
|
||||
return payments.Request{Kind: d.Kind, Source: d.Source, Destination: d.Destination, Recipient: d.Recipient, Amount: d.Amount}
|
||||
}
|
||||
func fromRequest(r payments.Request) requestDTO {
|
||||
return requestDTO{r.Kind, r.Source, r.Destination, r.Recipient, r.Amount}
|
||||
}
|
||||
|
||||
type quoteDTO struct {
|
||||
ID string `json:"id"`
|
||||
Request requestDTO `json:"request"`
|
||||
Fee int64 `json:"fee"`
|
||||
Debit int64 `json:"debit"`
|
||||
Credit int64 `json:"credit"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
Numerator int64 `json:"rateNumerator"`
|
||||
Denominator int64 `json:"rateDenominator"`
|
||||
}
|
||||
|
||||
func fromQuote(q payments.Quote) quoteDTO {
|
||||
return quoteDTO{q.ID, fromRequest(q.Request), q.Fee, q.Debit, q.Credit, q.ExpiresAt, q.RateNumerator, q.RateDenominator}
|
||||
}
|
||||
|
||||
type operationDTO struct {
|
||||
ID string `json:"id"`
|
||||
Quote quoteDTO `json:"quote"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func fromOperation(o payments.Operation) operationDTO {
|
||||
return operationDTO{o.ID, fromQuote(o.Quote), o.Status, o.CreatedAt}
|
||||
}
|
||||
|
||||
type accountDTO struct {
|
||||
ID string `json:"id"`
|
||||
Currency string `json:"currency"`
|
||||
Precision int `json:"precision"`
|
||||
Available int64 `json:"available"`
|
||||
PayoutMethod string `json:"payoutMethod"`
|
||||
PayoutLabel string `json:"payoutLabel"`
|
||||
CanFund bool `json:"canFund"`
|
||||
}
|
||||
type snapshotDTO struct {
|
||||
Accounts []accountDTO `json:"accounts"`
|
||||
Operations []operationDTO `json:"operations"`
|
||||
}
|
||||
|
||||
func fromSnapshot(s payments.Snapshot) snapshotDTO {
|
||||
v := snapshotDTO{Accounts: []accountDTO{}, Operations: []operationDTO{}}
|
||||
for _, a := range s.Accounts {
|
||||
v.Accounts = append(v.Accounts, accountDTO{a.ID, a.Currency, a.Precision, a.Available, a.PayoutMethod, a.PayoutLabel, a.FundingMethod != ""})
|
||||
}
|
||||
for i := len(s.Operations) - 1; i >= 0; i-- {
|
||||
v.Operations = append(v.Operations, fromOperation(s.Operations[i]))
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
type challengeDTO struct {
|
||||
ID string `json:"challengeId"`
|
||||
Target string `json:"target"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
ResendAt time.Time `json:"resendAt"`
|
||||
}
|
||||
|
||||
func fromChallenge(c factor.Challenge) challengeDTO {
|
||||
return challengeDTO{c.ID, c.Target, c.ExpiresAt, c.ResendAt}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package paymenthttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
sresponse "git.sendico.io/tech/sxchnge/product/auth/http/v1/response"
|
||||
"git.sendico.io/tech/sxchnge/product/auth/ipguard"
|
||||
customer "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
"git.sendico.io/tech/sxchnge/product/payments"
|
||||
verification "git.sendico.io/tech/sxchnge/product/verification/store"
|
||||
merrors "git.sendico.io/tech/sxchnge/shared/errors"
|
||||
api "git.sendico.io/tech/sxchnge/shared/http"
|
||||
"git.sendico.io/tech/sxchnge/shared/http/response"
|
||||
mlogger "git.sendico.io/tech/sxchnge/shared/logging"
|
||||
mservice "git.sendico.io/tech/sxchnge/shared/service"
|
||||
)
|
||||
|
||||
type Registrar interface {
|
||||
AccountHandler(mservice.Type, string, api.HTTPMethod, sresponse.AccountHandlerFunc)
|
||||
}
|
||||
type router struct {
|
||||
service *payments.Service
|
||||
logger mlogger.Logger
|
||||
}
|
||||
|
||||
func Install(reg Registrar, s *payments.Service, logger mlogger.Logger) {
|
||||
h := &router{s, logger.Named("payment_http")}
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet/profile", api.Get, h.profile)
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet", api.Get, h.fetch)
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet/quote", api.Post, h.quote)
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet/submit", api.Post, h.submit)
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet/submission", api.Post, h.reconcile)
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet/challenge", api.Post, h.challenge)
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet/resend", api.Post, h.resend)
|
||||
reg.AccountHandler(mservice.Accounts, "/wallet/verify", api.Post, h.verify)
|
||||
}
|
||||
func decode(r *http.Request, dst any) error {
|
||||
d := json.NewDecoder(io.LimitReader(r.Body, 8193))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(dst) != nil {
|
||||
return payments.InvalidAmount
|
||||
}
|
||||
var extra any
|
||||
if d.Decode(&extra) != io.EOF {
|
||||
return payments.InvalidAmount
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (h *router) result(data any, err error) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if err == nil {
|
||||
response.Ok(h.logger, data)(w, r)
|
||||
return
|
||||
}
|
||||
code := "unavailable"
|
||||
status := http.StatusServiceUnavailable
|
||||
var f payments.Failure
|
||||
if errors.As(err, &f) {
|
||||
code = string(f)
|
||||
if f != payments.Unavailable && f != payments.Uncertain {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, verification.ErrTokenExpired):
|
||||
code = "factorExpired"
|
||||
status = 400
|
||||
case errors.Is(err, verification.ErrTokenAttemptsExceeded):
|
||||
code = "factorLocked"
|
||||
status = 400
|
||||
case errors.Is(err, verification.ErrTokenNotFound), errors.Is(err, verification.ErrTokenAlreadyUsed), errors.Is(err, merrors.ErrUnauthorized):
|
||||
code = "factorInvalid"
|
||||
status = 400
|
||||
}
|
||||
if throttle, ok := verification.Throttle(err); ok {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(max(1, int(throttle.RetryAfter.Seconds()))))
|
||||
code = "factorCooldown"
|
||||
status = 429
|
||||
}
|
||||
response.Error(h.logger, mservice.Accounts, status, code, "Unable to complete wallet operation")(w, r)
|
||||
}
|
||||
}
|
||||
func (h *router) fetch(r *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
v, e := h.service.Fetch(r.Context(), a)
|
||||
return h.result(fromSnapshot(v), e)
|
||||
}
|
||||
func (h *router) quote(r *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
var d requestDTO
|
||||
if e := decode(r, &d); e != nil {
|
||||
return h.result(nil, e)
|
||||
}
|
||||
v, e := h.service.Quote(r.Context(), a, d.model())
|
||||
return h.result(fromQuote(v), e)
|
||||
}
|
||||
|
||||
type actionDTO struct {
|
||||
Quote string `json:"quoteId"`
|
||||
Key string `json:"idempotencyKey"`
|
||||
Challenge string `json:"challengeId"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
func (h *router) submit(r *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
var d actionDTO
|
||||
if e := decode(r, &d); e != nil {
|
||||
return h.result(nil, e)
|
||||
}
|
||||
v, e := h.service.Submit(r.Context(), a, d.Quote, d.Key)
|
||||
return h.result(fromOperation(v), e)
|
||||
}
|
||||
func (h *router) reconcile(r *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
var d actionDTO
|
||||
if e := decode(r, &d); e != nil {
|
||||
return h.result(nil, e)
|
||||
}
|
||||
v, e := h.service.Reconcile(r.Context(), a, d.Key)
|
||||
if v == nil {
|
||||
return h.result(nil, e)
|
||||
}
|
||||
return h.result(fromOperation(*v), e)
|
||||
}
|
||||
func requestIP(r *http.Request) string {
|
||||
if ip := ipguard.ClientIP(r); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
return "unresolved"
|
||||
}
|
||||
func (h *router) challenge(r *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
var d actionDTO
|
||||
if e := decode(r, &d); e != nil {
|
||||
return h.result(nil, e)
|
||||
}
|
||||
v, e := h.service.Challenge(r.Context(), a, d.Quote, requestIP(r))
|
||||
return h.result(fromChallenge(v), e)
|
||||
}
|
||||
func (h *router) resend(r *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
var d actionDTO
|
||||
if e := decode(r, &d); e != nil {
|
||||
return h.result(nil, e)
|
||||
}
|
||||
v, e := h.service.Resend(r.Context(), a, d.Quote, d.Challenge, d.Key, requestIP(r))
|
||||
return h.result(fromChallenge(v), e)
|
||||
}
|
||||
func (h *router) verify(r *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
var d actionDTO
|
||||
if e := decode(r, &d); e != nil {
|
||||
return h.result(nil, e)
|
||||
}
|
||||
e := h.service.Authorize(r.Context(), a, d.Quote, d.Challenge, d.Code, d.Key)
|
||||
return h.result(struct {
|
||||
Key string `json:"idempotencyKey"`
|
||||
}{d.Key}, e)
|
||||
}
|
||||
|
||||
func (h *router) profile(_ *http.Request, a *customer.Account, _ *sresponse.TokenData) http.HandlerFunc {
|
||||
return h.result(struct {
|
||||
Locale string `json:"locale"`
|
||||
}{a.Locale}, nil)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package paymenthttp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
customer "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestUnconfiguredWalletCannotReturnDemoFunds(t *testing.T) {
|
||||
h := &router{logger: zap.NewNop()}
|
||||
a := &customer.Account{}
|
||||
a.ID = bson.NewObjectID()
|
||||
request := httptest.NewRequest(http.MethodGet, "/accounts/wallet", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
h.fetch(request, a, nil)(recorder, request)
|
||||
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
|
||||
require.Equal(t, "no-store", recorder.Header().Get("Cache-Control"))
|
||||
require.NotContains(t, recorder.Body.String(), "7500")
|
||||
}
|
||||
func TestQuoteRejectsUnknownFieldsAndTrailingRequests(t *testing.T) {
|
||||
h := &router{logger: zap.NewNop()}
|
||||
a := &customer.Account{}
|
||||
a.ID = bson.NewObjectID()
|
||||
for _, body := range []string{`{"kind":"payout","subject":"foreign"}`, `{"amount":10} {"amount":20}`, `{"amount":1.2}`} {
|
||||
request := httptest.NewRequest(http.MethodPost, "/accounts/wallet/quote", strings.NewReader(body))
|
||||
recorder := httptest.NewRecorder()
|
||||
h.quote(request, a, nil)(recorder, request)
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user