p400

package
v1.19.4 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	NewReaderChoice = iota
	RegisteredReaderChoice
)

this is a lookup for ActivationTypeLabels

Variables

View Source
var (
	// ErrActivateReaderFailed is for when a new RPC session could not be created for the reader
	ErrActivateReaderFailed = errors.New("couldn't communicate with the Reader. Please make sure your reader is online and on the same network as your device.\nSee our troubleshooting docs here: https://stripe.com/docs/terminal/readers/verifone-p400#troubleshooting")
	// ErrRegisterReaderFailed is for when adding the reader via the Stripe API could not be completed (likely bad reg code)
	ErrRegisterReaderFailed = errors.New("could not register the Reader due to an invalid reader code")
	// ErrReaderSelectionFailed is for when the user quit the CLI at the reader choice prompt
	ErrReaderSelectionFailed = errors.New("reader choice failed, no selection made")
	// ErrDiscoverReadersFailed is for when the call to Stripe failed for listing the readers registered to user's account
	ErrDiscoverReadersFailed = errors.New("reader discovery was unable to list readers")
	// ErrNoReadersRegistered is for when a user has elected to use a registered reader but the list for their account returns empty
	ErrNoReadersRegistered = errors.New("no readers currently registered")
	// ErrConnectionTokenFailed is for when the call to Stripe for a new Terminal connection token went wonky
	ErrConnectionTokenFailed = errors.New("could not create new connection token")
	// ErrNewRPCSessionFailed is for when a new RPC Session (via the Stripe API not Rabbit) could not be created
	ErrNewRPCSessionFailed = errors.New("could not create new Terminal session")
	// ErrNewPaymentIntentFailed is for when calling Stripe for a new shiny Payment Intent failed
	ErrNewPaymentIntentFailed = errors.New("could not create new Payment Intent")
	// ErrCapturePaymentIntentFailed is for when you need to manually collect the Payment Intent after a Payment Method is attached and it failed
	ErrCapturePaymentIntentFailed = errors.New("could not capture the Payment Intent")
	// ErrSetReaderDisplayFailed is for when the Rabbit call to update the reader display didn't work as planned
	ErrSetReaderDisplayFailed = errors.New("could not set the Reader's display")
	// ErrClearReaderDisplayFailed is for when you're canceling a payment collection and need to reset the display back to default splash but it failed
	ErrClearReaderDisplayFailed = errors.New("could not clear the Reader's display")
	// ErrCollectPaymentFailed is for when the Rabbit call for the reader to go into collect payment state failed
	ErrCollectPaymentFailed = errors.New("could not collect payment method")
	// ErrCollectPaymentTimeout is for when the user didn't boop the card on the reader in a reasonable time
	ErrCollectPaymentTimeout = errors.New("timed out waiting for payment to be presented")
	// ErrConfirmPaymentFailed is for when the Rabbit call to confirm the payment method collected has failed
	ErrConfirmPaymentFailed = errors.New("could not confirm the payment")
	// ErrQueryPaymentFailed is for when you're polling Rabbit to see if the user has booped their card on the reader yet but something went wrong
	ErrQueryPaymentFailed = errors.New("could not query the payment")
	// ErrDNSFailed is for when a reader's address could not be resolved by DNS while attempting to contact it via Rabbit Service
	ErrDNSFailed = errors.New("couldn't find your reader on the network. We think it's probably a DNS issue.\n See our troubleshooting docs here: https://stripe.com/docs/terminal/readers/verifone-p400#troubleshooting")
	// ErrRabbitRequestCreationFailed is for when a Rabbit Service request is being rolled and the first stage of setting it up with the http client instance fails
	ErrRabbitRequestCreationFailed = errors.New("could not prepare request for Reader")
	// ErrStripeForbiddenResponse is for when a Stripe API call fails due to Terminal resource calls not supporting restricted keys
	ErrStripeForbiddenResponse = errors.New("it seems that your Stripe API Key is either restricted or out of date. Are you using a valid Stripe Secret Key with the --api-key global flag for this command?")
	// ErrStripeGenericResponse is for when any non status code happens for a Stripe call that isn't a 200 or a 403. This should be exceedingly rare (famous last words)
	ErrStripeGenericResponse = errors.New("could not connect to Stripe, perhaps try again?")
)
View Source
var ActivationTypeLabels = []string{
	"New",
	"Already registered",
}

ActivationTypeLabels defines the string values offered as options to the user to prompt them to choose a new or registered reader We use these strings in a few places so defining them here cuts down on brittleness if they change

Functions

func ActivateTerminalRPCSession

func ActivateTerminalRPCSession(tsCtx TerminalSessionContext) (string, error)

ActivateTerminalRPCSession calls Rabbit Service for a new reader session and returns the resulting session token

func CallRabbitService

func CallRabbitService(tsCtx TerminalSessionContext, method string, methodContent interface{}, methodResponse interface{}, parentTraceID string) error

CallRabbitService takes a TerminalSessionContext and method information and calls that Rabbit Service RPC method

func CapturePaymentIntent

func CapturePaymentIntent(ctx context.Context, tsCtx TerminalSessionContext) error

CapturePaymentIntent manually captures the Payment Intent after a Payment Method is attached which is the required flow for collecting payments on the Terminal platform

func ClearReaderDisplay

func ClearReaderDisplay(tsCtx TerminalSessionContext) error

ClearReaderDisplay calls Rabbit Service and sets the reader display back to the splash screen and ends any payment collection status

func CollectPaymentMethod

func CollectPaymentMethod(tsCtx TerminalSessionContext, parentTraceID string) error

CollectPaymentMethod calls Rabbit Service to put reader in payment collection state

func ConfirmPayment

func ConfirmPayment(tsCtx TerminalSessionContext, paymentMethod interface{}, parentTraceID string) (string, error)

ConfirmPayment calls Rabbit Service to confirm the payment that it collected, using Payment Intent and Payment Method to do so

func CreatePaymentIntent

func CreatePaymentIntent(ctx context.Context, tsCtx TerminalSessionContext) (string, error)

CreatePaymentIntent calls the Stripe API to create a new Payment Intent in order to later attach a collected P400 payment to it returns the Payment Intent Id

func CreateRabbitServicePayload

func CreateRabbitServicePayload(method string, methodContent string, parentTraceID string, tsCtx TerminalSessionContext) bytes.Buffer

CreateRabbitServicePayload serializes the required information into a JSON payload used in calls to RabbitService

func GeneratePOSDeviceID

func GeneratePOSDeviceID(seed int64) string

GeneratePOSDeviceID creates a pseudorandom alpha string id for a point-of-sale quasi-unique identifier mostly used for TransactionContext related tracking / tracing and is semi-persistent to a machine but not determinant

func GetNewConnectionToken

func GetNewConnectionToken(ctx context.Context, tsCtx TerminalSessionContext) (string, error)

GetNewConnectionToken calls the Stripe API and requests a new connection token in order to start a new reader session it returns the connection token when successful

func GetOSString

func GetOSString() string

GetOSString finds which operating system the user is running and creates the correct string name for it to report to Rabbit Service when making a call this is mostly used by the TransactionContext properties

func ReaderChargeAmountPrompt

func ReaderChargeAmountPrompt() (int, error)

ReaderChargeAmountPrompt prompts the user to enter a monetary amount to charge as a test payment it converts the string the user entered into an integer and returns that

func ReaderChargeCurrencyPrompt

func ReaderChargeCurrencyPrompt() (string, error)

ReaderChargeCurrencyPrompt prompts the user for the currency they want to take a test payment in it returns the currency code that the user entered

func ReaderNewOrExistingPrompt

func ReaderNewOrExistingPrompt() (string, error)

ReaderNewOrExistingPrompt prompts the user to choose to set up a new reader, or continue with an already registered reader it returns their choice

func ReaderRegistrationCodePrompt

func ReaderRegistrationCodePrompt() (string, error)

ReaderRegistrationCodePrompt prompts the user to generate a new registration code on their P400 and asks them to enter it at the prompt it returns the code that the user typed in

func SetParentTraceID

func SetParentTraceID(transactionID int, methodID int, methodName string) string

SetParentTraceID creates a string in a specific format for other methods to use for communicating which transaction a Rabbit Service call is concerning it returns the created trace id string

func SetReaderDisplay

func SetReaderDisplay(tsCtx TerminalSessionContext, parentTraceID string) error

SetReaderDisplay calls Rabbit Service to set a cart's contents on the reader display

func StartNewRPCSession

func StartNewRPCSession(tsCtx TerminalSessionContext) (string, error)

StartNewRPCSession calls the Stripe API for a new RPC session token for interacting with a P400 reader returns a session token when successful

func SummarizeQuickstartCompletion

func SummarizeQuickstartCompletion(tsCtx TerminalSessionContext) error

SummarizeQuickstartCompletion is the success text that is output once the quickstart flow is completed. It lists the Payment Intent Dashboard URL, and the Terminal readers Dashboard URL

func WaitForPaymentCollection

func WaitForPaymentCollection(tsCtx TerminalSessionContext, parentTraceID string, tries int) (interface{}, error)

WaitForPaymentCollection is a recursive function that calls Rabbit Service to query the status of the payment that is waiting to be collected (ie. user booping card on the reader) it exits if it either errors querying the payment, or the payment is successfully collected it additionally times out with an error after querying for around 60 seconds returns the payment method collected by the reader

Types

type AppModel

type AppModel struct {
	AppID      string `json:"app_id"`
	AppVersion string `json:"app_version"`
}

AppModel belongs to the Rabbit Service RPC call payload shape

type Cart

type Cart struct {
	LineItems []LineItem `json:"line_items"`
	Tax       int        `json:"tax"`
	Total     int        `json:"total"`
	Currency  string     `json:"currency"`
}

Cart belongs to the ReaderDisplayContent protobuf sent to Rabbit Service that updates the reader display

type ChargeAmount

type ChargeAmount struct {
	ChargeAmount   int    `json:"charge_amount"`
	Currency       string `json:"currency"`
	TipAmount      int    `json:"tip_amount"`
	CashbackAmount int    `json:"cashback_amount"`
}

ChargeAmount belongs to the ReaderCollectPaymentContent protobuf send to Rabbit Service for collecting a specific payment after the Payment Intent is created

type ConfirmedPaymentIntent

type ConfirmedPaymentIntent struct {
	PaymentMethod string `json:"payment_method"`
}

ConfirmedPaymentIntent belongs to ReaderConfirmPaymentResponse

type DeviceInfo

type DeviceInfo struct {
	DeviceClass   string        `json:"device_class"`
	DeviceUUID    string        `json:"device_uuid"`
	HostOSVersion string        `json:"host_os_version"`
	HardwareModel HardwareModel `json:"hardware_model"`
	AppModel      AppModel      `json:"app_model"`
}

DeviceInfo belongs to the Rabbit Service RPC call payload shape

type HardwareModel

type HardwareModel struct {
	POSInfo POSInfo `json:"pos_info"`
}

HardwareModel belongs to the Rabbit Service RPC call payload shape

type LineItem

type LineItem struct {
	Description string `json:"description"`
	Amount      int    `json:"amount"`
	Quantity    int    `json:"quantity"`
}

LineItem belongs to the Cart protobuf shape for updating the reader display via Rabbit Service

type Metadata

type Metadata struct{}

Metadata belongs to the Stripe P400 reader object we don't currently make use of it directly for quickstart

type POSInfo

type POSInfo struct {
	Description string `json:"description"`
}

POSInfo belongs to the Rabbit Service RPC call payload shape

type POSSoftwareInfo

type POSSoftwareInfo struct {
	POSType    string `json:"pos_type"`
	SdkVersion string `json:"sdk_version"`
}

POSSoftwareInfo belongs to the Rabbit Service RPC call payload shape

type PaymentMethod

type PaymentMethod struct {
}

PaymentMethod exists only so that you can pass a pointer reference of it to generate an actual empty payment method object when using JSON serialization and have it not be serialized as null

type RabbitServicePayload

type RabbitServicePayload struct {
	ID            int         `json:"id"`
	Service       string      `json:"service"`
	Method        string      `json:"method"`
	Content       string      `json:"content"`
	SessionToken  string      `json:"session_token"`
	RequestType   string      `json:"request_type"`
	VersionInfo   versionInfo `json:"version_info"`
	ParentTraceID string      `json:"parent_trace_id"`
	DeviceInfo    DeviceInfo  `json:"device_info"`
}

RabbitServicePayload represents the JSON shape of all request bodies when calling Rabbit Service

type RabbitServiceResponse

type RabbitServiceResponse struct {
	Content string `json:"content"`
}

RabbitServiceResponse is the response body from the Rabbit Service call

type Reader

type Reader struct {
	ID              string   `json:"id"`
	Object          string   `json:"object"`
	DeviceSwVersion string   `json:"device_software_version"`
	DeviceType      string   `json:"device_type"`
	IPAddress       string   `json:"ip_address"`
	Label           string   `json:"label"`
	Livemode        bool     `json:"livemode"`
	Location        string   `json:"location"`
	SerialNumber    string   `json:"serial_number"`
	Status          string   `json:"status"`
	Metadata        Metadata `json:"metadata"`
	BaseURL         string   `json:"base_url"`
}

Reader represents the Stripe P400 reader object shape

func AttemptRegisterReader

func AttemptRegisterReader(ctx context.Context, tsCtx TerminalSessionContext, tries int) (Reader, error)

AttemptRegisterReader prompt the user for their p400 registration code, and tries to register the reader via Stripe API it tries three times before returning an error returns the registered reader's IP address if successful

func DiscoverReaders

func DiscoverReaders(ctx context.Context, tsCtx TerminalSessionContext) ([]Reader, error)

DiscoverReaders calls the Stripe API to get a list of currently registered P400 readers on the account it returns a map of Reader types

func RegisterReader

func RegisterReader(ctx context.Context, regcode string, tsCtx TerminalSessionContext) (Reader, error)

RegisterReader calls the Stripe API to register a new P400 reader to an account it returns the IP address of the reader if successful

func RegisteredReaderChoicePrompt

func RegisteredReaderChoicePrompt(readerList []Reader, tsCtx TerminalSessionContext) (Reader, error)

RegisteredReaderChoicePrompt takes a list of registered p400 readers and prompts the reader to choose one to use it returns the IP address of the chosen reader

type ReaderActivateContent

type ReaderActivateContent struct {
	POSActivationToken string          `json:"pos_activation_token"`
	StoreName          string          `json:"store_name"`
	POSDeviceID        string          `json:"pos_device_id"`
	POSSoftwareInfo    POSSoftwareInfo `json:"pos_software_info"`
}

ReaderActivateContent represents the shape of the serialized protobuf sent to Rabbit Service for activating a terminal session

type ReaderActivateResponse

type ReaderActivateResponse struct {
	SessionToken string `json:"session_token"`
}

ReaderActivateResponse is the RPC response from calling the activateTerminal method

type ReaderCollectPaymentContent

type ReaderCollectPaymentContent struct {
	ChargeAmount       ChargeAmount       `json:"charge_amount"`
	TransactionContext TransactionContext `json:"transaction_context"`
}

ReaderCollectPaymentContent represents the shape of the serialized protobuf sent to Rabbit Service for collecting a payment for a specific Payment Intent

type ReaderConfirmPaymentContent

type ReaderConfirmPaymentContent struct {
	PaymentIntentID    string             `json:"payment_intent_id"`
	PaymentMethod      interface{}        `json:"payment_method"`
	TransactionContext TransactionContext `json:"transaction_context"`
}

ReaderConfirmPaymentContent represents the shape of the serialized protobuf sent to Rabbit Service for confirming a payment after it is collectedf

type ReaderConfirmPaymentResponse

type ReaderConfirmPaymentResponse struct {
	SystemContext          interface{}            `json:"system_context"`
	RequestID              string                 `json:"request_id"`
	ConfirmedPaymentIntent ConfirmedPaymentIntent `json:"confirmed_payment_intent"`
}

ReaderConfirmPaymentResponse is the decoded RPC response from calling the processPayment reader method

type ReaderDisplayClearContent

type ReaderDisplayClearContent struct {
	TransactionContext TransactionContext `json:"transaction_context"`
}

ReaderDisplayClearContent represents the shape of the serialized protobuf sent to Rabbit Service for clearing the reader display

type ReaderDisplayContent

type ReaderDisplayContent struct {
	Type               string             `json:"type"`
	Cart               Cart               `json:"cart"`
	TransactionContext TransactionContext `json:"transaction_context"`
}

ReaderDisplayContent represents the shape of the serialized protobuf sent to Rabbit Service for updating the reader display

type ReaderQueryPaymentContent

type ReaderQueryPaymentContent struct {
	TransactionContext TransactionContext `json:"transaction_context"`
}

ReaderQueryPaymentContent represents the shape of the serialized protobuf sent to Rabbit Service for querying a payment for its collection state

type ReaderQueryPaymentResponse

type ReaderQueryPaymentResponse struct {
	PaymentMethod interface{} `json:"payment_method"`
	PaymentStatus string      `json:"payment_status"`
}

ReaderQueryPaymentResponse is the decoded RPC response from calling the queryPaymentMethod reader method

func QueryPaymentMethod

func QueryPaymentMethod(tsCtx TerminalSessionContext, parentTraceID string) (ReaderQueryPaymentResponse, error)

QueryPaymentMethod calls Rabbit Service to query the status of a payment currently being collected

type TerminalSessionContext

type TerminalSessionContext struct {
	APIKey             string
	IPAddress          string
	BaseURL            string
	LocationID         string
	PstToken           string
	SessionToken       string
	TransactionID      int
	MethodID           int
	TransactionContext TransactionContext
	DeviceInfo         DeviceInfo
	PaymentIntentID    string
	Amount             int
	Currency           string
}

TerminalSessionContext is a type that contains important context most methods need to know to complete the quickstart flow one copy of this is passed around a lot and is mutable for whenever a property needs to change

func CompleteTestPayment

func CompleteTestPayment(ctx context.Context, tsCtx TerminalSessionContext) (TerminalSessionContext, error)

CompleteTestPayment sets the reader into collect payment mode, waits for the payment, confirms the payment, then finally captures the Payment Intent

func RegisterAndActivateReader

func RegisterAndActivateReader(ctx context.Context, tsCtx TerminalSessionContext) (TerminalSessionContext, error)

RegisterAndActivateReader prompts the user to either add a new reader or choose an existing reader on their account it then calls the appropriate method to set them up and activate a reader session for them to take a test payment it returns an updated TerminalSessionContext containing the session's connection token and rpc session token

func SetUpTestPayment

func SetUpTestPayment(ctx context.Context, tsCtx TerminalSessionContext) (TerminalSessionContext, error)

SetUpTestPayment asks the user for their payment amount / currency, then updates the reader display, then creates a new Payment Intent

type TransactionContext

type TransactionContext struct {
	TerminalID    string `json:"terminal_id"`
	StartTime     int64  `json:"start_time"`
	OperatorID    string `json:"operator_id"`
	TransactionID string `json:"transaction_id"`
}

TransactionContext belongs to each Rabbit Service protobuf payload and communicates the state and identity of the current transaction

func SetTransactionContext

func SetTransactionContext(tsCtx TerminalSessionContext) TransactionContext

SetTransactionContext creates a new transaction context with a baked in start time and unique id

type Transport

type Transport struct {
	DNSIPs []net.IPAddr
	Err    error
}

Transport is used when we're tracing a Rabbit Service call, in order to surface DNS and connectivity related data / errors it helps provide a more specific / succinct error to the user in order to be more helpful when they run into trouble

func (*Transport) DNSDone

func (t *Transport) DNSDone(info httptrace.DNSDoneInfo)

DNSDone is a hook called from http client tracing to extract any DNS service IP resolutions from the tcp dialing of Rabbit Service it attaches this list of resolved IPs to the Transport instance so we can later check if any errors were due to DNS not resolving to a valid IP

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip is a hook called from http client tracing to inspect for specific tcp dialing issues when calling Rabbit Service. It allows for a less verbose error than what occurs further down the call stack, and attaches it to the Transport instance It returns the response and any error unmodified in order to continue the completion of the http client's request work

Jump to

Keyboard shortcuts

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