stripe

package
v1.110.5 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2024 License: AGPL-3.0 Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MockCouponID1 is a coupon that stripe mock is aware of. Applying unknown coupons results in failure.
	MockCouponID1 = "c1"
	// MockCouponID2 is a coupon that stripe mock is aware of. Applying unknown coupons results in failure.
	MockCouponID2 = "c2"
	// MockCouponID3 is a coupon that stripe mock is aware of. Applying unknown coupons results in failure.
	MockCouponID3 = "c3"

	// MockInvoicesNewFailure can be passed to mockInvoices.New as `desc` argument to cause it to return
	// an error.
	MockInvoicesNewFailure = "mock_invoices_new_failure"

	// MockInvoicesPayFailure can be passed to mockInvoices.Pay as params.PaymentMethod to cause it to return
	// an error.
	MockInvoicesPayFailure = "mock_invoices_pay_failure"

	// MockInvoicesPaySuccess can be passed to mockInvoices.Pay as params.PaymentMethod to cause it to return
	// a paid invoice.
	MockInvoicesPaySuccess = "mock_invoices_pay_success"

	// TestPaymentMethodsNewFailure can be passed to creditCards.Add as the cardToken arg to cause
	// mockPaymentMethods.New to return an error.
	TestPaymentMethodsNewFailure = "test_payment_methods_new_failure"

	// TestPaymentMethodsAttachFailure can be passed to creditCards.Add as the cardToken arg to cause
	// mockPaymentMethods.Attach to return an error.
	TestPaymentMethodsAttachFailure = "test_payment_methods_attach_failure"

	// MockCBTXsNewFailure can be passed to mockCustomerBalanceTransactions.New as the `desc` argument to cause it
	// to return an error.
	MockCBTXsNewFailure = "mock_cbtxs_new_failure"
)
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"
)

Variables

View Source
var (
	// ErrCardNotFound is returned when card is not found for a user.
	ErrCardNotFound = errs.Class("card not found")
	// ErrDefaultCard is returned when a user tries to delete their default card.
	ErrDefaultCard = errs.Class("default card")
	// ErrDuplicateCard is returned when a user tries to add duplicate card.
	ErrDuplicateCard = errs.Class("duplicate card")

	// UnattachedErrString is part of the err string returned by stripe if a payment
	// method does not belong to a customer.
	UnattachedErrString = "The payment method must be attached to the customer"
)
View Source
var ErrInvalidTaxID = errs.Class("Invalid tax ID value")

ErrInvalidTaxID is returned when a tax ID value is invalid.

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 (
	// Error defines stripecoinpayments service error.
	Error = errs.Class("stripecoinpayments service")
)

Functions

This section is empty.

Types

type BackendWrapper

type BackendWrapper struct {
	// contains filtered or unexported fields
}

BackendWrapper is a wrapper for the Stripe backend that uses an exponential backoff strategy for retrying Stripe API calls.

func NewBackendWrapper

func NewBackendWrapper(log *zap.Logger, backendType stripe.SupportedBackend, retryCfg RetryConfig) *BackendWrapper

NewBackendWrapper creates a new wrapper for a Stripe backend.

func (*BackendWrapper) Call

func (w *BackendWrapper) Call(method, path, key string, params stripe.ParamsContainer, v stripe.LastResponseSetter) error

Call implements the stripe.Backend interface.

func (*BackendWrapper) CallMultipart

func (w *BackendWrapper) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *stripe.Params, v stripe.LastResponseSetter) error

CallMultipart implements the stripe.Backend interface.

func (*BackendWrapper) CallRaw

func (w *BackendWrapper) CallRaw(method, path, key string, body *form.Values, params *stripe.Params, v stripe.LastResponseSetter) error

CallRaw implements the stripe.Backend interface.

func (*BackendWrapper) CallStreaming

func (w *BackendWrapper) CallStreaming(method, path, key string, params stripe.ParamsContainer, v stripe.StreamingLastResponseSetter) error

CallStreaming implements the stripe.Backend interface.

func (*BackendWrapper) SetMaxNetworkRetries

func (w *BackendWrapper) SetMaxNetworkRetries(max int64)

SetMaxNetworkRetries sets the maximum number of times to retry failed requests.

func (*BackendWrapper) TestSwapBackend

func (w *BackendWrapper) TestSwapBackend(backend stripe.Backend)

TestSwapBackend replaces the wrapped backend with the one specified for use in testing.

func (*BackendWrapper) TestSwapClock

func (w *BackendWrapper) TestSwapClock(clock time2.Clock)

TestSwapClock replaces the internal clock with the one specified for use in testing.

type Charges

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

Charges Stripe Charges interface.

type Client

type Client interface {
	Customers() Customers
	PaymentMethods() PaymentMethods
	Invoices() Invoices
	InvoiceItems() InvoiceItems
	CustomerBalanceTransactions() CustomerBalanceTransactions
	Charges() Charges
	PromoCodes() PromoCodes
	CreditNotes() CreditNotes
	TaxIDs() TaxIDs
}

Client Stripe client interface.

func NewStripeClient

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

NewStripeClient creates Stripe client from configuration.

func NewStripeMock

func NewStripeMock(customersDB CustomersDB, usersDB console.Users) Client

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 Config

type Config struct {
	StripeSecretKey        string `help:"stripe API secret key" default:""`
	StripePublicKey        string `help:"stripe API public key" default:""`
	StripeFreeTierCouponID string `help:"stripe free tier coupon ID" default:""`
	AutoAdvance            bool   `help:"toggle 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"`
	SkipEmptyInvoices      bool   `help:"if set, skips the creation of empty invoices for customers with zero usage for the billing period" default:"true"`
	MaxParallelCalls       int    `help:"the maximum number of concurrent Stripe API calls in invoicing methods" default:"10"`
	RemoveExpiredCredit    bool   `help:"whether to remove expired package credit or not" default:"true"`
	UseIdempotency         bool   `help:"whether to use idempotency for create/update requests" default:"false"`
	Retries                RetryConfig
}

Config stores needed information for payment service initialization.

type CreateProjectRecord

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

CreateProjectRecord holds info needed for creation new invoice project record.

type CreditNotes

type CreditNotes interface {
	New(params *stripe.CreditNoteParams) (*stripe.CreditNote, error)
}

CreditNotes Stripe CreditNotes interface.

type Customer

type Customer struct {
	ID                 string
	BillingID          *string
	UserID             uuid.UUID
	PackagePlan        *string
	PackagePurchasedAt *time.Time
}

Customer holds customer id, user id, and package information.

type CustomerBalanceTransactions

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

CustomerBalanceTransactions Stripe CustomerBalanceTransactions interface.

type Customers

type Customers 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)
	List(listParams *stripe.CustomerListParams) *customer.Iter
}

Customers Stripe Customers interface.

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)
	// GetUserID return userID given stripe customer id.
	GetUserID(ctx context.Context, customerID string) (uuid.UUID, error)
	// List returns page with customers ids created before specified date.
	List(ctx context.Context, userIDCursor uuid.UUID, limit int, before time.Time) (CustomersPage, error)
	// UpdatePackage updates the customer's package plan and purchase time.
	UpdatePackage(ctx context.Context, userID uuid.UUID, packagePlan *string, timestamp *time.Time) (*Customer, error)
	// GetPackageInfo returns the package plan and time of purchase for a user.
	GetPackageInfo(ctx context.Context, userID uuid.UUID) (packagePlan *string, purchaseTime *time.Time, err error)
	// GetStripeIDs returns stripe customer and billing ids.
	GetStripeIDs(ctx context.Context, userID uuid.UUID) (billingID *string, customerID string, err error)
	// UpdateBillingCustomerID updates the customer's billing id.
	UpdateBillingCustomerID(ctx context.Context, userID uuid.UUID, billingID *string) (*Customer, error)

	// ListMissingCustomers lists users that have a missing stripe entry.
	ListMissingCustomers(ctx context.Context) (_ []MissingCustomer, err error)
}

CustomersDB is interface for working with stripe customers table.

architecture: Database

type CustomersPage

type CustomersPage struct {
	Customers []Customer
	Next      bool
	Cursor    uuid.UUID
}

CustomersPage holds customers and indicates if there is more data available and provides cursor for next page.

type DB

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
}

DB is stripecoinpayments DB interface.

architecture: Database

type InvoiceItems

type InvoiceItems interface {
	New(params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error)
	Update(id string, params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error)
	List(listParams *stripe.InvoiceItemListParams) *invoiceitem.Iter
	Del(id string, params *stripe.InvoiceItemParams) (*stripe.InvoiceItem, error)
}

InvoiceItems Stripe InvoiceItems interface.

type Invoices

type Invoices interface {
	New(params *stripe.InvoiceParams) (*stripe.Invoice, error)
	List(listParams *stripe.InvoiceListParams) *invoice.Iter
	Update(id string, params *stripe.InvoiceParams) (*stripe.Invoice, error)
	FinalizeInvoice(id string, params *stripe.InvoiceFinalizeInvoiceParams) (*stripe.Invoice, error)
	Pay(id string, params *stripe.InvoicePayParams) (*stripe.Invoice, error)
	Del(id string, params *stripe.InvoiceParams) (*stripe.Invoice, error)
	Get(id string, params *stripe.InvoiceParams) (*stripe.Invoice, error)
	MarkUncollectible(id string, params *stripe.InvoiceMarkUncollectibleParams) (*stripe.Invoice, error)
	VoidInvoice(id string, params *stripe.InvoiceVoidInvoiceParams) (*stripe.Invoice, error)
}

Invoices Stripe Invoices interface.

type MissingCustomer added in v1.108.1

type MissingCustomer struct {
	ID              uuid.UUID
	Email           string
	SignupPromoCode string
}

MissingCustomer holds customer id, user id, and package information.

type PaymentMethods

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

PaymentMethods Stripe PaymentMethods interface.

type ProjectRecord

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

ProjectRecord holds project usage particular for billing period.

type ProjectRecordsDB

type ProjectRecordsDB interface {
	// Create creates new invoice project record with credits spendings in the DB.
	Create(ctx context.Context, records []CreateProjectRecord, start, end time.Time) error
	// CreateToBeAggregated creates new to be aggregated invoice project record with credits spendings in the DB.
	CreateToBeAggregated(ctx context.Context, records []CreateProjectRecord, 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)
	// GetUnappliedByProjectIDs returns unapplied records within the billing period pertaining to a list of project IDs.
	GetUnappliedByProjectIDs(ctx context.Context, projectIDs []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.
	// Cursor is not included into listing results.
	ListUnapplied(ctx context.Context, cursor uuid.UUID, limit int, start, end time.Time) (ProjectRecordsPage, error)
	// ListToBeAggregated returns to be aggregated project records page with unapplied project records.
	// Cursor is not included into listing results.
	ListToBeAggregated(ctx context.Context, cursor uuid.UUID, limit int, start, end time.Time) (ProjectRecordsPage, error)
}

ProjectRecordsDB is interface for working with invoice project records.

architecture: Database

type ProjectRecordsPage

type ProjectRecordsPage struct {
	Records []ProjectRecord
	Next    bool
	Cursor  uuid.UUID
}

ProjectRecordsPage holds project records and indicates if there is more data available and provides cursor for next listing.

type PromoCodes

type PromoCodes interface {
	List(params *stripe.PromotionCodeListParams) *promotioncode.Iter
}

PromoCodes is the Stripe PromoCodes interface.

type RetryConfig

type RetryConfig struct {
	InitialBackoff time.Duration `help:"the duration of the first retry interval" default:"20ms"`
	MaxBackoff     time.Duration `help:"the maximum duration of any retry interval" default:"5s"`
	Multiplier     float64       `help:"the factor by which the retry interval will be multiplied on each iteration" default:"2"`
	MaxRetries     int64         `help:"the maximum number of times to retry a request" default:"10"`
}

RetryConfig contains the configuration for an exponential backoff strategy when retrying Stripe API calls.

type Service

type Service struct {

	// BonusRate amount of percents
	BonusRate int64
	// Coupon Values
	StripeFreeTierCouponID string

	// Stripe Extended Features
	AutoAdvance bool
	// 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 Client, config Config, db DB, walletsDB storjscan.WalletsDB, billingDB billing.TransactionsDB, projectsDB console.Projects, usersDB console.Users, usageDB accounting.ProjectAccounting, usagePrices payments.ProjectUsagePriceModel, usagePriceOverrides map[string]payments.ProjectUsagePriceModel, packagePlans map[string]payments.PackagePlan, bonusRate int64, analyticsService *analytics.Service, emissionService *emission.Service, deleteAccountEnabled bool) (*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) ApplyFreeTierCoupons

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

ApplyFreeTierCoupons iterates through all customers in Stripe. For each customer, if that customer does not currently have a Stripe coupon, the free tier Stripe coupon is applied.

func (*Service) CompletePendingInvoiceTokenPayments added in v1.90.1

func (service *Service) CompletePendingInvoiceTokenPayments(ctx context.Context, pendingPayments []string) (err error)

CompletePendingInvoiceTokenPayments updates the status of the pending invoice token payment to complete.

func (*Service) CreateBalanceInvoiceItems added in v1.78.1

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

CreateBalanceInvoiceItems will find users with a stripe balance, create an invoice item with the charges due, and zero out the stripe balance.

func (*Service) CreateInvoices

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

CreateInvoices lists through all customers, removes expired credit if applicable, and creates invoices.

func (*Service) FailPendingInvoiceTokenPayments added in v1.90.1

func (service *Service) FailPendingInvoiceTokenPayments(ctx context.Context, pendingPayments []string) (err error)

FailPendingInvoiceTokenPayments marks all specified pending invoice token payments as failed, and refunds the pending charges.

func (*Service) FinalizeInvoices

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

FinalizeInvoices transitions all draft invoices to open finalized invoices in stripe. No payment is to be collected yet.

func (*Service) GenerateInvoices

func (service *Service) GenerateInvoices(ctx context.Context, period time.Time, shouldAggregate, groupInvoiceItems, includeEmissionInfo bool) (err error)

GenerateInvoices performs tasks necessary to generate Stripe invoices. This is equivalent to invoking PrepareInvoiceProjectRecords, InvoiceApplyProjectRecords, and CreateInvoices in order.

func (*Service) Healthy added in v1.107.1

func (service *Service) Healthy(ctx context.Context) bool

Healthy returns true if this service can contact stripe.

func (*Service) InvoiceApplyCustomerTokenBalance added in v1.84.1

func (service *Service) InvoiceApplyCustomerTokenBalance(ctx context.Context, customerID string) (err error)

InvoiceApplyCustomerTokenBalance creates invoice credit notes for the customers token payments to open invoices.

func (*Service) InvoiceApplyProjectRecords

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) InvoiceApplyProjectRecordsGrouped added in v1.105.2

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

InvoiceApplyProjectRecordsGrouped iterates the customers and creates invoice items for each project and ensures line items are grouped by project.

func (*Service) InvoiceApplyToBeAggregatedProjectRecords added in v1.93.1

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

InvoiceApplyToBeAggregatedProjectRecords iterates through to be aggregated invoice project records and creates invoice line items for stripe customer.

func (*Service) InvoiceApplyTokenBalance

func (service *Service) InvoiceApplyTokenBalance(ctx context.Context, createdOnAfter time.Time) (err error)

InvoiceApplyTokenBalance iterates through customer storjscan wallets and creates invoice credit notes for stripe customers with invoices on or after the given date.

func (*Service) InvoiceItemsFromProjectUsage

func (service *Service) InvoiceItemsFromProjectUsage(projName string, partnerUsages map[string]accounting.ProjectUsage, aggregated bool) (result []*stripe.InvoiceItemParams)

InvoiceItemsFromProjectUsage calculates Stripe invoice item from project usage.

func (*Service) Name added in v1.107.1

func (service *Service) Name() string

Name returns the name of this service.

func (*Service) PayCustomerInvoices added in v1.84.1

func (service *Service) PayCustomerInvoices(ctx context.Context, customerID string) (err error)

PayCustomerInvoices attempts to transition all open finalized invoices created on or after a certain time to "paid" by charging the customer according to subscriptions settings.

func (*Service) PayInvoices

func (service *Service) PayInvoices(ctx context.Context, createdOnAfter time.Time) (err error)

PayInvoices attempts to transition all open finalized invoices created on or after a certain time to "paid" by charging the customer according to subscriptions settings.

func (*Service) PayInvoicesWithTokenBalance added in v1.84.1

func (service *Service) PayInvoicesWithTokenBalance(ctx context.Context, userID uuid.UUID, cusID string, invoices []stripe.Invoice) (err error)

PayInvoicesWithTokenBalance attempts to transition all the users open invoices to "paid" by charging the customer token balance.

func (*Service) PrepareInvoiceProjectRecords

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

PrepareInvoiceProjectRecords iterates through all projects and creates invoice records if none exist.

func (*Service) RemoveExpiredPackageCredit added in v1.80.3

func (service *Service) RemoveExpiredPackageCredit(ctx context.Context, customer Customer) (sentEvent bool, err error)

RemoveExpiredPackageCredit removes a user's package plan credit, or sends an analytics event, if it has expired. If the user has never received credit from anything other than the package, and it is expired, the remaining package credit is removed. If the user has received credit from another source, we send an analytics event instead of removing the remaining credit so someone can remove it manually. `sentEvent` indicates whether this analytics event was sent.

func (*Service) SetInvoiceStatus added in v1.83.2

func (service *Service) SetInvoiceStatus(ctx context.Context, startPeriod, endPeriod time.Time, status string, dryRun bool) (err error)

SetInvoiceStatus will set all open invoices within the specified date range to the requested status.

func (*Service) SetNow

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.

type TaxIDs added in v1.104.1

type TaxIDs interface {
	New(params *stripe.TaxIDParams) (*stripe.TaxID, error)
	Del(id string, params *stripe.TaxIDParams) (*stripe.TaxID, error)
}

TaxIDs is the Stripe TaxIDs interface.

type Transaction

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

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

type TransactionsDB

type TransactionsDB interface {
	// GetLockedRate returns locked conversion rate for transaction or error if non exists.
	GetLockedRate(ctx context.Context, id coinpayments.TransactionID) (decimal.Decimal, error)
	// ListAccount returns all transaction for specific user.
	ListAccount(ctx context.Context, userID uuid.UUID) ([]Transaction, error)
	// TestInsert inserts new coinpayments transaction into DB.
	TestInsert(ctx context.Context, tx Transaction) (time.Time, error)
	// TestLockRate locks conversion rate for transaction.
	TestLockRate(ctx context.Context, id coinpayments.TransactionID, rate decimal.Decimal) error
}

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

architecture: Database

Jump to

Keyboard shortcuts

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