payitgo

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 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, and pay your own clients, 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"

var client *payitgo.Client

func main() {
	var err error
	client, err = payitgo.NewClient(os.Getenv("PAYITGO_KEY"),
		payitgo.WithWebhookSecret(os.Getenv("PAYITGO_WEBHOOK_SECRET")), // the signing secret: see Webhooks (IPN) below
	)
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/checkout", checkout)
	http.HandleFunc("/payitgo/ipn", ipn)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// 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
		Amount:     "19.99",      // decimal string, in US dollars unless Currency says otherwise
		// Token: "USDT_TRC20",   // optional: without it the customer picks the coin
		SuccessURL: "https://yourdomain.com/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 your own currency

A payment is priced in US dollars unless you give Currency, an ISO 4217 code such as EUR, GBP or NGN (any case). Every figure on the payment is then in that currency: Amount (your price), AmountDue (what the customer pays: the price, plus the fees when you pass them on), AmountReceived (what has arrived so far), each deposit's Value, each coin's Minimum and NetworkFee in TokenOptions, and RateLocked (the coin's price). Only CryptoAmount and CryptoReceived are in the coin.

payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
	OrderID: "ORD-1002", Amount: "45.50", Currency: "EUR", // decimal string; any case
})
// payment.Currency "EUR", payment.Amount "45.5", payment.AmountDue "45.5"

payitgo converts at the rate of the moment. When no exchange rate can be had, Create fails with a 503 (exchange rate unavailable for currency: try again shortly) once the client's retries are spent: try again shortly. A payment link priced in a coin has that coin as its Currency ("ETH"), and its figures in the coin.

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", Amount: "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 customer can change the coin (another of TokenOptions) while nothing has arrived, up to three times; the coin it has already changes nothing. Once the coin can no longer change, another one is a 409. 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", Amount: "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, paid_twice. 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, of a payout and of your mass payouts. 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://api.yourdomain.com/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", Amount: "10", WebhookURL: "https://api.yourdomain.com/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://api.yourdomain.com/orders/ipn"))

A storefront's key cannot set the account's URL (403): set WebhookURL on its payments instead. Payout (payout.*) and payout wallet events always go to the webhook's URL. A mass payout payment's events go to its own WebhookURL, else to its batch's, else to the webhook's URL; a payout batch made with its own WebhookURL sends its batch events there.

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).

Payouts

Pay your own clients (withdrawals from your platform, payroll, prizes) from your payout wallet: one address per network, yours alone, that you top up. payitgo checks and prices every payment before anything leaves the wallet. Each payment is in one of the payout coins (USDT_TRC20, USDT_BEP20, BTC, … the list); amounts are decimal strings in the coin. Reading works with any key; making, sending, quoting, removing and canceling need a key with payouts turned on in the dashboard (403 otherwise). The whole guide: Mass payouts.

Payout requests, one by one. Send each client's payout request as it comes in. payitgo checks and prices it at once and keeps it in your open list with its costs; send the list when you choose (or let it go by itself: auto-send, in your payout settings).

// A client asks for a withdrawal. Your reference makes the call safe to retry:
// the same reference again returns this payment (200 instead of 201).
item, err := client.Payouts.Request(ctx, &payitgo.PayoutParams{
	Reference: "WD-7731",
	Asset:     "USDT_TRC20",
	Address:   "TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi",
	Amount:    "120",       // decimal string, in the coin
	Name:      "Ana Silva", // optional: Name, Email, Note, and WebhookURL for this payment's events
})
if err != nil {
	return err
}
if item.Status == payitgo.PayoutItemInvalid {
	log.Println(item.Errors[0].Message) // kept, never sent: "this address is for Tron, not BNB Smart Chain"
}
// item.Fee: its whole fee; item.Debit: what it takes from the wallet

// The open list: its requests, and what sending them needs of each coin.
inbox, err := client.Payouts.Inbox(ctx, nil)
for _, c := range inbox.Coverage {
	if c.TopUp != "0" {
		fmt.Printf("send %s %s to %s first\n", c.TopUp, c.Asset, c.Address)
	}
}

// Send every valid request (or some: client.Payouts.Send(ctx, id1, id2)).
batch, err := client.Payouts.Send(ctx)
// batch.Status: pending_approval, awaiting_funds (batch.Waiting says what to send where) or processing;
// validating for more than 100 requests (submitted once priced)

// Take a request out of the list (or cancel it once sent, until it is on its way).
// Its record stays: Status "canceled", CancelReason "removed", ReleasedReference, no BatchID.
// Canceling it again returns it as it is.
_, err = client.Payouts.Cancel(ctx, item.ID)

// Or take many out of the list at once: one result per id, Item or Error (a *payitgo.Error).
results, err := client.Payouts.Remove(ctx, id1, id2)

// Read it later, by its id or by your reference (or the latest payment that gave the
// reference back, once canceled, failed or expired):
item, err = client.Payouts.RetrieveByReference(ctx, "WD-7731") // Status "sent", TxID

// Resync every payment, whatever its batch, oldest change first: keep NextCursor.
page, err := client.Payouts.List(ctx, &payitgo.PayoutPageParams{UpdatedSince: since, Limit: 200})
page, err = client.Payouts.List(ctx, &payitgo.PayoutPageParams{Cursor: page.NextCursor}) // while page.HasMore, and later

To show a client the fee before they ask, quote it (up to 100 payments, nothing kept):

q, err := client.Payouts.Quote(ctx, &payitgo.PayoutQuoteParams{
	FeePaidBy: payitgo.FeePaidByRecipient, // the fees come out of the amount
	Items:     []payitgo.PayoutParams{{Asset: "USDT_BEP20", Address: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", Amount: "120"}},
})
// q.Items[0].Fee "0.61183421", q.Items[0].SendAmount "119.38816579", q.Quote.TotalUSD "120"

Batches. A whole list at once: up to 1000 payments per call, more with AddItems, up to 10,000.

batch, err := client.PayoutBatches.Create(ctx, &payitgo.PayoutBatchParams{
	Reference: "payroll-2026-10", // a reference used already returns that batch: safe to retry
	Name:      "October payroll",
	Items: []payitgo.PayoutParams{
		{Reference: "payroll-2026-10-ana", Asset: "USDT_TRC20", Address: "TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi", Amount: "1500"},
		{Reference: "payroll-2026-10-ben", Asset: "USDT_BEP20", Address: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", Amount: "250"},
	},
})
// batch.Status "quoted": Totals per coin, TotalUSD. The rows that failed a check:
invalid, err := client.PayoutBatches.Items(ctx, batch.ID, &payitgo.PayoutListParams{Status: payitgo.PayoutItemInvalid})

batch, err = client.PayoutBatches.Submit(ctx, batch.ID)
if batch.Waiting != nil && batch.Waiting.Reason == payitgo.PayoutWaitFunds {
	for _, s := range batch.Waiting.Shortfall {
		fmt.Printf("top up %s %s at %s\n", s.Amount, s.Asset, s.Address) // it starts by itself once the money arrives
	}
}

A batch's prices hold for an hour: past that, Submit is a 409 (its prices expired: get a new quote first); call client.PayoutBatches.Quote(ctx, id), then submit. Only a batch not submitted yet changes (AddItems, Quote); Cancel stops one before it is funded, or the payments not sent yet of one already processing.

The wallet. client.PayoutWallets.List(ctx) returns one wallet per network: its Address to top up, and per coin its Balance, Reserved, Spendable and Needed (the top-up that batches waiting for funds need).

In test mode a test key has a test payout wallet with balances on paper. Top it up with a call; batches waiting for it are funded, and their payments are "sent" within seconds with made-up TxIDs and the same webhooks as live:

wallets, err := client.PayoutWallets.SimulateTopUp(ctx, "USDT_TRC20", "1000") // test keys only (400 otherwise)

Claim links. Pay someone whose address you don't have: leave Address out and set Claim: true (giving ClaimAssets does too). With an Email, payitgo emails them the link; without one, you share it yourself. Claim links are opt-in only: an Email without an Address and without Claim is refused like any missing address. The recipient opens it, chooses the coin (Asset, or one of ClaimAssets, paid at the same dollar value) and their address, and the payment goes. Once its batch is funded it waits, claimable, until Claim.ExpiresAt; never claimed, it is expired and its money is free again. Payout requests, batch items and quotes all take them; a claim link is never converted.

item, err := client.Payouts.Request(ctx, &payitgo.PayoutParams{
	Reference:   "prize-cup-final-2",
	Asset:       "USDT_TRC20",
	Amount:      "100",
	Claim:       true,                          // no Address: its recipient chooses
	Email:       "player2@example.com",         // the link is emailed there
	ClaimAssets: []string{"USDT_BEP20", "BTC"}, // other coins they may choose
})
// item.Claim.URL: the link (share it yourself when there is no email); item.Claim.ExpiresAt once funded
// On payout_item.claimed: item.Asset and item.Address are what they chose, and when that is
// another coin, item.Claim.FundedAsset and FundedAmount are what it was funded with.

Converted payments. Pay a coin your wallet does not hold: give a batch (or a quote) Convert: payitgo.PayoutConvert and ConvertFrom, a coin the wallet holds, and every payment in another coin is paid from ConvertFrom, converted on its way. Without them your payout settings decide, as they do for payout requests.

batch, err := client.PayoutBatches.Create(ctx, &payitgo.PayoutBatchParams{
	Reference: "payroll-2026-11", Convert: payitgo.PayoutConvert, ConvertFrom: "USDT_TRC20",
	Items: []payitgo.PayoutParams{{Asset: "BTC", Address: "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", Amount: "0.01"}},
})
// Each converted payment: item.Convert.To "BTC", ToAmount "0.01" (what you asked), Estimate
// (about what arrives), AmountOut once sent. item.Asset, Amount, Fee (converting included)
// and Debit are in USDT_TRC20; item.Address is the recipient's Bitcoin address.

A batch with converted payments holds its prices for 15 minutes instead of an hour. A coin that cannot be paid from ConvertFrom is an invalid payment (conversion_unavailable).

Webhooks. Each step raises an event, signed like the others (event.PayoutBatch(), event.PayoutItem(), event.PayoutWithdrawal(), event.PayoutSchedule() and event.PayoutScheduleFunding() decode them):

switch event.Type {
case payitgo.EventPayoutItemSent:
	item, _ := event.PayoutItem()
	markWithdrawalPaid(item.Reference, item.TxID)
case payitgo.EventPayoutItemFailed, payitgo.EventPayoutItemCanceled:
	item, _ := event.PayoutItem() // item.FailReason or item.CancelReason; its money stays in the wallet
	reopenWithdrawal(item.ReleasedReference) // never sent: its reference was given back
case payitgo.EventPayoutBatchAwaitingFunds:
	batch, _ := event.PayoutBatch() // batch.Waiting.Shortfall: what to send where
	alertFinance(batch)
}

Batch events (EventPayoutBatch…): payout_batch.quoted, .pending_approval, .approved, .rejected, .awaiting_funds, .processing, .completed, .canceled (also when payitgo cancels a batch itself: CanceledBy payitgo.PayoutCanceledBySystem). Payment events (EventPayoutItem…): payout_item.processing (a payout request left your list for a batch) and .returned (it came back, not final), .sent, .failed, .canceled (every canceled payment, whatever canceled it: CancelReason, CanceledBy, CanceledAt, CancelNote for a rejection), and for claim links .claimed and .claim_expired. payout_wallet.withdrawn (EventPayoutWalletWithdrawn) when a withdrawal you made in the dashboard reaches your address, payout_wallet.withdrawal_failed (EventPayoutWalletWithdrawalFailed, with FailReason) when it could not be sent: its money stays in the wallet. Schedules, set up in the dashboard, send payout_schedule.run (EventPayoutScheduleRun: the schedule, whose LastBatchID is the batch it made) and payout_schedule.funding_needed (EventPayoutScheduleFundingNeeded: the schedule and the Shortfall to send before its next run).

Staying in sync. Every payment ends sent, failed, canceled or expired, with one event each, delivered at least once: deduplicate on event.ID, which stays the same however often it is sent. Order is not guaranteed: act on the payment's Status and its latest UpdatedAt. Replay missed events with client.Events.List (After: the last event ID you handled), and resync payments with client.Payouts.List (keep NextCursor):

page, err := client.Events.List(ctx, &payitgo.EventListParams{Types: []string{"payout_item.*"}, After: lastID})
for _, event := range page.Events {
	handleEvent(event) // the same code as your webhook: event.PayoutItem() decodes it; skip IDs seen
}
// while page.HasMore, again with After: the last event's ID

API

client, err := payitgo.NewClient(apiKey,
	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://api.yourdomain.com/payitgo/ipn"), // default PaymentParams.WebhookURL
)

client.IsLive(ctx)                                // (false, nil) for a test key: asks payitgo once
client.Payments.Create(ctx, &payitgo.PaymentParams{...}) // OrderID, Amount, Currency, 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, its figures in US dollars
client.Tokens.List(ctx, &payitgo.TokenListParams{Amount: "49.90", Currency: "EUR"}) // the coins a 49.90 EUR payment offers, with AmountDue
client.Checkout.Get(ctx, checkoutToken)           // public payer view
client.Payouts.Request(ctx, &payitgo.PayoutParams{...})        // Reference, Asset, Address, Amount, Name, …, Claim, ClaimAssets: *PayoutItem
client.Payouts.Retrieve(ctx, itemID)                            // *PayoutItem
client.Payouts.RetrieveByReference(ctx, reference)              // *PayoutItem: the one carrying it, or the latest that gave it back
client.Payouts.List(ctx, &payitgo.PayoutPageParams{Status: []string{"sent", "failed"}, UpdatedSince: since}) // *PayoutPage: Items, HasMore, NextCursor
client.Payouts.Inbox(ctx, &payitgo.PayoutListParams{Status: payitgo.PayoutItemReady}) // *PayoutInbox: Inbox, Coverage, Items, Total
client.Payouts.Send(ctx, ids...)                                // none: every valid request; *PayoutBatch
client.Payouts.Cancel(ctx, itemID)                              // *PayoutItem, canceled (again: as it is)
client.Payouts.Remove(ctx, ids...)                              // 1 to 1000 out of the list: []PayoutRemoveResult (Item or Error)
client.Payouts.Quote(ctx, &payitgo.PayoutQuoteParams{...})      // *PayoutQuote: Quote, Items (nothing kept)
client.PayoutBatches.Create(ctx, &payitgo.PayoutBatchParams{...}) // Reference, Name, FeePaidBy, Convert, ConvertFrom, WebhookURL, Items: *PayoutBatch
client.PayoutBatches.List(ctx, &payitgo.PayoutListParams{Status: payitgo.PayoutBatchCompleted, Limit: 50}) // *PayoutBatchList
client.PayoutBatches.Retrieve(ctx, batchID)                     // *PayoutBatch
client.PayoutBatches.Items(ctx, batchID, &payitgo.PayoutListParams{Status: "sent,failed"}) // *PayoutItemList
client.PayoutBatches.AddItems(ctx, batchID, items)              // *PayoutBatch
client.PayoutBatches.Quote(ctx, batchID)                        // priced again: *PayoutBatch
client.PayoutBatches.Submit(ctx, batchID)                       // *PayoutBatch
client.PayoutBatches.Cancel(ctx, batchID)                       // *PayoutBatch
client.PayoutWallets.List(ctx)                                  // []PayoutWallet
client.PayoutWallets.SimulateTopUp(ctx, "USDT_TRC20", "1000")   // test keys: []PayoutWallet
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)
client.Events.List(ctx, &payitgo.EventListParams{Types: []string{"payout_item.*"}, After: lastID}) // *EventPage: Events, HasMore
event.Payment(); event.PayoutBatch(); event.PayoutItem(); event.PayoutWithdrawal() // decode event.Data
event.PayoutSchedule(); event.PayoutScheduleFunding()                             // payout_schedule.* events

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.00 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"))
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
	OrderID: "ORD-1001", Amount: "10", Token: "USDT_TRC20",
})
// send the customer to payment.CheckoutURL; fulfil on the payment.confirmed webhook

Mass payouts pay your own clients from your payout wallet:

item, err := client.Payouts.Request(ctx, &payitgo.PayoutParams{
	Reference: "WD-7731", Asset: "USDT_TRC20", Address: "TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi", Amount: "120",
})
batch, err := client.Payouts.Send(ctx) // every valid request in the open list

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"
	OutcomePaidTwice     = "paid_twice"
)

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 (
	PayoutBatchValidating      = "validating"       // its payments are being checked and priced
	PayoutBatchQuoted          = "quoted"           // checked and priced: submit it while its prices hold (QuoteExpiresAt)
	PayoutBatchPendingApproval = "pending_approval" // submitted; waiting for its approvals
	PayoutBatchAwaitingFunds   = "awaiting_funds"   // approved; waiting for the wallet (Waiting says why)
	PayoutBatchProcessing      = "processing"       // funded: its payments are being sent
	PayoutBatchCompleted       = "completed"        // every payment sent, failed or canceled
	PayoutBatchCanceled        = "canceled"         // canceled before it was funded: nothing was sent
	PayoutBatchRejected        = "rejected"         // an approver refused it (Rejection)
)

Payout batch statuses.

View Source
const (
	PayoutItemValidating = "validating" // being checked
	PayoutItemReady      = "ready"      // checked and priced: it goes
	PayoutItemInvalid    = "invalid"    // Errors say why; never sent, costs nothing
	PayoutItemCooling    = "cooling"    // funded; a new recipient waits until CoolingUntil
	PayoutItemQueued     = "queued"     // funded; waiting for its transfer
	PayoutItemSending    = "sending"    // its transfer is on its way
	PayoutItemSent       = "sent"       // on chain (TxID)
	PayoutItemFailed     = "failed"     // given up (FailReason); its money stays in the wallet
	PayoutItemCanceled   = "canceled"   // canceled, or removed from the open list, before it was sent (CancelReason says why)
	PayoutItemClaimable  = "claimable"  // a claim link, funded: waiting for its recipient (until Claim.ExpiresAt)
	PayoutItemExpired    = "expired"    // a claim link never claimed: its money is free again
)

Payout item (a payment to one recipient) statuses.

View Source
const (
	PayoutCancelRemoved       = "removed"        // taken out of your list of payout requests
	PayoutCancelCanceled      = "canceled"       // the payment alone, by your team or an API key
	PayoutCancelBatchCanceled = "batch_canceled" // its batch was canceled
	PayoutCancelRejected      = "rejected"       // its batch was rejected (CancelNote says why)
	PayoutCancelInvalid       = "invalid"        // no longer payable when its batch was submitted or funded (Errors say why)
)

Why a payment was canceled (PayoutItem.CancelReason).

View Source
const (
	FeePaidByMerchant  = "merchant"  // on top: the recipient receives the whole amount
	FeePaidByRecipient = "recipient" // out of each amount
)

Who pays a batch's fees (PayoutBatch.FeePaidBy).

View Source
const (
	PayoutSameNetwork = "same_network" // each payment from the wallet's balance of its own coin
	PayoutConvert     = "convert"      // every payment not in ConvertFrom paid from ConvertFrom, converted on its way
)

How a batch pays coins its wallet does not hold (PayoutBatch.Convert).

View Source
const (
	PayoutWaitFunds      = "funds"       // the wallet holds less than the batch needs: send the Shortfall
	PayoutWaitDailyLimit = "daily_limit" // the day's limit would be passed: it is funded from 00:00 UTC
	PayoutWaitPaused     = "paused"      // payitgo paused payouts on your account: contact support
)

Why a batch waits (PayoutWaiting.Reason).

View Source
const (
	IssueUnsupportedAsset      = "unsupported_asset"      // error
	IssueInvalidAmount         = "invalid_amount"         // error
	IssueTooPrecise            = "too_precise"            // error: more decimals than the coin takes
	IssueInvalidAddress        = "invalid_address"        // error
	IssueWrongNetwork          = "wrong_network"          // error: an address of another network
	IssueOwnWallet             = "own_wallet"             // error: your own payout wallet
	IssueDuplicateReference    = "duplicate_reference"    // error: another payment carries the reference
	IssueSanctioned            = "sanctioned"             // error: the address is on the sanctions list
	IssueContractRecipient     = "contract_recipient"     // error: BNB to a contract address
	IssueBelowMinimum          = "below_minimum"          // error: worth less than the smallest payment
	IssueOverLimit             = "over_limit"             // error: over your limit per payment
	IssueFeeExceedsAmount      = "fee_exceeds_amount"     // error: the recipient pays fees that would leave too little
	IssueDuplicatePayment      = "duplicate_payment"      // warning: another row pays the same to the same address
	IssueNewHolder             = "new_holder"             // warning: costlier first USDT to a Tron wallet, in its fee
	IssueActivation            = "activation"             // warning: TRX to a Tron address not activated yet, in its fee
	IssueCheckFailed           = "check_failed"           // warning: priced as the costlier case
	IssueNewRecipient          = "new_recipient"          // warning: an address you never paid waits after funding
	IssueInvalidEmail          = "invalid_email"          // error: a claim link's email is not one
	IssueConversionUnavailable = "conversion_unavailable" // error: paying this coin from the wallet's is not available
)

Issue codes (PayoutIssue.Code). An error leaves its payment out; a warning does not. Codes may be added: treat an unknown one by the list it is in (Errors or Warnings) and show its Message.

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"
	// Mass payouts: a batch's progress (data: a PayoutBatch), each payment to
	// a recipient (a PayoutItem), the payout wallet's withdrawals (a
	// PayoutWithdrawal), and schedules' runs (a PayoutSchedule) and the
	// top-ups they need (a PayoutScheduleFunding).
	EventPayoutBatchQuoted            = "payout_batch.quoted"
	EventPayoutBatchPendingApproval   = "payout_batch.pending_approval"
	EventPayoutBatchApproved          = "payout_batch.approved"
	EventPayoutBatchRejected          = "payout_batch.rejected"
	EventPayoutBatchAwaitingFunds     = "payout_batch.awaiting_funds"
	EventPayoutBatchProcessing        = "payout_batch.processing"
	EventPayoutBatchCompleted         = "payout_batch.completed"
	EventPayoutBatchCanceled          = "payout_batch.canceled"
	EventPayoutItemProcessing         = "payout_item.processing" // a payout request left your list for a batch of its own
	EventPayoutItemReturned           = "payout_item.returned"   // a sent payout request came back to your list (not final)
	EventPayoutItemSent               = "payout_item.sent"
	EventPayoutItemFailed             = "payout_item.failed"
	EventPayoutItemCanceled           = "payout_item.canceled"
	EventPayoutItemClaimed            = "payout_item.claimed"       // a claim link's recipient chose the coin and address
	EventPayoutItemClaimExpired       = "payout_item.claim_expired" // a claim link was never claimed: its money is free again
	EventPayoutWalletWithdrawn        = "payout_wallet.withdrawn"
	EventPayoutWalletWithdrawalFailed = "payout_wallet.withdrawal_failed" // a withdrawal failed (FailReason): its money stays in the wallet
	EventPayoutScheduleRun            = "payout_schedule.run"             // a schedule made its batch (or says why not)
	EventPayoutScheduleFundingNeeded  = "payout_schedule.funding_needed"  // the wallet would not cover a schedule's next run
)

Event types: every event of the key's mode is sent. EventPing is sent by WebhooksService.Test. A payout payment's payout_item.* events go to its own WebhookURL, else to its batch's, else to the webhook's URL; a payout batch made with a WebhookURL sends its payout_batch.* events there.

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 (or payout batch'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 PayoutCanceledBySystem = "system"

PayoutCanceledBySystem is PayoutItem.CanceledBy and PayoutBatch.CanceledBy when payitgo itself canceled it.

View Source
const Version = "0.8.1"

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
	Payouts       *PayoutsService
	PayoutBatches *PayoutBatchesService
	PayoutWallets *PayoutWalletsService
	Events        *EventsService
	// 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; Value is its value in the payment's Currency.
	Amount  string `json:"amount"`
	Value   string `json:"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"`
	// Confirmations is how many blocks have confirmed it so far, out of
	// ConfirmationsRequired on its network: show "12 of 20" while it is
	// pending.
	Confirmations         int64 `json:"confirmations"`
	ConfirmationsRequired int64 `json:"confirmations_required"`
	// 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    `json:"status"`
	Message string `json:"message"`
}

Error is a request the API refused. Status is the HTTP status, or 0 for a network error. A call the library refuses before sending it (an empty reference or list of ids) is one too, with Status 400. It is also why one of several ids was not done (PayoutRemoveResult.Error): what a call of its own would have answered.

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, and when it is replayed.
	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, as its webhook carried it or as EventsService.List replays it.

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.

func (*Event) PayoutBatch added in v0.6.0

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

PayoutBatch decodes the batch a payout_batch.* event carries.

func (*Event) PayoutItem added in v0.6.0

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

PayoutItem decodes the payment to a recipient a payout_item.* event carries (payout_item.processing, .returned, .sent, .failed, .canceled, .claimed and .claim_expired).

func (*Event) PayoutSchedule added in v0.6.0

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

PayoutSchedule decodes the schedule a payout_schedule.run event carries.

func (*Event) PayoutScheduleFunding added in v0.6.0

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

PayoutScheduleFunding decodes what a payout_schedule.funding_needed event carries: the schedule, and the shortfall to send before its next run.

func (*Event) PayoutWithdrawal added in v0.6.0

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

PayoutWithdrawal decodes the withdrawal a payout_wallet.withdrawn or payout_wallet.withdrawal_failed event carries.

type EventListParams added in v0.6.0

type EventListParams struct {
	// Types keeps the events of these types: exact (EventPayoutItemSent), or
	// a family ("payout_item.*"). None keeps them all.
	Types []string
	// After is an event's ID: the events after it. Keep the last one you
	// handled.
	After string
	// CreatedAfter keeps the events created after it (ignored with After).
	CreatedAfter time.Time
	Limit        int // 1 to 200 (default 100)
}

EventListParams narrows EventsService.List; zero values are left out.

type EventPage added in v0.6.0

type EventPage struct {
	Events  []Event `json:"events"`
	HasMore bool    `json:"has_more"`
}

EventPage is one page of EventsService.List: events, oldest first, each decoded with the Event methods as on a webhook. While HasMore, read on with After set to the last event's ID.

type EventsService added in v0.6.0

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

EventsService replays the events of the key's mode.

func (*EventsService) List added in v0.6.0

List returns the events of the key's mode exactly as their webhooks carried them, oldest first: replay the ones your system missed. Events are kept; pings are left out, and events of the last 5 seconds are left for the next read, so moving forward never skips one. Any account key reads them (read-only keys too); a storefront's key gets an *Error with Status 403. A key without payouts gets claim links without their URL and PIN.

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 payitgo's API address. Without it the client uses the PAYITGO_BASE_URL environment variable, then "https://api.payitgo.co".

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 is what the customer sends, in Token; CryptoReceived what
	// has arrived in it.
	CryptoAmount   string `json:"crypto_amount"`
	CryptoReceived string `json:"crypto_received"`
	// Currency is what the payment was priced in: an ISO 4217 code, upper
	// case ("USD" unless PaymentParams.Currency gave another), or the coin of
	// a payment link priced in a coin. Every figure below is in it: Amount is
	// your price; AmountDue what the customer pays, the price plus the fees
	// when you pass them on; AmountReceived what has arrived so far;
	// AmountExtra the part of AmountDue paid only to reach the exchange's
	// minimum, which you receive (empty when there is none); RateLocked the
	// coin's price, locked when the coin was chosen.
	Currency           string    `json:"currency"`
	Amount             string    `json:"amount"`
	AmountDue          string    `json:"amount_due"`
	AmountReceived     string    `json:"amount_received"`
	AmountExtra        string    `json:"amount_extra,omitempty"`
	FeesPaidByCustomer bool      `json:"fees_paid_by_customer"`
	Settlement         string    `json:"settlement"` // "custodial" (your balance) or "direct" (your payout address)
	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"`
	// Confirmations is the latest deposit's, out of ConfirmationsRequired on
	// the payment's network: while the status is detecting, the customer's
	// payment is on the network and these say how far it is from final.
	// DetectedAt is when the first deposit was seen.
	Confirmations         int64             `json:"confirmations"`
	ConfirmationsRequired int64             `json:"confirmations_required"`
	DetectedAt            *time.Time        `json:"detected_at,omitempty"`
	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"`
	Amount        string            `json:"amount"`             // decimal, e.g. "19.99"
	Currency      string            `json:"currency,omitempty"` // e.g. "EUR"; US dollars when empty
	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 Amount, the price in Currency: an ISO 4217 code such as "EUR", "GBP" or "NGN" (any case), US dollars when empty. 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 PayoutApproval added in v0.6.0

type PayoutApproval struct {
	UserID string    `json:"user_id"`
	At     time.Time `json:"at"`
}

PayoutApproval is a team member's approval of a batch.

type PayoutAssetTotal added in v0.6.0

type PayoutAssetTotal struct {
	Asset      string `json:"asset"`
	Ticker     string `json:"ticker"`
	IconURL    string `json:"icon_url"`
	Chain      string `json:"chain"`
	Network    string `json:"network"`
	Items      int    `json:"items"`
	Amount     string `json:"amount"`
	SendAmount string `json:"send_amount"`
	Fee        string `json:"fee"`
	Debit      string `json:"debit"`
	DebitUSD   string `json:"debit_usd"`
	SavedUSD   string `json:"saved_usd"`
}

PayoutAssetTotal is a batch's payments in one coin: how many (Items), what they send, what they pay, and what the wallet gives (Debit, and DebitUSD in dollars); SavedUSD is what sending them together saves in network fees.

type PayoutBatch added in v0.6.0

type PayoutBatch struct {
	ID         string `json:"id"`
	MerchantID string `json:"merchant_id"`
	Livemode   bool   `json:"livemode"`
	Reference  string `json:"reference,omitempty"` // your id for it, unique in its mode
	Name       string `json:"name"`
	Source     string `json:"source"` // "api", "dashboard", "csv", "requests" or "schedule"
	Inbox      bool   `json:"inbox"`  // made of payout requests
	Open       bool   `json:"open"`   // your open list of payout requests
	// CreatedBy is the team member who made it, or the API key's id (ByAPIKey).
	CreatedBy string `json:"created_by"`
	ByAPIKey  bool   `json:"by_api_key"`
	FeePaidBy string `json:"fee_paid_by"` // FeePaidByMerchant or FeePaidByRecipient
	// Convert is PayoutSameNetwork or PayoutConvert: then every payment not
	// in ConvertFrom is paid from ConvertFrom, converted on its way.
	Convert     string         `json:"convert"`
	ConvertFrom string         `json:"convert_from,omitempty"`
	WebhookURL  string         `json:"webhook_url,omitempty"` // where its events go, and its payments' without their own, instead of the webhook's URL
	Status      string         `json:"status"`                // a PayoutBatch… constant
	Waiting     *PayoutWaiting `json:"waiting,omitempty"`     // while it waits for funds, the day's limit or a pause
	// Totals are its payments that go, per coin; Counts its payments by
	// status; TotalUSD what it takes from the wallet, in dollars.
	Totals          []PayoutAssetTotal `json:"totals"`
	Counts          PayoutCounts       `json:"counts"`
	TotalUSD        string             `json:"total_usd"`
	QuoteExpiresAt  *time.Time         `json:"quote_expires_at,omitempty"` // its prices hold until then
	ApprovalsNeeded int                `json:"approvals_needed"`
	Approvals       []PayoutApproval   `json:"approvals"`
	Rejection       *PayoutDecision    `json:"rejection,omitempty"`
	SubmittedBy     string             `json:"submitted_by,omitempty"`
	SubmittedAt     *time.Time         `json:"submitted_at,omitempty"`
	FundedAt        *time.Time         `json:"funded_at,omitempty"`
	CompletedAt     *time.Time         `json:"completed_at,omitempty"`
	CanceledBy      string             `json:"canceled_by,omitempty"` // a team member's id, an API key's id, or PayoutCanceledBySystem
	CanceledAt      *time.Time         `json:"canceled_at,omitempty"`
	CreatedAt       time.Time          `json:"created_at"`
	UpdatedAt       time.Time          `json:"updated_at"`
}

PayoutBatch is a set of payments checked, priced, approved and funded together. Your open list of payout requests is one too (Inbox and Open): it is never submitted itself; sending moves its requests into a batch of their own.

type PayoutBatchList added in v0.6.0

type PayoutBatchList struct {
	Batches []PayoutBatch `json:"batches"`
	Total   int           `json:"total"`
	Limit   int           `json:"limit"`
	Offset  int           `json:"offset"`
}

PayoutBatchList is one page of batches.

type PayoutBatchParams added in v0.6.0

type PayoutBatchParams struct {
	Reference   string         `json:"reference,omitempty"`
	Name        string         `json:"name,omitempty"`
	FeePaidBy   string         `json:"fee_paid_by,omitempty"`
	Convert     string         `json:"convert,omitempty"`
	ConvertFrom string         `json:"convert_from,omitempty"`
	WebhookURL  string         `json:"webhook_url,omitempty"`
	Items       []PayoutParams `json:"items"`
}

PayoutBatchParams makes a batch of 1 to 1000 payments (add more with PayoutBatchesService.AddItems, up to 10,000). Reference, your id for the batch, makes Create safe to retry. FeePaidBy, Convert and ConvertFrom default to your payout settings: with Convert PayoutConvert, every payment in another coin than ConvertFrom (a coin, e.g. "USDT_TRC20") is paid from ConvertFrom, converted on its way. WebhookURL (https) gets the batch's events, and those of its payments without a WebhookURL of their own, instead of the webhook's URL.

type PayoutBatchesService added in v0.6.0

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

PayoutBatchesService makes and follows batches: a whole list of payments at once.

func (*PayoutBatchesService) AddItems added in v0.6.0

func (s *PayoutBatchesService) AddItems(ctx context.Context, id string, items []PayoutParams) (*PayoutBatch, error)

AddItems adds 1 to 1000 payments to a batch not submitted yet; the whole batch is checked and priced again.

func (*PayoutBatchesService) Cancel added in v0.6.0

Cancel cancels a batch not funded yet; once it is processing, its payments not sent yet are canceled and their money stays in the wallet.

func (*PayoutBatchesService) Create added in v0.6.0

Create makes a batch; up to 100 payments are checked while the call waits and the batch comes back PayoutBatchQuoted (a larger one PayoutBatchValidating, then quoted within a minute or two). Safe to retry with a Reference: a reference used already returns that batch, with nothing added.

func (*PayoutBatchesService) Items added in v0.6.0

Items returns a page of a batch's payments, in row order.

func (*PayoutBatchesService) List added in v0.6.0

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

func (*PayoutBatchesService) Quote added in v0.6.0

Quote checks and prices a batch not submitted yet again, at today's prices: they then hold for another hour. Use it when Submit answers 409 because its prices expired.

func (*PayoutBatchesService) Retrieve added in v0.6.0

func (s *PayoutBatchesService) Retrieve(ctx context.Context, id string) (*PayoutBatch, error)

Retrieve returns a batch by its id.

func (*PayoutBatchesService) Submit added in v0.6.0

Submit sends a quoted batch on: its ready payments go, the invalid ones stay out. It waits for its approvals and funds (Waiting says how much to send where), or is funded at once.

type PayoutClaim added in v0.6.0

type PayoutClaim struct {
	Email        string     `json:"email,omitempty"`
	Assets       []string   `json:"assets"`
	ExpiresAt    *time.Time `json:"expires_at,omitempty"`
	ClaimedAt    *time.Time `json:"claimed_at,omitempty"`
	Emailed      int        `json:"emailed"`
	LastEmailAt  *time.Time `json:"last_email_at,omitempty"`
	Extended     int        `json:"extended"`
	FundedAsset  string     `json:"funded_asset,omitempty"`
	FundedAmount string     `json:"funded_amount,omitempty"`
	URL          string     `json:"url,omitempty"`
	PIN          string     `json:"pin,omitempty"`
	PINLocked    bool       `json:"pin_locked,omitempty"`
}

PayoutClaim is a claim link's state: a payment its recipient claims, choosing the coin (its own, or one of Assets, paid at the same dollar value) and the address. URL is the link: emailed to Email when there is one (the recipient confirms with a code sent there), yours to share otherwise, with PIN, the 6 digits the recipient must enter: give it another way than the link (a call, a text message), so the link alone pays no one. PINLocked: 5 wrong PINs were entered; a new PIN from the dashboard unlocks it. Emailed counts the emails sent, Extended how often its end was pushed back. Once claimed in another coin, FundedAsset and FundedAmount are what it was funded with (the payment's Asset and Amount are then the chosen coin's).

type PayoutConversion added in v0.6.0

type PayoutConversion struct {
	To        string `json:"to"`
	Ticker    string `json:"ticker"`
	Network   string `json:"network"`
	ToAmount  string `json:"to_amount"`
	Estimate  string `json:"estimate"`
	AmountOut string `json:"amount_out,omitempty"`
}

PayoutConversion is a payment converted on its way: you asked to pay ToAmount of To (its Ticker, on Network); the recipient receives about Estimate of it, and AmountOut once it is sent.

type PayoutCounts added in v0.6.0

type PayoutCounts struct {
	Total     int `json:"total"`
	Invalid   int `json:"invalid"`
	Ready     int `json:"ready"`
	Cooling   int `json:"cooling"`
	Queued    int `json:"queued"`
	Sending   int `json:"sending"`
	Sent      int `json:"sent"`
	Failed    int `json:"failed"`
	Canceled  int `json:"canceled"`
	Claimable int `json:"claimable"`
	Expired   int `json:"expired"`
}

PayoutCounts are a batch's payments by status.

type PayoutCoverage added in v0.6.0

type PayoutCoverage struct {
	Asset     string `json:"asset"`
	Ticker    string `json:"ticker"`
	Network   string `json:"network"`
	Needed    string `json:"needed"`
	Spendable string `json:"spendable"`
	TopUp     string `json:"top_up"`
	Address   string `json:"address"`
}

PayoutCoverage is what sending your valid payout requests in one coin takes (Needed) against what the wallet can spend; TopUp is the difference to send to Address first ("0" when the wallet covers it).

type PayoutDecision added in v0.6.0

type PayoutDecision struct {
	By     string    `json:"by"`
	At     time.Time `json:"at"`
	Reason string    `json:"reason"`
}

PayoutDecision is who refused a batch, when, and why.

type PayoutInbox added in v0.6.0

type PayoutInbox struct {
	Inbox    PayoutBatch      `json:"inbox"`
	Coverage []PayoutCoverage `json:"coverage"`
	Items    []PayoutItem     `json:"items"`
	Total    int              `json:"total"`
	Limit    int              `json:"limit"`
	Offset   int              `json:"offset"`
}

PayoutInbox is your open list of payout requests: the list itself (its Totals and Counts), what sending its valid requests takes of each coin, and one page of the requests.

type PayoutIssue added in v0.6.0

type PayoutIssue struct {
	Code    string `json:"code"`            // an Issue… constant
	Field   string `json:"field,omitempty"` // asset, amount, address, tag, reference, email or claim_assets
	Message string `json:"message"`
	Hint    string `json:"hint,omitempty"`
}

PayoutIssue is something wrong with a payment (in Errors: it is left out) or worth knowing (in Warnings): Code for programs, Message for people, Hint what to do.

type PayoutItem added in v0.6.0

type PayoutItem struct {
	ID         string `json:"id,omitempty"`
	MerchantID string `json:"merchant_id,omitempty"`
	Livemode   bool   `json:"livemode"`
	BatchID    string `json:"batch_id,omitempty"` // its batch, or your open list of payout requests; empty for a request removed from the list
	// Reference is your id for it, unique in its mode. RefusedReference is
	// one it was given that another payment carries (it keeps none, and is
	// invalid); ReleasedReference the one it had once canceled or failed
	// (never sent), free for a new payment.
	Reference         string          `json:"reference,omitempty"`
	RefusedReference  string          `json:"refused_reference,omitempty"`
	ReleasedReference string          `json:"released_reference,omitempty"`
	Row               int             `json:"row"` // its place in the batch, from 1
	Recipient         PayoutRecipient `json:"recipient"`
	Asset             string          `json:"asset"`              // the coin paid from the wallet: "USDT_TRC20", …
	Ticker            string          `json:"ticker,omitempty"`   // what people call the coin: "USDT"
	IconURL           string          `json:"icon_url,omitempty"` // its icon, an SVG image
	Chain             string          `json:"chain"`
	Address           string          `json:"address"`
	Tag               *uint32         `json:"tag,omitempty"`
	// Amount is what you asked to pay; SendAmount what reaches the
	// recipient; Fee is the whole fee (a converted payment's converting
	// included); Debit what it takes from the wallet. AmountUSD is Amount
	// at USDRate.
	Amount       string        `json:"amount"`
	SendAmount   string        `json:"send_amount"`
	Fee          string        `json:"fee"`
	Debit        string        `json:"debit"`
	USDRate      string        `json:"usd_rate"`
	AmountUSD    string        `json:"amount_usd"`
	Status       string        `json:"status"` // a PayoutItem… constant
	Errors       []PayoutIssue `json:"errors"`
	Warnings     []PayoutIssue `json:"warnings"`
	CoolingUntil *time.Time    `json:"cooling_until,omitempty"`
	TxID         string        `json:"tx_id,omitempty"`        // once sent (made up in test mode)
	ExplorerURL  string        `json:"explorer_url,omitempty"` // live only
	FailReason   string        `json:"fail_reason,omitempty"`
	CancelReason string        `json:"cancel_reason,omitempty"` // why it was canceled: a PayoutCancel… constant
	CancelNote   string        `json:"cancel_note,omitempty"`   // a rejection's reason (PayoutCancelRejected)
	CanceledBy   string        `json:"canceled_by,omitempty"`   // who canceled it: a team member's id, an API key's id, or PayoutCanceledBySystem
	CanceledAt   *time.Time    `json:"canceled_at,omitempty"`   // when it was canceled
	// Members is the email of the team member CanceledBy names, by id, as it
	// was when they acted.
	Members    map[string]string `json:"members,omitempty"`
	WebhookURL string            `json:"webhook_url,omitempty"` // where its events go instead of its batch's WebhookURL or the webhook's URL
	Claim      *PayoutClaim      `json:"claim,omitempty"`       // a claim link
	// Convert is set on a payment converted on its way.
	Convert *PayoutConversion `json:"convert,omitempty"`
	// FeeCredit is the fee given back for a payment never sent, taken off
	// your next batch's fees in its coin.
	FeeCredit string     `json:"fee_credit,omitempty"`
	SentAt    *time.Time `json:"sent_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

PayoutItem is one payment to a recipient: a payout request, or a row of a batch. Amounts are decimal strings in Asset; while it is validating and when it is invalid, its fees and dollar figures are "0". In a quote nothing is kept: ID, MerchantID, BatchID and the times are empty. A claim link (Claim) has no Address until its recipient claims it. A converted payment (Convert) has Asset, Chain, Amount, Fee and Debit in the wallet's coin (the batch's ConvertFrom), and Address on Convert.To's network.

type PayoutItemList added in v0.6.0

type PayoutItemList struct {
	Items  []PayoutItem `json:"items"`
	Total  int          `json:"total"`
	Limit  int          `json:"limit"`
	Offset int          `json:"offset"`
}

PayoutItemList is one page of a batch's payments, in row order.

type PayoutListParams added in v0.6.0

type PayoutListParams struct {
	Status string
	Limit  int
	Offset int
}

PayoutListParams narrows a listing of batches, a batch's payments or payout requests (PayoutsService.List takes PayoutPageParams); zero values are left out. Status is one status, or for PayoutBatchesService.Items and PayoutsService.Inbox several, comma-separated ("sent,failed"). Limit is 1 to 200 (default 50).

type PayoutPage added in v0.6.0

type PayoutPage struct {
	Items      []PayoutItem `json:"items"`
	HasMore    bool         `json:"has_more"`
	NextCursor string       `json:"next_cursor,omitempty"`
}

PayoutPage is one page of PayoutsService.List: payments, oldest change first. While HasMore, read on with Cursor set to NextCursor. NextCursor is empty when the page is: keep the cursor you passed.

type PayoutPageParams added in v0.6.0

type PayoutPageParams struct {
	// Status keeps the payments in these statuses (PayoutItem… constants);
	// none keeps them all.
	Status []string
	// UpdatedSince keeps the payments changed at or after it: for your first
	// read.
	UpdatedSince time.Time
	// Cursor is the NextCursor of the page before: the payments changed after
	// the last one it listed.
	Cursor string
	Limit  int // 1 to 200 (default 50)
}

PayoutPageParams narrows PayoutsService.List; zero values are left out.

type PayoutParams added in v0.6.0

type PayoutParams struct {
	Reference   string   `json:"reference,omitempty"`
	Asset       string   `json:"asset"` // "USDT_TRC20", "BTC", …
	Address     string   `json:"address,omitempty"`
	Tag         *uint32  `json:"tag,omitempty"` // an XRP destination tag
	Amount      string   `json:"amount"`        // decimal, in the coin, e.g. "120"
	Name        string   `json:"name,omitempty"`
	Email       string   `json:"email,omitempty"` // a claim link's link is emailed there
	Note        string   `json:"note,omitempty"`
	Claim       bool     `json:"claim,omitempty"`        // a claim link
	ClaimAssets []string `json:"claim_assets,omitempty"` // the other coins its recipient may choose (a claim link)
	WebhookURL  string   `json:"webhook_url,omitempty"`  // where its events go instead of its batch's or the webhook's URL
	Simulate    string   `json:"simulate,omitempty"`     // test mode only: "failed" or "failed_after_broadcast" (sent by default)
}

PayoutParams is one payment to a recipient: a payout request (PayoutsService.Request), or an item of a batch or a quote. Asset and Amount are required, and Address unless it is a claim link. Reference, your id for the payment, is unique in its mode: send one, so that a retry never pays twice. Name, Email and Note are kept with it. Empty optional fields are left out.

A claim link has no Address: its recipient chooses the coin (Asset, or one of ClaimAssets, at the same dollar value) and the address. Claim links are opt-in: Claim, or giving ClaimAssets, makes one; an Email without an Address and without Claim is refused like any missing address. With an Email its link is emailed there; without one you share it (PayoutItem.Claim.URL) yourself, and give its PIN (Claim.PIN) another way: the recipient enters it. A claim link is never converted.

WebhookURL (https, on a public host) gets the payment's events, signed with the mode's secret: it comes before its batch's WebhookURL and the webhook's URL, and a payout request keeps it when it is sent into a batch. The payments of one call may name at most 10 different WebhookURLs.

type PayoutQuote added in v0.6.0

type PayoutQuote struct {
	Quote PayoutQuoteTotals `json:"quote"`
	Items []PayoutItem      `json:"items"`
}

PayoutQuote is what payments would cost, nothing kept: the totals a batch of them would have, and each payment with its fees and issues.

type PayoutQuoteParams added in v0.6.0

type PayoutQuoteParams struct {
	FeePaidBy   string         `json:"fee_paid_by,omitempty"`
	Convert     string         `json:"convert,omitempty"`
	ConvertFrom string         `json:"convert_from,omitempty"`
	Items       []PayoutParams `json:"items"`
}

PayoutQuoteParams prices 1 to 100 payments without keeping anything; FeePaidBy, Convert and ConvertFrom as in PayoutBatchParams.

type PayoutQuoteTotals added in v0.6.0

type PayoutQuoteTotals struct {
	Livemode    bool               `json:"livemode"`
	FeePaidBy   string             `json:"fee_paid_by"`
	Convert     string             `json:"convert"`
	ConvertFrom string             `json:"convert_from"`
	Totals      []PayoutAssetTotal `json:"totals"`
	TotalUSD    string             `json:"total_usd"`
	Counts      PayoutCounts       `json:"counts"`
}

PayoutQuoteTotals are a quote's totals, as a batch would have them; ConvertFrom is empty without conversion.

type PayoutRecipient added in v0.6.0

type PayoutRecipient struct {
	Name  string `json:"name,omitempty"`
	Email string `json:"email,omitempty"`
	Note  string `json:"note,omitempty"`
}

PayoutRecipient is who a payment is for, as you named them.

type PayoutRemoveResult added in v0.6.0

type PayoutRemoveResult struct {
	ID    string      `json:"id"`
	Item  *PayoutItem `json:"item,omitempty"`
	Error *Error      `json:"error,omitempty"`
}

PayoutRemoveResult is what PayoutsService.Remove did with one id: the request, now canceled (Item), or why it was not removed (Error: Status 404 "not found", or 409 for a request sent from the list already or one that ended).

type PayoutSchedule added in v0.6.0

type PayoutSchedule struct {
	ID          string                `json:"id"`
	Livemode    bool                  `json:"livemode"`
	Name        string                `json:"name"`
	Status      string                `json:"status"`
	Cadence     string                `json:"cadence"`
	Weekday     int                   `json:"weekday"`
	Day         int                   `json:"day"`
	At          string                `json:"at"`
	Timezone    string                `json:"timezone"`
	FeePaidBy   string                `json:"fee_paid_by"`
	AutoSubmit  bool                  `json:"auto_submit"`
	RemindDays  int                   `json:"remind_days"` // how many days before a run a short wallet is told
	Totals      []PayoutScheduleTotal `json:"totals"`
	NextRunAt   *time.Time            `json:"next_run_at"`
	LastRunAt   *time.Time            `json:"last_run_at"`
	LastBatchID string                `json:"last_batch_id"`
	LastError   string                `json:"last_error"`
	Runs        int                   `json:"runs"`
}

PayoutSchedule is a batch made again and again (set up in the dashboard), as payout_schedule.* events tell it: everything but its rows, whose recipients stay in the dashboard. Cadence is "weekly" (on Weekday, 0 for Sunday), "biweekly" or "monthly" (on Day, 1 to 28, or -1 for the month's last day), at At ("09:00") in Timezone. Status is "active" or "paused". Each run makes a batch (Source "schedule"): LastBatchID, or LastError saying why it made none. NextRunAt and LastRunAt are nil when there is none.

type PayoutScheduleFunding added in v0.6.0

type PayoutScheduleFunding struct {
	Schedule  PayoutSchedule    `json:"schedule"`
	Shortfall []PayoutShortfall `json:"shortfall"`
}

PayoutScheduleFunding is what a payout_schedule.funding_needed event carries: a schedule whose next run the wallet would not cover, and what to send where before it.

type PayoutScheduleTotal added in v0.6.0

type PayoutScheduleTotal struct {
	Asset  string `json:"asset"`
	Ticker string `json:"ticker"`
	Items  int    `json:"items"`
	Amount string `json:"amount"`
}

PayoutScheduleTotal is what a schedule's rows pay in one coin each run (fees aside: they are priced at the run).

type PayoutShortfall added in v0.6.0

type PayoutShortfall struct {
	Asset   string `json:"asset"`
	Network string `json:"network"`
	Amount  string `json:"amount"`
	Address string `json:"address"`
}

PayoutShortfall is how much more of Asset the wallet needs, and the address (on Network) to send it to.

type PayoutWaiting added in v0.6.0

type PayoutWaiting struct {
	Reason    string            `json:"reason"`
	Note      string            `json:"note"`
	Since     time.Time         `json:"since"`
	Shortfall []PayoutShortfall `json:"shortfall,omitempty"`
}

PayoutWaiting is why a batch waits (a PayoutWait… constant), said for people in Note; for PayoutWaitFunds, Shortfall is what to send where.

type PayoutWallet added in v0.6.0

type PayoutWallet struct {
	Chain       string              `json:"chain"`
	Network     string              `json:"network"`
	Address     string              `json:"address"`
	ExplorerURL string              `json:"explorer_url,omitempty"` // live only
	Livemode    bool                `json:"livemode"`
	Assets      []PayoutWalletAsset `json:"assets"`
	Error       string              `json:"error,omitempty"`
}

PayoutWallet is your payout wallet on one network (Chain "tron", "bsc", "ethereum", …): the address to top up, and what it holds of each coin it pays in. Error says why its balances could not be read just now (they are then "0").

type PayoutWalletAsset added in v0.6.0

type PayoutWalletAsset struct {
	Asset     string `json:"asset"`
	Ticker    string `json:"ticker"`
	IconURL   string `json:"icon_url"`
	Balance   string `json:"balance"`
	Reserved  string `json:"reserved"`
	Spendable string `json:"spendable"`
	Needed    string `json:"needed"`
}

PayoutWalletAsset is what a payout wallet holds of one coin: Balance (on paper in test mode), Reserved for payments, fees and withdrawals not sent yet, Spendable the rest, and Needed what batches waiting for funds need beyond Spendable: the top-up to send.

type PayoutWalletsService added in v0.6.0

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

PayoutWalletsService reads your payout wallet, and tops up the test one.

func (*PayoutWalletsService) List added in v0.6.0

List returns your payout wallet of the key's mode, one per network, each with what it holds of each coin. It is made the first time it is asked for, and never changes.

func (*PayoutWalletsService) SimulateTopUp added in v0.6.0

func (s *PayoutWalletsService) SimulateTopUp(ctx context.Context, asset, amount string) ([]PayoutWallet, error)

SimulateTopUp adds amount (a decimal string, over 0 and up to 10,000,000) of asset to the test wallet's paper balance, and funds any test batch waiting for it. Test keys only: a live key is an *Error with Status 400.

type PayoutWithdrawal added in v0.6.0

type PayoutWithdrawal struct {
	ID          string     `json:"id"`
	MerchantID  string     `json:"merchant_id"`
	Livemode    bool       `json:"livemode"`
	Asset       string     `json:"asset"`
	Chain       string     `json:"chain"`
	Amount      string     `json:"amount"`
	Fee         string     `json:"fee"`
	SendAmount  string     `json:"send_amount"`
	AddressID   string     `json:"address_id"`
	Address     string     `json:"address"`
	Tag         *uint32    `json:"tag,omitempty"`
	Status      string     `json:"status"`
	TxID        string     `json:"tx_id,omitempty"`
	ExplorerURL string     `json:"explorer_url,omitempty"`
	FailReason  string     `json:"fail_reason,omitempty"` // why it failed
	RequestedBy string     `json:"requested_by"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	SentAt      *time.Time `json:"sent_at,omitempty"`
}

PayoutWithdrawal is a payout wallet's funds in one coin sent back to one of your payout addresses (made in the dashboard, by the owner): Amount leaves the wallet, Fee goes to payitgo, SendAmount arrives. Status is "requested", "sending", "sent" or "failed" (FailReason says why; its money stays in the wallet).

type PayoutsService added in v0.6.0

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

PayoutsService takes your clients' payout requests one by one, sends or removes them, and reads, lists, cancels and quotes payments to recipients.

func (*PayoutsService) Cancel added in v0.6.0

func (s *PayoutsService) Cancel(ctx context.Context, id string) (*PayoutItem, error)

Cancel takes a payout request still in your open list out of it (its record is kept: CancelReason PayoutCancelRemoved, no BatchID), or cancels a payment that was sent but is not on its way yet (PayoutCancelCanceled). It comes back with Status PayoutItemCanceled. A payment canceled already comes back as it is: safe to retry.

func (*PayoutsService) Inbox added in v0.6.0

Inbox returns your open list of payout requests: the list, what sending its valid requests needs of each coin against what the wallet can spend (Coverage, with the top-up to send first), and a page of the requests.

func (*PayoutsService) List added in v0.6.0

List returns the payments of the key's mode whatever their batch (payout requests in your list, removed ones, and every batch's), oldest change first, to bring your records back in sync. Read with UpdatedSince the first time, then with Cursor set to NextCursor while HasMore; keep the last NextCursor to read what changed since, later. Changes of the last 5 seconds are left for the next read, so a cursor never skips one.

func (*PayoutsService) Quote added in v0.6.0

Quote prices up to 100 payments, checked exactly as in a batch, without keeping anything: show a client their fee before they ask for a payout.

func (*PayoutsService) Remove added in v0.6.0

func (s *PayoutsService) Remove(ctx context.Context, ids ...string) ([]PayoutRemoveResult, error)

Remove takes 1 to 1000 payout requests out of your open list at once. Each one still waiting there is canceled (CancelReason PayoutCancelRemoved): its reference is free again (ReleasedReference), and its record is kept, with no BatchID. It never cancels a request sent from the list already: Cancel does. The results come one per id (given twice, once), in the order given. A request removed already comes back as it is: safe to retry. No ids is an *Error with Status 400, sent nowhere.

func (*PayoutsService) Request added in v0.6.0

func (s *PayoutsService) Request(ctx context.Context, p *PayoutParams) (*PayoutItem, error)

Request adds one of your clients' payout requests to your open list, checked and priced at once. A request that fails a check is kept too, with Status PayoutItemInvalid and Errors saying why, and is never sent. Safe to retry with a Reference: a reference another payment carries returns that payment.

func (*PayoutsService) Retrieve added in v0.6.0

func (s *PayoutsService) Retrieve(ctx context.Context, id string) (*PayoutItem, error)

Retrieve returns a payment to a recipient by its id: a payout request or a batch's payment.

func (*PayoutsService) RetrieveByReference added in v0.6.0

func (s *PayoutsService) RetrieveByReference(ctx context.Context, reference string) (*PayoutItem, error)

RetrieveByReference returns the payment that carries your reference, or else the latest payment that gave it back (canceled, failed or expired, with it as ReleasedReference): what became of a request sent with it. An empty reference is an *Error with Status 400, sent nowhere.

func (*PayoutsService) Send added in v0.6.0

func (s *PayoutsService) Send(ctx context.Context, ids ...string) (*PayoutBatch, error)

Send sends your open payout requests: those of ids, or every valid one when none is given. They move into a new batch, priced again and submitted: it then waits for its approvals and funds, or starts. The rest stay in the list.

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"`
	Minimum    string `json:"minimum"`
	NetworkFee string `json:"network_fee"`
	// AmountDue, 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; AmountExtra the part of it paid only to reach the exchange's
	// minimum, which the merchant receives.
	AmountDue   string `json:"amount_due,omitempty"`
	AmountExtra string `json:"amount_extra,omitempty"`
	FeeNote     string `json:"fee_note"`
}

TokenInfo is a token a customer can pay with. Its figures are in the listing's currency: a payment's own for its TokenOptions, the one TokensService.List was asked for (US dollars without one). Minimum and NetworkFee move with the network's fees.

type TokenListParams

type TokenListParams struct {
	// Amount, when set, lists only the tokens a payment of that amount
	// offers (its TokenOptions), each with AmountDue when fees are passed on.
	Amount string
	// Currency is the ISO 4217 code that Amount and every figure listed are
	// in (any case); US dollars when empty.
	Currency string
}

TokenListParams narrows a token listing; nil lists every token, in US dollars.

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, their figures in the currency asked for.

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