payitgo

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

payitgo for Go

Accept crypto payments with payitgo from Go. Standard library only.

Full reference, with every method, option, type and error: api.payitgo.co/docs/sdk-go.

go get github.com/payitgo/go-sdk

Accept a payment in three steps

import payitgo "github.com/payitgo/go-sdk"

client, err := payitgo.NewClient(os.Getenv("PAYITGO_KEY"),
	payitgo.WithBaseURL(os.Getenv("PAYITGO_BASE_URL")),
	payitgo.WithWebhookSecret(os.Getenv("PAYITGO_WEBHOOK_SECRET")), // the signing secret: see Webhooks (IPN) below
)

// 1. Create a payment and send the customer to the checkout page.
func checkout(w http.ResponseWriter, r *http.Request) {
	payment, err := client.Payments.Create(r.Context(), &payitgo.PaymentParams{
		OrderID:    "ORD-1001",   // your order id: safe to retry
		AmountUSD:  "19.99",      // decimal string
		// Token: "USDT_TRC20",   // optional: without it the customer picks the coin
		SuccessURL: "https://shop.example/thanks",
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	http.Redirect(w, r, payment.CheckoutURL, http.StatusSeeOther)
}

// 2. Receive the notification (the complete handler is under Webhooks (IPN) below).
func ipn(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	event, err := client.Webhooks.ConstructEvent(body, r.Header.Get("X-Webhook-Signature"))
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	// 3. Fulfil the order once the payment is final.
	if event.Type == payitgo.EventPaymentConfirmed {
		p, _ := event.Payment()
		markOrderPaid(p.OrderID) // make this idempotent: events can arrive twice
	}
	w.WriteHeader(http.StatusOK)
}

Start with a test key, where you simulate what the customer pays; switch to a live key when the account owner has turned live mode on. A key does not say its mode (the dashboard shows a Test or Live badge next to it): client.IsLive(ctx) asks payitgo, once.

Prices in other currencies

To price a payment in your own currency, give PriceAmount and PriceCurrency (an ISO 4217 code such as EUR, GBP or NGN) instead of AmountUSD. payitgo converts the price into dollars at the rate of the moment, and the payment keeps both:

payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
	OrderID: "ORD-1002", PriceAmount: "45.50", PriceCurrency: "EUR", // decimal string, any case
})
// payment.PriceAmount "45.5", payment.PriceCurrency "EUR",
// payment.PriceRate "1.082" (dollars per euro), payment.USDAmount "49.23"

Everything else (USDAmount, CryptoAmount, fees, minimums) stays in dollars; a payment priced in dollars has empty Price… fields. Give AmountUSD or the pair, not both (400). When no exchange rate can be had, Create fails with a 503 (exchange rate unavailable for price_currency: try again shortly) once the client's retries are spent: try again shortly.

Your own payment page

CheckoutURL is only for payitgo's hosted page. To show the payment on your own page, render the payment your server gets back (DepositAddress, CryptoAmount, DestinationTag for XRP, a QR code of QRPayload, ExpiresAt); no Checkout calls are needed.

  • You know the coin: create the payment with Token and render the payment it returns.
  • The customer chooses it: create the payment without Token, show payment.TokenOptions on your page, then call client.Payments.SelectToken(ctx, payment.ID, chosen) from your server and render the payment it returns: it now has its coin, address, amount, locked rate and a deadline 15 minutes away.
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{OrderID: "ORD-1", AmountUSD: "10"})
// your page shows payment.TokenOptions; the customer picks one
chosen, err := client.Payments.SelectToken(ctx, payment.ID, "USDT_TRC20") // or your order id
// render chosen.DepositAddress, chosen.CryptoAmount, chosen.QRPayload, chosen.ExpiresAt

The coin is chosen once: choosing again is a 409 (Payments.Get then returns the payment with its coin). A coin outside TokenOptions, or a payment that can no longer be paid, is a 400.

Test mode

A test payment gets an address like a live one, but no coins are involved: you choose an outcome and payitgo plays its deposits, status changes and webhooks a few seconds apart (Test mode).

// Choose the outcome when you create the payment (with Token it starts at once,
// without it once the coin is chosen)…
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
	OrderID: "TEST-1", AmountUSD: "10", Token: "USDT_TRC20", Simulate: payitgo.OutcomeConfirmed,
})

// …or later, on a payment you already have (its id or your order id).
payment, err = client.Payments.Simulate(ctx, "TEST-2", payitgo.OutcomePartiallyPaid)
// payment.Simulation: {Outcome: "partially_paid", State: "running"}

Outcomes (payitgo.Outcome…): confirmed, overpaid, partially_paid, underpaid, expired, failed, wrong_asset, paid_late. Simulated deposits have Simulated: true; their TxID names no transaction on any chain. A live key gets 400; a payment whose simulation is still running, 409.

Webhooks (IPN)

payitgo POSTs a signed notification for every change of a payment (payment.confirmed, payment.expired, …), of a direct settlement and of a payout. Each mode has one webhook: a test key manages the test one, a live key the live one.

Where the notifications go. Set the URL once per mode (https:// on a public host, accepting POST requests), or give a payment its own when you create it:

// Once per mode (safe to repeat):
_, err := client.Webhooks.Set(ctx, "https://shop.example/payitgo/ipn")

// Or per payment: its events go there instead of the webhook's URL.
_, err = client.Payments.Create(ctx, &payitgo.PaymentParams{
	OrderID: "ORD-1", AmountUSD: "10", WebhookURL: "https://shop.example/orders/ipn",
})

// Or as the client's default for every payment it creates (a payment's own WebhookURL wins):
shop, err := payitgo.NewClient(os.Getenv("PAYITGO_KEY"), payitgo.WithWebhookURL("https://shop.example/orders/ipn"))

A storefront's key cannot set the account's URL (403): set WebhookURL on its payments instead. Payout events always go to the webhook's URL.

The signing secret. Every notification of a mode is signed with that mode's secret, whichever URL it goes to. Copy it from the dashboard or read it with client.Webhooks.Get(ctx) (.Secret), and give it to the client once:

client, err := payitgo.NewClient(os.Getenv("PAYITGO_KEY"), payitgo.WithWebhookSecret(os.Getenv("PAYITGO_WEBHOOK_SECRET")))

Receiving them (net/http). Verify the raw body, handle each event once, and answer 2xx within 10 seconds; otherwise payitgo retries after 1 min, 5 min, 30 min, 2 h, 6 h and 24 h.

http.HandleFunc("/payitgo/ipn", func(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		http.Error(w, "unreadable body", http.StatusBadRequest)
		return
	}
	// Checks the signature with the client's WithWebhookSecret and refuses anything older than 5 minutes.
	event, err := client.Webhooks.ConstructEvent(body, r.Header.Get("X-Webhook-Signature"))
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	// The same event can arrive more than once: handle each event id once,
	// e.g. by inserting it into a table with a unique key.
	first, err := recordEventOnce(r.Context(), event.ID)
	if err != nil {
		http.Error(w, "try again", http.StatusInternalServerError) // payitgo retries
		return
	}
	if !first {
		w.WriteHeader(http.StatusOK) // seen before
		return
	}
	switch event.Type {
	case payitgo.EventPaymentConfirmed:
		p, _ := event.Payment()
		jobs.Enqueue("fulfil", p.OrderID) // slow work off the request
	case payitgo.EventPaymentExpired:
		p, _ := event.Payment()
		jobs.Enqueue("release-stock", p.OrderID)
	}
	w.WriteHeader(http.StatusOK)
})

Testing it. client.Webhooks.Test(ctx) queues a signed ping event to the webhook's URL and returns its delivery (400 when no URL is set).

API

client, err := payitgo.NewClient(apiKey,
	payitgo.WithBaseURL("https://api.example.com"), // or PAYITGO_BASE_URL
	payitgo.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
	payitgo.WithMaxRetries(2),                      // network errors, 429 and 5xx
	payitgo.WithWebhookSecret(secret),              // for client.Webhooks.ConstructEvent
	payitgo.WithWebhookURL("https://…"),            // default PaymentParams.WebhookURL
)

client.IsLive(ctx)                                // (false, nil) for a test key: asks payitgo once
client.Payments.Create(ctx, &payitgo.PaymentParams{...}) // OrderID, AmountUSD (or PriceAmount + PriceCurrency), Token, …, WebhookURL, Simulate
client.Payments.SelectToken(ctx, paymentID, token) // or your order id: the payment with its coin
client.Payments.Simulate(ctx, paymentID, payitgo.OutcomeConfirmed) // test keys: plays the outcome
client.Payments.Get(ctx, paymentID)               // or your order id
client.Payments.List(ctx, &payitgo.ListParams{Status: payitgo.StatusConfirmed, StoreID: storeID, Limit: 50})
client.Tokens.List(ctx, nil)                                            // every token
client.Tokens.List(ctx, &payitgo.TokenListParams{AmountUSD: "49.90"})    // the coins a $49.90 payment offers, with AmountDueUSD
client.Checkout.Get(ctx, checkoutToken)           // public payer view
client.Webhooks.Get(ctx)                          // *Webhook{Livemode, URL, Secret, CreatedAt, UpdatedAt}
client.Webhooks.Set(ctx, url)                     // *Webhook
client.Webhooks.Remove(ctx)                       // *Webhook, URL "" (the secret stays)
client.Webhooks.Test(ctx)                         // *WebhookDelivery of a "ping" event
client.Webhooks.ConstructEvent(body, header)      // with WithWebhookSecret
client.Webhooks.ConstructEvent(body, header, secret)
payitgo.ConstructEvent(body, header, secret)        // 5-minute tolerance, no client needed
payitgo.ConstructEventWithTolerance(body, header, secret, tolerance)

Amounts are decimal strings ("19.99"), never floats.

Errors

var perr *payitgo.Error
if errors.As(err, &perr) {
	log.Println(perr.Status, perr.Message) // 400 "minimum payment in BTC is $10 right now (network fees)"
}
if errors.Is(err, payitgo.ErrSignature) { /* err says why: signature does not match, timestamp outside the tolerance, … */ }

Development

go test ./...

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

View Source
const (
	StatusPending       = "pending"
	StatusPartiallyPaid = "partially_paid"
	StatusDetecting     = "detecting"
	StatusConfirmed     = "confirmed"
	StatusUnderpaid     = "underpaid"
	StatusExpired       = "expired"
	StatusFailed        = "failed"
)

Payment statuses.

View Source
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.

View Source
const (
	SimulationRequested = "requested" // asked for on create, waiting for the coin
	SimulationRunning   = "running"
	SimulationDone      = "done"
)

Simulation states.

View Source
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.

View Source
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.

View Source
const (
	TargetAccount = "account" // the webhook's URL, as it is at each attempt
	TargetPayment = "payment" // the payment's own WebhookURL
)

Delivery targets.

View Source
const DefaultTolerance = 5 * time.Minute

DefaultTolerance is how old a webhook's timestamp may be.

View Source
const Version = "0.5.0"

Version is this library's version, sent in the User-Agent.

Variables

View Source
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

func (s *CheckoutService) Get(ctx context.Context, checkoutToken string) (*Payment, error)

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 NewClient

func NewClient(apiKey string, opts ...Option) (*Client, error)

NewClient returns a client for apiKey, a test or a live secret key.

func (*Client) IsLive added in v0.3.0

func (c *Client) IsLive(ctx context.Context) (bool, error)

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

type Error struct {
	Status  int
	Message string
}

Error is a request the API refused. Status is the HTTP status, or 0 for a network error.

func (*Error) Error

func (e *Error) Error() string

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

func ConstructEvent(payload []byte, signatureHeader, secret string) (*Event, error)

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.

func (*Event) Payment

func (e *Event) Payment() (*Payment, error)

Payment decodes the payment a payment.* event carries.

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

func WithBaseURL(u string) Option

WithBaseURL sets the gateway's address, e.g. "https://api.example.com". The default is the PAYITGO_BASE_URL environment variable.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient replaces the HTTP client (default: 30 s timeout).

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how often a request is retried after a network error, a 429 or a 5xx (default 2).

func WithWebhookSecret

func WithWebhookSecret(secret string) Option

WithWebhookSecret sets the signing secret of the key's mode, which WebhooksService.ConstructEvent uses when given none.

func WithWebhookURL

func WithWebhookURL(u string) Option

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

func (s *PaymentsService) Get(ctx context.Context, id string) (*Payment, error)

Get returns a payment by its id or by your order id (the order's open payment).

func (*PaymentsService) List

List returns payments of the key's mode, newest first.

func (*PaymentsService) SelectToken

func (s *PaymentsService) SelectToken(ctx context.Context, id, token string) (*Payment, error)

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

func (s *PaymentsService) Simulate(ctx context.Context, id, outcome string) (*Payment, error)

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

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

func (s *WebhooksService) Set(ctx context.Context, url string) (*Webhook, error)

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

Test queues a signed "ping" event to the URL and returns its delivery.

Jump to

Keyboard shortcuts

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