pay

package module
v0.0.0-...-1e90118 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2023 License: MIT Imports: 10 Imported by: 0

README

Bronzecod Payment SDK

Go Reference

Provides an interface to the bronzecod Payments server REST API for managing

  • customer accounts
  • customer payment methods
  • charges
  • subscriptions
  • subscription line items

Usage

To connect to the API, you will need your API account API Key, API Secret, the baseURL for your platforms deployment.
With these, call Dial to create a new API connection and validate the credentials access.

    connection, err := pay.Dial("https://example.com/", apiKey, apiSecret, nil)
    if err != nil {
        // handle connection error
        // common causes:
        //   - incorrect baseURL
        //   - incorrect credentials
        //   - server running outside APIs configured whitelist
    }

    // use API connection here

If required, TLS configuration can be provided with the 4th argument.

Documentation

Each method in the SDK wraps the corresponding API endpoint in the reference manual provided with your deployment.
For specifics of each call, consult that manual.

Documentation on this specific package can be found in the Go reference documentation Go Reference

Documentation

Overview

Package pay is a golang SDK for the Bronzecod payments REST API

it provides type safe bindings for the APIs core features and entities as well as the various API endpoints available to get, enumerate and mutate them.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(a bool) *bool

Bool utility to create Bool pointers

func String

func String(a string) *string

String utility to create String pointers

func Time

func Time(a time.Time) *time.Time

Time utility to create Time pointers

func UUID

func UUID(a uuid.UUID) *uuid.UUID

UUID utility to create UUID pointers

Types

type Address

type Address struct {
	Name     string `json:"recipient,omitempty"`
	Phone    string `json:"contact,omitempty"`
	Line1    string `json:"line1"`
	Line2    string `json:"line2,omitempty"`
	City     string `json:"city"`
	State    string `json:"state"`
	PostCode string `json:"postCode"`
	Country  string `json:"country"`
}

Address collects the details of either a billing or shipping address

note: name and phone should never be populated for a billing address

type ChargeRequest

type ChargeRequest struct {
	Customer    *uuid.UUID        `json:"customer,omitempty"`
	Method      string            `json:"method,omitempty"`
	Amount      int64             `json:"amount"`
	Collect     *bool             `json:"collect"`
	Currency    string            `json:"currency"`
	Description string            `json:"description"`
	Statement   string            `json:"statement"`
	Voucher     string            `json:"voucher"`
	Metadata    map[string]string `json:"metadata"`
}

ChargeRequest handles a request to charge a user while offline Either a customer ID or a stripe payment method ID must be provided

setting collect to false will create the charge but not capture and settle the transaction in this case the returned transaction ID may be used in the ChargeCapture endpoint to collect the funds

type ChargeView

type ChargeView struct {
	Currency            string            `json:"currency"`
	Amount              int64             `json:"amount"`
	Description         *string           `json:"description"`
	StatementDescriptor *string           `json:"statementDescriptor"`
	For                 *uuid.UUID        `json:"for"`
	Customer            *uuid.UUID        `json:"customer"`
	Method              *string           `json:"method"`
	UseOffSession       *bool             `json:"usage"`
	Collect             *bool             `json:"collect"`
	Details             *bool             `json:"details"`
	Shipping            *bool             `json:"shipping"`
	AllowSave           *bool             `json:"allowSave"`
	AllowSignup         *bool             `json:"allowSignup"`
	Metadata            map[string]string `json:"metadata"`
}

ChargeView wraps the information to prepare a view of a charge for a user

type Connection

type Connection interface {

	// Charge will create and optionally resolve the described charge, either billing the identified customer, or
	// creating a pending collect request that may be resolved later
	Charge(req ChargeRequest) (string, error)
	// ChargeCapture will resolve the identified pending capture, charging the identified amount and closing the request
	ChargeCapture(id string, amount int64) error

	// CustomerPlatformList returns a summary list of all customers available on the platform for the requesting account
	CustomerPlatformList() ([]Customer, error)
	// CustomerGet retrieves the customer with the corresponding ID, and optionally their billing sources based on the provided source mode
	CustomerGet(id uuid.UUID, sources SourceMode) (Customer, error)
	// CustomerGetFor retrieves the customer with the corresponding for identifier, and optionally their billing sources based on the provided source mode
	CustomerGetFor(target uuid.UUID, sources SourceMode) (Customer, error)
	// CustomerGetUserAccess retrieves all customers a user has access permissions to, and optionally their billing sources based on the provided source mode
	CustomerGetUserAccess(user uuid.UUID, sources SourceMode, queryCondition *QueryCondition) ([]Customer, error)

	// CustomerNew creates a new customer with the provided details for the "for" target identifier, name, email, phone, description, payment method token and metadata
	CustomerNew(target uuid.UUID, name, email, phone, description, token string, metadata map[string]string) (Customer, error)
	// CustomerUpdateDetails updates the identified customers labelling details (name, email, phone and description)
	CustomerUpdateDetails(id uuid.UUID, name, email, phone, description string) error
	// CustomerUpdateAddress updates a customers address details, either their billing or shipping address
	CustomerUpdateAddress(id uuid.UUID, isShipping bool, addr Address) error
	// CustomerDelete deletes the identified customer
	CustomerDelete(id uuid.UUID) error

	// CustomerSourceGet gets the "current" source of the identified customer, or their most recent if none are set as "current"
	CustomerSourceGet(id uuid.UUID) (Source, error)
	// CustomerSourceDefault gets the "default source of the identified customer, or the most recent if none are set as "default"
	CustomerSourceDefault(customer uuid.UUID) (Source, error)
	// CustomerSourceList lists all valid payment sources on a customer
	CustomerSourceList(customer uuid.UUID) ([]Source, error)

	// CustomerSourceAdd adds a tokenized payment method to the identified customer
	CustomerSourceAdd(customer uuid.UUID, method string) (Source, error)
	// CustomerSourceRemove removes a stored payment method from its customer, and the platform
	CustomerSourceRemove(id uuid.UUID) error

	// SubscriptionGet retrieves the subscription identified, with the line items populated according to the provided lines mode
	SubscriptionGet(id uuid.UUID, lines LinesMode) (Subscription, error)
	// SubscriptionFor retrieves the list of subscriptions for a given target, with the line items populated according to the provided lines mode
	SubscriptionFor(target uuid.UUID, lines LinesMode) ([]Subscription, error)
	// SubscriptionCustomer retrieves all subscriptions a customer pays, with the line items populated according to the provided lines mode
	SubscriptionCustomer(customer uuid.UUID, lines LinesMode) ([]Subscription, error)

	// SubscriptionNew creates a new subscription with the given details for paying customer, target product/permission, line items and setup costs
	SubscriptionNew(customer uuid.UUID, target uuid.UUID, lines, setup []SubscriptionNewPlan, metadata map[string]string, voucher string) (Subscription, error)
	// SubscriptionUpdateMetadata updates the identified subscriptions metadata with the provided values, either replacing the existing metadata or merging them based on the flag
	SubscriptionUpdateMetadata(id uuid.UUID, metadata map[string]string, merge bool) error
	// SubscriptionDelete deletes the identified subscription
	SubscriptionDelete(id uuid.UUID) error

	// SubscriptionGetLines retrieves line items for a subscription subject to the lines mode provided
	SubscriptionGetLines(subscription uuid.UUID, lines LinesMode) ([]LineItem, error)

	// SubscriptionLineNew creates a new line item in the identified subscription with the given plan key, quantity and whether to prorate billing or bill for the whole period
	SubscriptionLineNew(subscription uuid.UUID, plan string, quantity int64, prorate bool) (LineItem, error)
	// SubscriptionLineUpdate updates a subscription line item, changing it quantity, notating if the quantity is a change or a delta, and if the change should be prorated
	SubscriptionLineUpdate(id uuid.UUID, quantity int64, delta, prorate bool) error
	// SubscriptionLineDelete deletes the identified line item from its subscription
	SubscriptionLineDelete(id uuid.UUID) error
	// SubscriptionInvoiceExtraNewFromPlan adds an invoice item to the identified subscription that will appear on the next invoice but not recur. Uses the identified plan key and quantity
	SubscriptionInvoiceExtraNewFromPlan(subscription uuid.UUID, plan string, quantity int64) (InvoiceItem, error)
	// SubscriptionInvoiceExtraNewWithDetails adds an invoice item to the identified subscription, providing specific details for the line item such as quantity, unit price, a title and description.
	SubscriptionInvoiceExtraNewWithDetails(subscription uuid.UUID, unitPrice int64, quantity int64, title, description string) (InvoiceItem, error)
	// SubscriptionInvoiceExtraDelete removes an un-charged invoice item from the next invoice of its subscription
	SubscriptionInvoiceExtraDelete(key string) error

	// VoucherExists checks if the provided voucher key exists and is currently valid
	VoucherExists(key string) (exists bool, valid bool, err error)
	// VoucherGet retrieves the voucher with the provided key
	VoucherGet(key string) (Voucher, error)
	// VoucherList lists all vouchers on the current platform (optionally filtered to only those currently valid)
	VoucherList(activeOnly bool) ([]Voucher, error)

	// VoucherNewPayment creates a new voucher that can be used to discount payments (charges) with the provided details
	VoucherNewPayment(key string, percent float64, amount int64, useLimit uint, expiry *time.Time) (Voucher, error)
	// VoucherNewSubscription creates a new voucher that can be used to discount subscriptions recurrently, with the provided details
	VoucherNewSubscription(key string, trial int64, stripeCoupon string, useLimit uint, expiry *time.Time) (Voucher, error)
	// VoucherDelete deletes the identified voucher from the platform
	VoucherDelete(key string) error

	// ChargeViewPrepare creates a view url to charge a customer with the provided details
	ChargeViewPrepare(req ChargeView) (ViewDescriptor, error)
	// CustomerViewPrepare creates a view url to display a customers billing details, or collect the details of a new customer
	CustomerViewPrepare(req CustomerView) (ViewDescriptor, error)
	// CustomerViewResolve resolves the collected details from a customer details collect view (CustomerViewPrepare) and uses the resultant token to create a customer with the provided details
	CustomerViewResolve(token, name, phone, email string) (Customer, error)
	// SubscriptionViewPrepare creates a view url to view, create or update a subscription with the provided details
	SubscriptionViewPrepare(req SubscriptionView) (ViewDescriptor, error)
}

Connection is an instance of a connection to the bronzecod Payments server each function corresponds to a synchronous API call to the server

func Dial

func Dial(baseurl, user, password string, tls *tls.Config) (Connection, error)

Dial a new connection to a bronzecod sso instance

type Customer

type Customer struct {
	ID          uuid.UUID         `json:"id"`
	CreatedAt   time.Time         `json:"createdAt"`
	UpdatedAt   time.Time         `json:"updatedAt"`
	For         uuid.UUID         `json:"for"`
	Name        string            `json:"name,omitempty"`
	Email       string            `json:"email"`
	Phone       string            `json:"phone"`
	Description string            `json:"description"`
	Currency    string            `json:"currency"`
	Balance     int64             `json:"balance"`
	MetaData    map[string]string `json:"metaData"`
	Address     *Address          `json:"Address,omitempty"`
	Shipping    *Address          `json:"Shipping,omitempty"`
	Sources     []Source          `json:"sources,omitempty"`
}

Customer represents a recorded recurring customer collecting general details of the customer, eternal references an internal balance, and a collection of payment sources

type CustomerView

type CustomerView struct {
	Customer    *uuid.UUID        `json:"customer"`
	For         *uuid.UUID        `json:"for"`
	Description *string           `json:"description"`
	Types       []string          `json:"types"`
	SingleUse   *bool             `json:"singleUse"`
	OnSession   *bool             `json:"onSession"`
	Metadata    map[string]string `json:"metadata"`
}

CustomerView wraps the information to prepare a view of to collect/update customer details

type InvoiceItem

type InvoiceItem struct {
	ID          string `json:"id"`
	Amount      int64  `json:"amount"`
	Currency    string `json:"currency"`
	Date        int64  `json:"date"`
	Description string `json:"description"`
	Price       struct {
		ID string `json:"id"`
	} `json:"price"`
	Proration  bool              `json:"proration"`
	Quantity   int64             `json:"quantity"`
	UnitAmount int64             `json:"unit_amount"`
	Metadata   map[string]string `json:"metadata"`
}

InvoiceItem is a simplifies stripe.InvoiceItem used for transport

type LineItem

type LineItem struct {
	ID           uuid.UUID `json:"id"`
	CreatedAt    time.Time `json:"createdat"`
	UpdatedAt    time.Time `json:"updatedat"`
	Subscription uuid.UUID `json:"subscription"`
	Plan         string    `json:"plan"`
	Quantity     int64     `json:"quantity"`
	Metered      bool      `json:"metered"`
	NonRecurring bool      `json:"nonRecurring"`
}

LineItem represents a single billing line on a subscription

note: Plan field is a stripe price ID, it is named plan for legacy support

note: NonRecurring being true indicates that line is an invoice item on the next invoice for the subscription and will not recur on subsequent invoices

type LinesMode

type LinesMode string

LinesMode defines the behavior for loading line items for a subscription during retrieval

const (
	// LinesNone loads no line items, leaving only the core subscription details
	LinesNone LinesMode = "none"
	// LinesBase loads only recurring line items on the subscription
	LinesBase LinesMode = "base"
	// LinesAll loads all line items, both recurring, and pending one off invoice items
	LinesAll LinesMode = "all"
)

the list of valid LinesMode constants

type QueryCondition

type QueryCondition struct {
	Key       string
	Condition string
}

QueryCondition is a wrapper type used to imply conditions when querying a list of customers for a user allowing constraints on required permission to that customer object by key and a regular expression condition

type Source

type Source struct {
	ID         uuid.UUID         `json:"id"`
	CreatedAt  time.Time         `json:"createdAt"`
	UpdatedAt  time.Time         `json:"updatedAt"`
	Customer   uuid.UUID         `json:"customer"`
	Name       string            `json:"name"`
	Source     string            `json:"source"`
	Identifier string            `json:"identifier"`
	Expiry     *time.Time        `json:"expiry,omitempty"`
	Address    *Address          `json:"address,omitempty"`
	Metadata   map[string]string `json:"metadata"`
}

Source is a payment method a customer may use to pay for a transaction

type SourceMode

type SourceMode string

SourceMode defines which of a users source list to retrieve

const (
	// SourceNone gets no sources for a customer
	SourceNone SourceMode = "none"
	// SourceCurrent gets only the current "default" or most recent valid source
	SourceCurrent SourceMode = "current"
	// SourceAll gets all a customers sources that are current and valid
	SourceAll SourceMode = "all"
)

type Subscription

type Subscription struct {
	ID        uuid.UUID          `json:"id"`
	CreatedAt time.Time          `json:"createdAt"`
	UpdatedAt time.Time          `json:"updatedAt"`
	Customer  uuid.UUID          `json:"customer"`
	For       uuid.UUID          `json:"for"`
	Status    SubscriptionStatus `json:"status"`
	PeriodEnd time.Time          `json:"periodEnd"`
	TrialEnd  time.Time          `json:"trialEnd"`
	Metadata  map[string]string  `json:"metadata"`
	Lines     []LineItem         `json:"lines"`
}

Subscription represents a recurring billing arrangement with a given customer

type SubscriptionNewPlan

type SubscriptionNewPlan struct {
	Plan     string `json:"plan"`
	Quantity int64  `json:"quantity"`
}

SubscriptionNewPlan wraps a pair of price/plan keys and the quantity of that plan

type SubscriptionStatus

type SubscriptionStatus string

SubscriptionStatus represents the valid states a subscription may be in

const (
	// StatusIncomplete the subscription has failed its initial invoice or the invoice after ending a trial period
	StatusIncomplete SubscriptionStatus = "incomplete"
	// StatusIncompleteExpired the subscription failed its initial billing and was not resolved, it is now expired and cannot be recovered
	StatusIncompleteExpired SubscriptionStatus = "incomplete_expired"
	// StatusTrialing the subscription is currently in a trial period and not billing
	StatusTrialing SubscriptionStatus = "trialing"
	// StatusActive the subscription is active and billing normally
	StatusActive SubscriptionStatus = "active"
	// StatusPastDue the most recent charge for the invoice failed, or, if using manual invoices, the invoice is not paid
	StatusPastDue SubscriptionStatus = "past_due"
	// StatusCancelling the subscription is currently active, but has been marked to cancel at the end of the current billing period
	StatusCancelling SubscriptionStatus = "cancelling"
	// StatusCanceled the subscription has ended
	StatusCanceled SubscriptionStatus = "canceled"
	// StatusUnpaid the subscription is configured to enter the unpaid state rather than cancel when invoices fail to be paid in the configured number of attempts
	StatusUnpaid SubscriptionStatus = "unpaid"
)

type SubscriptionView

type SubscriptionView struct {
	Subscription *uuid.UUID            `json:"subscription"`
	For          *uuid.UUID            `json:"for"`
	Customer     *uuid.UUID            `json:"customer"`
	CustomerFor  *uuid.UUID            `json:"customerFor"`
	Plans        []SubscriptionNewPlan `json:"plans"`
	Setup        []SubscriptionNewPlan `json:"setup"`
	Metadata     map[string]string     `json:"metadata"`
	Prorate      bool                  `json:"prorate"`
}

SubscriptionView wraps the information to prepare a view to create/update a subscription

type ViewDescriptor

type ViewDescriptor struct {
	Token string `json:"token"`
	URL   string `json:"url"`
}

ViewDescriptor describes a token used to create a payment server view

Token is the ID of the prepared view and its transaction, and where appropriate can be used to complete the transaction with subsequent server side step.

URL is the address a user should be redirected to in order to view the prepared page view

type Voucher

type Voucher struct {
	Key       string    `json:"key"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	// one off payments
	AmountOff  int64   `json:"amountOff"`
	PercentOff float64 `json:"percentOff"`
	// subscriptions
	TrialPeriod int64  `json:"trialPeriod"`
	Coupon      string `json:"coupon"`
	// limitations
	RemainingUses uint       `json:"remainingUses"`
	Expiry        *time.Time `json:"expiry"`
}

Voucher represents data about a string key that may be used to apply discounts and similar behavioral changes to charges and subscriptions

Jump to

Keyboard shortcuts

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