Documentation
¶
Overview ¶
Package payitgo is the Go client for the payitgo crypto payment gateway.
client, err := payitgo.NewClient(os.Getenv("PAYITGO_KEY"), payitgo.WithBaseURL("https://api.example.com"))
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
OrderID: "ORD-1001", AmountUSD: "10", Token: "USDT_TRC20",
})
// send the customer to payment.CheckoutURL; fulfil on the payment.confirmed webhook
Use the client from your server only: the API key is a secret.
Index ¶
- Constants
- Variables
- type CheckoutService
- type Client
- type Deposit
- type Error
- type Event
- type ListParams
- type Option
- type Payment
- type PaymentList
- type PaymentParams
- type PaymentsService
- func (s *PaymentsService) Create(ctx context.Context, p *PaymentParams) (*Payment, error)
- func (s *PaymentsService) Get(ctx context.Context, id string) (*Payment, error)
- func (s *PaymentsService) List(ctx context.Context, p *ListParams) (*PaymentList, error)
- func (s *PaymentsService) SelectToken(ctx context.Context, id, token string) (*Payment, error)
- func (s *PaymentsService) Simulate(ctx context.Context, id, outcome string) (*Payment, error)
- type PreviousCoin
- type Simulation
- type TokenInfo
- type TokenListParams
- type TokensService
- type Webhook
- type WebhookDelivery
- type WebhookDeliveryAttempt
- type WebhooksService
- func (s *WebhooksService) ConstructEvent(payload []byte, signatureHeader string, secret ...string) (*Event, error)
- func (s *WebhooksService) Get(ctx context.Context) (*Webhook, error)
- func (s *WebhooksService) Remove(ctx context.Context) (*Webhook, error)
- func (s *WebhooksService) Set(ctx context.Context, url string) (*Webhook, error)
- func (s *WebhooksService) Test(ctx context.Context) (*WebhookDelivery, error)
Constants ¶
const ( StatusPending = "pending" StatusPartiallyPaid = "partially_paid" StatusDetecting = "detecting" StatusConfirmed = "confirmed" StatusUnderpaid = "underpaid" StatusExpired = "expired" StatusFailed = "failed" )
Payment statuses.
const ( OutcomeConfirmed = "confirmed" OutcomeOverpaid = "overpaid" OutcomePartiallyPaid = "partially_paid" OutcomeUnderpaid = "underpaid" OutcomeExpired = "expired" OutcomeFailed = "failed" OutcomeWrongAsset = "wrong_asset" OutcomePaidLate = "paid_late" )
Simulated outcomes, for a test payment's PaymentParams.Simulate or PaymentsService.Simulate.
const ( SimulationRequested = "requested" // asked for on create, waiting for the coin SimulationRunning = "running" SimulationDone = "done" )
Simulation states.
const ( EventPaymentPartiallyPaid = "payment.partially_paid" EventPaymentDetecting = "payment.detecting" EventPaymentConfirmed = "payment.confirmed" EventPaymentUnderpaid = "payment.underpaid" EventPaymentExpired = "payment.expired" EventPaymentFailed = "payment.failed" EventPaymentWrongAsset = "payment.wrong_asset" EventPaymentLateDeposit = "payment.late_deposit" EventPayoutApproved = "payout.approved" EventPayoutRejected = "payout.rejected" EventPayoutSent = "payout.sent" EventSettlementCompleted = "settlement.completed" EventSettlementFailed = "settlement.failed" EventPing = "ping" )
Event types: every event of the key's mode is sent. EventPing is sent by WebhooksService.Test.
const ( DeliveryPending = "pending" // waiting for its next attempt DeliverySending = "sending" // being posted DeliveryDelivered = "delivered" // your server answered 2xx DeliveryFailed = "failed" // every attempt failed DeliveryResolved = "resolved" // a failed delivery someone acknowledged )
Delivery statuses.
const ( TargetAccount = "account" // the webhook's URL, as it is at each attempt TargetPayment = "payment" // the payment's own WebhookURL )
Delivery targets.
const DefaultTolerance = 5 * time.Minute
DefaultTolerance is how old a webhook's timestamp may be.
const Version = "0.5.0"
Version is this library's version, sent in the User-Agent.
Variables ¶
var ErrSignature = errors.New("payitgo: webhook signature verification failed")
ErrSignature is returned for a webhook request whose signature or timestamp does not check out, wrapped with the reason ("signature does not match", …): test for it with errors.Is.
Functions ¶
This section is empty.
Types ¶
type CheckoutService ¶
type CheckoutService struct {
// contains filtered or unexported fields
}
CheckoutService reads the payer's view of a payment.
func (*CheckoutService) Get ¶
Get returns a payment by its checkout token. Public: sent without the API key.
func (*CheckoutService) SelectToken ¶
func (s *CheckoutService) SelectToken(ctx context.Context, checkoutToken, token string) (*Payment, error)
SelectToken is the customer's choice of coin for a payment created without one. Public: sent without the API key.
type Client ¶
type Client struct {
Payments *PaymentsService
Tokens *TokensService
Checkout *CheckoutService
Webhooks *WebhooksService
// contains filtered or unexported fields
}
Client talks to the payitgo API with one secret key. IsLive says whether it is a live key or a test key.
func (*Client) IsLive ¶ added in v0.3.0
IsLive reports whether the key is a live key (its payments are real) rather than a test key. payitgo says which (GET /v1/webhook's livemode) the first time; the answer is kept for the client's life. An error (an *Error when payitgo refuses the key) is not kept: the next call asks again.
type Deposit ¶
type Deposit struct {
TxID string `json:"tx_id"`
Token string `json:"token"` // the asset that arrived
Chain string `json:"chain"`
// Amount is in Token; USDValue is its dollar value.
Amount string `json:"amount"`
USDValue string `json:"usd_value"`
Counted bool `json:"counted"` // counts toward the payment
Late bool `json:"late,omitempty"` // arrived after the payment had closed
// Status is pending (confirming), confirmed (final and credited) or failed.
Status string `json:"status"`
SeenAt time.Time `json:"seen_at"`
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
// From is the sender's address when the network reports it (for a
// Bitcoin-like coin, the first input's): where a refund would go. To is
// the address it was sent to: the payment's, or a previous coin's.
From string `json:"from,omitempty"`
To string `json:"to,omitempty"`
// Block is the block (on XRP, the ledger) that holds the transfer, and
// MadeAt that block's time.
Block int64 `json:"block,omitempty"`
MadeAt *time.Time `json:"made_at,omitempty"`
// FailedAt and FailReason ("transaction not found on chain" or
// "confirmation timeout") say when and why a deposit never became final.
FailedAt *time.Time `json:"failed_at,omitempty"`
FailReason string `json:"fail_reason,omitempty"`
// Simulated is true for a deposit a test payment's simulation played: its
// TxID names no transaction on any chain.
Simulated bool `json:"simulated,omitempty"`
}
Deposit is one transfer to a payment's address.
type Error ¶
Error is a request the API refused. Status is the HTTP status, or 0 for a network error.
type Event ¶
type Event struct {
// ID identifies the event; it is the same when the event is delivered again.
ID string `json:"id"`
Type string `json:"type"`
Livemode bool `json:"livemode"`
CreatedAt time.Time `json:"created_at"`
Data json.RawMessage `json:"data"`
}
Event is a webhook event.
func ConstructEvent ¶
ConstructEvent verifies a webhook request and returns its event. Pass the raw request body (before any JSON parsing), the X-Webhook-Signature header and the mode's signing secret (Webhook.Secret, from WebhooksService.Get or the dashboard).
body, _ := io.ReadAll(r.Body)
event, err := payitgo.ConstructEvent(body, r.Header.Get("X-Webhook-Signature"), secret)
if err != nil {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
func ConstructEventWithTolerance ¶
func ConstructEventWithTolerance(payload []byte, signatureHeader, secret string, tolerance time.Duration) (*Event, error)
ConstructEventWithTolerance is ConstructEvent with a custom timestamp tolerance; 0 disables the timestamp check. Every verification failure wraps ErrSignature with its reason.
type ListParams ¶
type ListParams struct {
Status string
Chain string
Token string
StoreID string
Limit int
Offset int
}
ListParams narrows a payment listing; zero values are left out. StoreID keeps the payments of one store (ignored for a storefront's key, which sees its own).
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithBaseURL ¶
WithBaseURL sets the gateway's address, e.g. "https://api.example.com". The default is the PAYITGO_BASE_URL environment variable.
func WithHTTPClient ¶
WithHTTPClient replaces the HTTP client (default: 30 s timeout).
func WithMaxRetries ¶
WithMaxRetries sets how often a request is retried after a network error, a 429 or a 5xx (default 2).
func WithWebhookSecret ¶
WithWebhookSecret sets the signing secret of the key's mode, which WebhooksService.ConstructEvent uses when given none.
func WithWebhookURL ¶
WithWebhookURL sets the webhook_url sent with every payment this client creates whose PaymentParams.WebhookURL is empty.
type Payment ¶
type Payment struct {
ID string `json:"id"`
MerchantID string `json:"merchant_id,omitempty"`
StoreID string `json:"store_id,omitempty"`
OrderID string `json:"order_id"`
Status string `json:"status"`
Livemode bool `json:"livemode"`
// Simulation is set on a test payment that has a simulated outcome.
Simulation *Simulation `json:"simulation,omitempty"`
// Token and Chain are empty until the customer chooses the coin, from
// TokenOptions, which stay while the coin can still change.
// PreviousCoins are the coins chosen before it.
Token string `json:"token"`
Chain string `json:"chain"`
TokenOptions []TokenInfo `json:"token_options,omitempty"`
PreviousCoins []PreviousCoin `json:"previous_coins,omitempty"`
DepositAddress string `json:"deposit_address"`
DestinationTag *uint32 `json:"destination_tag,omitempty"`
CryptoAmount string `json:"crypto_amount"`
ReceivedAmount string `json:"received_amount"`
USDAmount string `json:"usd_amount"` // your price
PriceAmount string `json:"price_amount,omitempty"` // your price in another currency, when you gave one (PaymentParams.PriceAmount)
PriceCurrency string `json:"price_currency,omitempty"` // its ISO 4217 code, upper case: "EUR"
PriceRate string `json:"price_rate,omitempty"` // dollars per unit of PriceCurrency that USDAmount was converted at
AmountDueUSD string `json:"amount_due_usd"` // what the customer pays: the price, plus the fees when you pass them on
FeesPaidByCustomer bool `json:"fees_paid_by_customer"`
NetworkFee string `json:"network_fee"` // quoted for moving the payment, in its coin
NetworkFeeUSD string `json:"network_fee_usd"` // and in dollars
Settlement string `json:"settlement"` // "custodial" (your balance) or "direct" (your payout address)
ReceivedUSD string `json:"received_usd"` // dollar value of the deposits that count
RateLocked string `json:"rate_locked"`
TxID string `json:"tx_id,omitempty"`
Overpaid bool `json:"overpaid,omitempty"`
PaidLate bool `json:"paid_late,omitempty"`
Deposits []Deposit `json:"deposits"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
NetworkFeeNote string `json:"network_fee_note"`
QRPayload string `json:"qr_payload"`
CheckoutToken string `json:"checkout_token,omitempty"`
CheckoutURL string `json:"checkout_url,omitempty"`
Description string `json:"description,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
CustomerEmail string `json:"customer_email,omitempty"`
SuccessURL string `json:"success_url,omitempty"`
CancelURL string `json:"cancel_url,omitempty"`
WebhookURL string `json:"webhook_url,omitempty"` // where its events go instead of the webhook's URL
}
Payment is a payment as the API returns it. Amounts are decimal strings.
type PaymentList ¶
type PaymentList struct {
Payments []Payment `json:"payments"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
PaymentList is one page of payments.
type PaymentParams ¶
type PaymentParams struct {
OrderID string `json:"order_id"`
AmountUSD string `json:"amount_usd,omitempty"` // decimal, e.g. "19.99"
PriceAmount string `json:"price_amount,omitempty"` // decimal, e.g. "45.50": instead of AmountUSD
PriceCurrency string `json:"price_currency,omitempty"` // with PriceAmount, e.g. "EUR"
Token string `json:"token,omitempty"`
Tokens []string `json:"tokens,omitempty"`
Description string `json:"description,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
CustomerEmail string `json:"customer_email,omitempty"`
SuccessURL string `json:"success_url,omitempty"`
CancelURL string `json:"cancel_url,omitempty"`
WebhookURL string `json:"webhook_url,omitempty"`
Simulate string `json:"simulate,omitempty"`
}
PaymentParams creates a payment. OrderID is required, and the price: either AmountUSD, or PriceAmount in PriceCurrency (an ISO 4217 code such as "EUR", "GBP" or "NGN"), which payitgo converts into dollars at the rate of the moment. Leave Token empty to let the customer choose the coin on the checkout page, from Tokens (default: every token the amount reaches the minimum of). WebhookURL (https) gets the payment's events instead of the webhook's URL, signed with the same secret; empty means the client's WithWebhookURL. Simulate (an Outcome… constant, test keys only) plays that outcome on the test payment once it has its coin.
type PaymentsService ¶
type PaymentsService struct {
// contains filtered or unexported fields
}
PaymentsService creates and reads payments.
func (*PaymentsService) Create ¶
func (s *PaymentsService) Create(ctx context.Context, p *PaymentParams) (*Payment, error)
Create creates a payment. Safe to retry: an order with an open payment returns that payment.
func (*PaymentsService) Get ¶
Get returns a payment by its id or by your order id (the order's open payment).
func (*PaymentsService) List ¶
func (s *PaymentsService) List(ctx context.Context, p *ListParams) (*PaymentList, error)
List returns payments of the key's mode, newest first.
func (*PaymentsService) SelectToken ¶
SelectToken sets the coin of a payment created without one, when the customer chose it on your own page: one of its TokenOptions. id is the payment's id or your order id. The payment comes back whole, now with its address, amount, locked rate and a deadline 15 minutes away. Another coin changes it while the payment still has TokenOptions; once it can no longer change, an *Error with Status 409.
func (*PaymentsService) Simulate ¶ added in v0.2.0
Simulate plays outcome (an Outcome… constant) on a test payment: payitgo sends its deposits, status changes and webhooks a few seconds apart, with no coins. id is the payment's id or your order id. The payment comes back whole, with its Simulation. A live payment is an *Error with Status 400; a simulation that is still running, 409.
type PreviousCoin ¶ added in v0.4.0
type PreviousCoin struct {
Token string `json:"token"`
Chain string `json:"chain"`
DepositAddress string `json:"deposit_address"`
DestinationTag *uint32 `json:"destination_tag,omitempty"`
CryptoAmount string `json:"crypto_amount"`
RateLocked string `json:"rate_locked"`
}
PreviousCoin is a coin chosen for a payment before its current one, when the customer changed it. Its address is still watched.
type Simulation ¶ added in v0.2.0
type Simulation struct {
Outcome string `json:"outcome"` // an Outcome… constant
State string `json:"state"` // a Simulation… constant
}
Simulation is a test payment's simulated outcome and how far it is.
type TokenInfo ¶
type TokenInfo struct {
Token string `json:"token"`
Chain string `json:"chain"`
MinUSD string `json:"min_usd"`
NetworkFeeUSD string `json:"network_fee_usd"`
// AmountDueUSD, in a payment's TokenOptions (or a token listing with an
// amount) when fees are passed on, is what the customer pays in this token.
AmountDueUSD string `json:"amount_due_usd,omitempty"`
FeeNote string `json:"fee_note"`
}
TokenInfo is a token a customer can pay with. MinUSD and NetworkFeeUSD move with the network's fees.
type TokenListParams ¶
type TokenListParams struct {
// AmountUSD, when set, lists only the tokens a payment of that amount
// offers (its TokenOptions), each with AmountDueUSD when fees are passed on.
AmountUSD string
}
TokenListParams narrows a token listing; nil lists every token.
type TokensService ¶
type TokensService struct {
// contains filtered or unexported fields
}
TokensService lists what customers can pay with.
func (*TokensService) List ¶
func (s *TokensService) List(ctx context.Context, p *TokenListParams) ([]TokenInfo, error)
List returns the tokens of the key's mode.
type Webhook ¶
type Webhook struct {
Livemode bool `json:"livemode"`
// URL is empty when none is set: events then go only to the payments
// created with their own WebhookURL.
URL string `json:"url"`
// Secret signs every notification of the mode: pass it to
// WithWebhookSecret.
Secret string `json:"secret"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Webhook is the webhook (IPN) of the key's mode: the URL every event of the mode is POSTed to, and the secret that signs them. A test key has the test webhook, a live key the live one.
type WebhookDelivery ¶
type WebhookDelivery struct {
ID string `json:"id"`
MerchantID string `json:"merchant_id"`
Target string `json:"target"` // TargetAccount or TargetPayment
URL string `json:"url"`
EventID string `json:"event_id"`
EventType string `json:"event_type"`
// Payload is the exact JSON body that is signed and posted.
Payload string `json:"payload"`
Status string `json:"status"` // one of the Delivery* constants
Attempts int `json:"attempts"`
MaxAttempts int `json:"max_attempts"`
NextAttemptAt time.Time `json:"next_attempt_at"`
LastStatusCode int `json:"last_status_code,omitempty"`
LastError string `json:"last_error,omitempty"`
LastAttemptAt *time.Time `json:"last_attempt_at,omitempty"`
DeliveredAt *time.Time `json:"delivered_at,omitempty"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
ResolutionNote string `json:"resolution_note,omitempty"`
CreatedAt time.Time `json:"created_at"`
History []WebhookDeliveryAttempt `json:"history,omitempty"`
}
WebhookDelivery is one event on its way to one URL.
type WebhookDeliveryAttempt ¶
type WebhookDeliveryAttempt struct {
At time.Time `json:"at"`
URL string `json:"url,omitempty"` // where it was actually posted
Signed string `json:"signed,omitempty"` // the signature's timestamp
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
Response string `json:"response,omitempty"` // the start of the answer your server gave
Millis int64 `json:"millis,omitempty"`
Note string `json:"note,omitempty"` // redelivered or resolved, and by whom
}
WebhookDeliveryAttempt is one try at a delivery, or a person's action on it.
type WebhooksService ¶
type WebhooksService struct {
// contains filtered or unexported fields
}
WebhooksService manages the webhook (IPN) of the key's mode: a test key the test webhook, a live key the live one. A storefront's key may read and test it, not change it.
func (*WebhooksService) ConstructEvent ¶
func (s *WebhooksService) ConstructEvent(payload []byte, signatureHeader string, secret ...string) (*Event, error)
ConstructEvent verifies a webhook request with the client's WithWebhookSecret, or with secret when one is passed, and returns its event (see the package's ConstructEvent). Without any secret it returns an error wrapping ErrSignature.
func (*WebhooksService) Get ¶
func (s *WebhooksService) Get(ctx context.Context) (*Webhook, error)
Get returns the webhook: its URL (empty when not set) and its signing secret.
func (*WebhooksService) Remove ¶
func (s *WebhooksService) Remove(ctx context.Context) (*Webhook, error)
Remove stops posting to the URL (payments with their own WebhookURL still get theirs); the secret stays.
func (*WebhooksService) Set ¶
Set sets the URL every event of the mode is POSTed to: https, on a public host, accepting POST requests. Safe to retry.
func (*WebhooksService) Test ¶
func (s *WebhooksService) Test(ctx context.Context) (*WebhookDelivery, error)
Test queues a signed "ping" event to the URL and returns its delivery.