stripecoinpayments

package
v1.30.1 Latest Latest
Warning

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

Go to latest
Published: May 18, 2021 License: AGPL-3.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// StripeDepositTransactionDescription is the description for Stripe
	// balance transactions representing STORJ deposits.
	StripeDepositTransactionDescription = "STORJ deposit"

	// StripeDepositBonusTransactionDescription is the description for Stripe
	// balance transactions representing bonuses received for STORJ deposits.
	StripeDepositBonusTransactionDescription = "STORJ deposit bonus"

	// StripeMigratedDepositBonusTransactionDescription is the description for
	// Stripe balance transactions representing bonuses migrated from the
	// 'credits' table of the satellite DB.
	StripeMigratedDepositBonusTransactionDescription = "Migrated STORJ deposit bonus"
)

Variables

View Source
var (
	// Error defines stripecoinpayments service error.
	Error = errs.Class("stripecoinpayments service")
	// ErrNoCouponUsages indicates that there are no coupon usages.
	ErrNoCouponUsages = errs.Class("stripecoinpayments no coupon usages")
)
View Source
var ErrChore = errs.Class("stripecoinpayments chore")

ErrChore is stripecoinpayments clearing loop chore error class.

View Source
var ErrNoCustomer = Error.New("customer doesn't exist")

ErrNoCustomer is error class defining that there is no customer for user.

View Source
var ErrProjectRecordExists = Error.New("invoice project record already exists")

ErrProjectRecordExists is error class defining that such project record already exists.

View Source
var ErrTransactionConsumed = errs.New("error transaction already consumed")

ErrTransactionConsumed is thrown when trying to consume already consumed transaction.

View Source
var ErrVersion = errs.Class("version service")

ErrVersion defines version service error.

Functions

func BytesAreWithinProportion added in v1.10.1

func BytesAreWithinProportion(uuidBytes [16]byte, proportion float64) bool

BytesAreWithinProportion returns true if first byte is less than the normalized proportion [0..1].

Types

type Chore added in v0.25.0

type Chore struct {
	TransactionCycle    *sync2.Cycle
	AccountBalanceCycle *sync2.Cycle
	// contains filtered or unexported fields
}

Chore runs clearing process of reconciling transactions deposits, customer balance, invoices and usages.

architecture: Chore

func NewChore added in v0.25.0

func NewChore(log *zap.Logger, service *Service, txInterval, accBalanceInterval time.Duration) *Chore

NewChore creates new clearing loop chore. TODO: uncomment new interval when coupons will be finished.

func (*Chore) Close added in v0.25.0

func (chore *Chore) Close() (err error)

Close closes all underlying resources.

func (*Chore) Run added in v0.25.0

func (chore *Chore) Run(ctx context.Context) (err error)

Run runs all clearing related cycles.

type Config

type Config struct {
	StripeSecretKey              string        `help:"stripe API secret key" default:""`
	StripePublicKey              string        `help:"stripe API public key" default:""`
	CoinpaymentsPublicKey        string        `help:"coinpayments API public key" default:""`
	CoinpaymentsPrivateKey       string        `help:"coinpayments API private key key" default:""`
	TransactionUpdateInterval    time.Duration `help:"amount of time we wait before running next transaction update loop" default:"2m"`
	AccountBalanceUpdateInterval time.Duration `help:"amount of time we wait before running next account balance update loop" default:"2m"`
	ConversionRatesCycleInterval time.Duration `help:"amount of time we wait before running next conversion rates update loop" default:"10m"`
	AutoAdvance                  bool          `help:"toogle autoadvance feature for invoice creation" default:"false"`
	ListingLimit                 int           `help:"sets the maximum amount of items before we start paging on requests" default:"100" hidden:"true"`
}

Config stores needed information for payment service initialization.

type CouponUsage added in v0.27.0

type CouponUsage struct {
	CouponID uuid.UUID
	Amount   int64
	Status   CouponUsageStatus
	Period   time.Time
}

CouponUsage stores amount of money that should be charged from coupon for billing period.

type CouponUsagePage added in v0.30.0

type CouponUsagePage struct {
	Usages     []CouponUsage
	Next       bool
	NextOffset int64
}

CouponUsagePage holds coupons usages and indicates if there is more data available and provides next offset.

type CouponUsageStatus added in v0.30.0

type CouponUsageStatus int

CouponUsageStatus indicates the state of the coupon usage.

const (
	// CouponUsageStatusUnapplied is a default coupon usage state.
	CouponUsageStatusUnapplied CouponUsageStatus = 0
	// CouponUsageStatusApplied status indicates that coupon usage was used.
	CouponUsageStatusApplied CouponUsageStatus = 1
)

type CouponsDB added in v0.27.0

type CouponsDB interface {
	// Insert inserts a coupon into the database.
	Insert(ctx context.Context, coupon payments.Coupon) (payments.Coupon, error)
	// Update updates coupon in database.
	Update(ctx context.Context, couponID uuid.UUID, status payments.CouponStatus) (payments.Coupon, error)
	// Get returns coupon by ID.
	Get(ctx context.Context, couponID uuid.UUID) (payments.Coupon, error)
	// Delete removes a coupon from the database
	Delete(ctx context.Context, couponID uuid.UUID) error
	// List returns all coupons with specified status.
	List(ctx context.Context, status payments.CouponStatus) ([]payments.Coupon, error)
	// ListByUserID returns all coupons of specified user.
	ListByUserID(ctx context.Context, userID uuid.UUID) ([]payments.Coupon, error)
	// ListByUserIDAndStatus returns all coupons of specified user and status. Results are ordered (asc) by expiration date.
	ListByUserIDAndStatus(ctx context.Context, userID uuid.UUID, status payments.CouponStatus) ([]payments.Coupon, error)
	// ListPending returns paginated list of coupons with specified status.
	ListPaged(ctx context.Context, offset int64, limit int, before time.Time, status payments.CouponStatus) (payments.CouponsPage, error)

	// AddUsage creates new coupon usage record in database.
	AddUsage(ctx context.Context, usage CouponUsage) error
	// TotalUsage gets sum of all usage records for specified coupon.
	TotalUsage(ctx context.Context, couponID uuid.UUID) (int64, error)
	// GetLatest return period_end of latest coupon charge.
	GetLatest(ctx context.Context, couponID uuid.UUID) (time.Time, error)
	// ListUnapplied returns coupon usage page with unapplied coupon usages.
	ListUnapplied(ctx context.Context, offset int64, limit int, period time.Time) (CouponUsagePage, error)
	// ApplyUsage applies coupon usage and updates its status.
	ApplyUsage(ctx context.Context, couponID uuid.UUID, period time.Time) error

	// PopulatePromotionalCoupons is used to populate promotional coupons through all active users who already have a project
	// and do not have a promotional coupon yet. And updates project limits to selected size.
	PopulatePromotionalCoupons(ctx context.Context, users []uuid.UUID, duration *int, amount int64, projectLimit memory.Size) error
}

CouponsDB is an interface for managing coupons table.

architecture: Database

type CreateProjectRecord added in v0.25.0

type CreateProjectRecord struct {
	ProjectID uuid.UUID
	Storage   float64
	Egress    int64
	Objects   float64
}

CreateProjectRecord holds info needed for creation new invoice project record.

type Customer added in v0.25.0

type Customer struct {
	ID     string
	UserID uuid.UUID
}

Customer holds customer id and user id.

type CustomersDB

type CustomersDB interface {
	// Insert inserts a stripe customer into the database.
	Insert(ctx context.Context, userID uuid.UUID, customerID string) error
	// GetCustomerID return stripe customers id.
	GetCustomerID(ctx context.Context, userID uuid.UUID) (string, error)
	// List returns page with customers ids created before specified date.
	List(ctx context.Context, offset int64, limit int, before time.Time) (CustomersPage, error)

	// TODO: get rid of this.
	Raw() *dbx.DB
}

CustomersDB is interface for working with stripe customers table.

architecture: Database

type CustomersPage added in v0.25.0

type CustomersPage struct {
	Customers  []Customer
	Next       bool
	NextOffset int64
}

CustomersPage holds customers and indicates if there is more data available and provides next offset.

type DB added in v0.25.0

type DB interface {
	// Customers is getter for customers db.
	Customers() CustomersDB
	// Transactions is getter for transactions db.
	Transactions() TransactionsDB
	// ProjectRecords is getter for invoice project records db.
	ProjectRecords() ProjectRecordsDB
	// Coupons is getter for coupons db.
	Coupons() CouponsDB
}

DB is stripecoinpayments DB interface.

architecture: Database

type ProjectRecord added in v0.25.0

type ProjectRecord struct {
	ID          uuid.UUID
	ProjectID   uuid.UUID
	Storage     float64
	Egress      int64
	Objects     float64
	PeriodStart time.Time
	PeriodEnd   time.Time
	State       int
}

ProjectRecord holds project usage particular for billing period.

type ProjectRecordsDB added in v0.25.0

type ProjectRecordsDB interface {
	// Create creates new invoice project record with coupon usages and credits spendings in the DB.
	Create(ctx context.Context, records []CreateProjectRecord, couponUsages []CouponUsage, start, end time.Time) error
	// Check checks if invoice project record for specified project and billing period exists.
	Check(ctx context.Context, projectID uuid.UUID, start, end time.Time) error
	// Get returns record for specified project and billing period.
	Get(ctx context.Context, projectID uuid.UUID, start, end time.Time) (*ProjectRecord, error)
	// Consume consumes invoice project record.
	Consume(ctx context.Context, id uuid.UUID) error
	// ListUnapplied returns project records page with unapplied project records.
	ListUnapplied(ctx context.Context, offset int64, limit int, start, end time.Time) (ProjectRecordsPage, error)
}

ProjectRecordsDB is interface for working with invoice project records.

architecture: Database

type ProjectRecordsPage added in v0.25.0

type ProjectRecordsPage struct {
	Records    []ProjectRecord
	Next       bool
	NextOffset int64
}

ProjectRecordsPage holds project records and indicates if there is more data available and provides next offset.

type Service

type Service struct {
	StorageMBMonthPriceCents decimal.Decimal
	EgressMBPriceCents       decimal.Decimal
	ObjectMonthPriceCents    decimal.Decimal
	// BonusRate amount of percents
	BonusRate int64
	// Coupon Values
	CouponValue        int64
	CouponDuration     *int64
	CouponProjectLimit memory.Size
	// Minimum CoinPayment to create a coupon
	MinCoinPayment int64

	// Stripe Extended Features
	AutoAdvance bool

	PaywallProportion float64
	// contains filtered or unexported fields
}

Service is an implementation for payment service via Stripe and Coinpayments.

architecture: Service

func NewService

func NewService(log *zap.Logger, stripeClient StripeClient, config Config, db DB, projectsDB console.Projects, usageDB accounting.ProjectAccounting, storageTBPrice, egressTBPrice, objectPrice string, bonusRate, couponValue int64, couponDuration *int64, couponProjectLimit memory.Size, minCoinPayment int64, paywallProportion float64) (*Service, error)

NewService creates a Service instance.

func (*Service) Accounts

func (service *Service) Accounts() payments.Accounts

Accounts exposes all needed functionality to manage payment accounts.

func (*Service) CreateInvoices added in v0.25.0

func (service *Service) CreateInvoices(ctx context.Context, period time.Time) (err error)

CreateInvoices lists through all customers and creates invoices.

func (*Service) FinalizeInvoices added in v1.7.1

func (service *Service) FinalizeInvoices(ctx context.Context) (err error)

FinalizeInvoices sets autoadvance flag on all draft invoices currently available in stripe.

func (*Service) GetRate added in v0.26.0

func (service *Service) GetRate(ctx context.Context, curr1, curr2 coinpayments.Currency) (_ *big.Float, err error)

GetRate returns conversion rate for specified currencies.

func (*Service) InvoiceApplyCoupons added in v0.27.0

func (service *Service) InvoiceApplyCoupons(ctx context.Context, period time.Time) (err error)

InvoiceApplyCoupons iterates through unapplied project coupons and creates invoice line items for stripe customer.

func (*Service) InvoiceApplyProjectRecords added in v0.25.0

func (service *Service) InvoiceApplyProjectRecords(ctx context.Context, period time.Time) (err error)

InvoiceApplyProjectRecords iterates through unapplied invoice project records and creates invoice line items for stripe customer.

func (*Service) InvoiceItemsFromProjectRecord added in v1.8.1

func (service *Service) InvoiceItemsFromProjectRecord(projName string, record ProjectRecord) (result []*stripe.InvoiceItemParams)

InvoiceItemsFromProjectRecord calculates Stripe invoice item from project record.

func (*Service) PrepareInvoiceProjectRecords added in v0.25.0

func (service *Service) PrepareInvoiceProjectRecords(ctx context.Context, period time.Time) (err error)

PrepareInvoiceProjectRecords iterates through all projects and creates invoice records if none exists. Before creating invoice records, it ensures that all eligible users have a free tier coupon.

func (*Service) SetNow added in v1.6.1

func (service *Service) SetNow(now func() time.Time)

SetNow allows tests to have the Service act as if the current time is whatever they want. This avoids races and sleeping, making tests more reliable and efficient.

func (*Service) UpdateRates added in v0.26.0

func (service *Service) UpdateRates(ctx context.Context) (err error)

UpdateRates fetches new rates and updates service rate cache.

type StripeCharges added in v1.5.2

type StripeCharges interface {
	List(listParams *stripe.ChargeListParams) *charge.Iter
}

StripeCharges Stripe Charges interface.

type StripeClient added in v1.5.2

type StripeClient interface {
	Customers() StripeCustomers
	PaymentMethods() StripePaymentMethods
	Invoices() StripeInvoices
	InvoiceItems() StripeInvoiceItems
	CustomerBalanceTransactions() StripeCustomerBalanceTransactions
	Charges() StripeCharges
}

StripeClient Stripe client interface.

func NewStripeClient added in v1.5.2

func NewStripeClient(log *zap.Logger, config Config) StripeClient

NewStripeClient creates Stripe client from configuration.

func NewStripeMock added in v1.5.2

func NewStripeMock(id storj.NodeID, customersDB CustomersDB, usersDB console.Users) StripeClient

NewStripeMock creates new Stripe client mock.

A new mock is returned for each unique id. If this method is called multiple times with the same id, it will return the same mock instance for that id.

If called by satellite component, the id param should be the peer.ID(). If called by CLI tool, the id param should be a zero value, i.e. storj.NodeID{}. If called by satellitedb test case, the id param should be a random value, i.e. testrand.NodeID().

type StripeCustomerBalanceTransactions added in v1.5.2

type StripeCustomerBalanceTransactions interface {
	New(params *stripe.CustomerBalanceTransactionParams) (*stripe.CustomerBalanceTransaction, error)
	List(listParams *stripe.CustomerBalanceTransactionListParams) *customerbalancetransaction.Iter
}

StripeCustomerBalanceTransactions Stripe CustomerBalanceTransactions interface.

type StripeCustomers added in v1.5.2

type StripeCustomers interface {
	New(params *stripe.CustomerParams) (*stripe.Customer, error)
	Get(id string, params *stripe.CustomerParams) (*stripe.Customer, error)
	Update(id string, params *stripe.CustomerParams) (*stripe.Customer, error)
}

StripeCustomers Stripe Customers interface.

type StripeInvoiceItems added in v1.5.2

type StripeInvoiceItems interface {
	New(params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error)
	List(listParams *stripe.InvoiceItemListParams) *invoiceitem.Iter
}

StripeInvoiceItems Stripe InvoiceItems interface.

type StripeInvoices added in v1.5.2

type StripeInvoices interface {
	New(params *stripe.InvoiceParams) (*stripe.Invoice, error)
	List(listParams *stripe.InvoiceListParams) *invoice.Iter
	FinalizeInvoice(id string, params *stripe.InvoiceFinalizeParams) (*stripe.Invoice, error)
}

StripeInvoices Stripe Invoices interface.

type StripePaymentMethods added in v1.5.2

type StripePaymentMethods interface {
	List(listParams *stripe.PaymentMethodListParams) *paymentmethod.Iter
	New(params *stripe.PaymentMethodParams) (*stripe.PaymentMethod, error)
	Attach(id string, params *stripe.PaymentMethodAttachParams) (*stripe.PaymentMethod, error)
	Detach(id string, params *stripe.PaymentMethodDetachParams) (*stripe.PaymentMethod, error)
}

StripePaymentMethods Stripe PaymentMethods interface.

type Transaction

type Transaction struct {
	ID        coinpayments.TransactionID
	AccountID uuid.UUID
	Address   string
	Amount    big.Float
	Received  big.Float
	Status    coinpayments.Status
	Key       string
	Timeout   time.Duration
	CreatedAt time.Time
}

Transaction defines coinpayments transaction info that is stored in the DB.

type TransactionAndUserList added in v0.31.4

type TransactionAndUserList map[coinpayments.TransactionID]uuid.UUID

TransactionAndUserList is a composite type for storing userID and txID.

func (TransactionAndUserList) IDList added in v0.31.4

IDList returns transaction id list.

type TransactionUpdate

type TransactionUpdate struct {
	TransactionID coinpayments.TransactionID
	Status        coinpayments.Status
	Received      big.Float
}

TransactionUpdate holds transaction update info.

type TransactionsDB

type TransactionsDB interface {
	// Insert inserts new coinpayments transaction into DB.
	Insert(ctx context.Context, tx Transaction) (*Transaction, error)
	// Update updates status and received for set of transactions.
	Update(ctx context.Context, updates []TransactionUpdate, applies coinpayments.TransactionIDList) error
	// Consume marks transaction as consumed, so it won't participate in apply account balance loop.
	Consume(ctx context.Context, id coinpayments.TransactionID) error
	// LockRate locks conversion rate for transaction.
	LockRate(ctx context.Context, id coinpayments.TransactionID, rate *big.Float) error
	// GetLockedRate returns locked conversion rate for transaction or error if non exists.
	GetLockedRate(ctx context.Context, id coinpayments.TransactionID) (*big.Float, error)
	// ListAccount returns all transaction for specific user.
	ListAccount(ctx context.Context, userID uuid.UUID) ([]Transaction, error)
	// ListPending returns TransactionsPage with pending transactions.
	ListPending(ctx context.Context, offset int64, limit int, before time.Time) (TransactionsPage, error)
	// List Unapplied returns TransactionsPage with completed transaction that should be applied to account balance.
	ListUnapplied(ctx context.Context, offset int64, limit int, before time.Time) (TransactionsPage, error)
}

TransactionsDB is an interface which defines functionality of DB which stores coinpayments transactions.

architecture: Database

type TransactionsPage

type TransactionsPage struct {
	Transactions []Transaction
	Next         bool
	NextOffset   int64
}

TransactionsPage holds set of transaction and indicates if there are more transactions to fetch.

func (*TransactionsPage) CreationTimes added in v1.8.1

func (page *TransactionsPage) CreationTimes() map[coinpayments.TransactionID]time.Time

CreationTimes returns a map of creation times of page's transactions.

func (*TransactionsPage) IDList

IDList returns transaction id list of page's transactions.

type VersionService added in v0.26.0

type VersionService struct {
	Cycle sync2.Cycle
	// contains filtered or unexported fields
}

VersionService updates conversion rates in a loop.

architecture: Service

func NewVersionService added in v0.26.0

func NewVersionService(log *zap.Logger, service *Service, interval time.Duration) *VersionService

NewVersionService creates new instance of VersionService.

func (*VersionService) Close added in v0.26.0

func (version *VersionService) Close() (err error)

Close closes underlying cycle.

func (*VersionService) Run added in v0.26.0

func (version *VersionService) Run(ctx context.Context) (err error)

Run runs loop which updates conversion rates for service.

Jump to

Keyboard shortcuts

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