Go library
The github.com/payitgo/go-sdk module wraps the payitgo API for Go:
payments, tokens, your webhook (IPN) and its signature check, the replay of
past events, the public checkout calls, and mass payouts to your
own clients. It uses only
the standard library. Use it on your server only:
it holds your secret key.
Structs carry the API's fields with Go names (OrderID, CheckoutURL, …) and
the API's JSON tags, so the Payments,
Webhooks, Checkout and
Mass payouts pages describe every field this library returns.
Every method that calls the API takes a context.Context and returns an
error last. On error the value returned with it holds no data (and may be
nil): check err first.
Install
go get github.com/payitgo/go-sdk
import payitgo "github.com/payitgo/go-sdk"
The package is named payitgo; import it with that name, since the import path
ends in go.
| Requirement | |
|---|---|
| Go | 1.23 or later |
| Dependencies | github.com/coder/websocket, for Realtime |
Quickstart
package main
import (
"context"
"fmt"
"log"
"os"
payitgo "github.com/payitgo/go-sdk"
)
func main() {
client, err := payitgo.NewClient(os.Getenv("PAYITGO_KEY"))
if err != nil {
log.Fatal(err)
}
payment, err := client.Payments.Create(context.Background(), &payitgo.PaymentParams{
OrderID: "ORD-1001", Amount: "49.90", Token: "USDT_TRC20",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(payment.CryptoAmount, payment.Token, "to", payment.DepositAddress)
}
Then set your webhook URL and fulfil the order when
payment.confirmed arrives.
Configuration
NewClient
func NewClient(apiKey string, opts ...Option) (*Client, error)
| Parameter | Type | Required | Description |
|---|---|---|---|
apiKey |
string | yes | Your secret key, test or live (Authentication) |
opts |
...Option |
no | The options below |
| Option | Default | Description |
|---|---|---|
WithBaseURL(u string) |
PAYITGO_BASE_URL, then https://api.payitgo.co |
payitgo's API, default https://api.payitgo.co (Base URL). Trailing slashes are removed |
WithHTTPClient(h *http.Client) |
&http.Client{Timeout: 30 * time.Second} |
The HTTP client every request goes through: your timeout, transport, proxy or tracing. Its Timeout is the limit for one attempt; a zero Timeout means none |
WithMaxRetries(n int) |
2 |
How many times a request is retried after a network error, a 429 or a 5xx. 0 turns retries off |
WithWebhookSecret(secret string) |
none | Your mode's signing secret. Webhooks.ConstructEvent uses it when you pass none |
WithWebhookURL(u string) |
none | Sent as webhook_url with every Payments.Create whose PaymentParams.WebhookURL is empty |
NewClient makes no request. It returns an error when:
| Error | Cause |
|---|---|
payitgo: the API key is required |
apiKey is empty |
payitgo: WithBaseURL is empty: leave it out to use https://api.payitgo.co |
WithBaseURL(""), for example WithBaseURL(os.Getenv("PAYITGO_BASE_URL")) with the variable unset: leave the option out to use https://api.payitgo.co |
client, err := payitgo.NewClient(os.Getenv("PAYITGO_KEY"),
payitgo.WithHTTPClient(&http.Client{Timeout: 15 * time.Second}),
payitgo.WithMaxRetries(2),
payitgo.WithWebhookSecret(os.Getenv("PAYITGO_WEBHOOK_SECRET")), // the signing secret of the key's mode
payitgo.WithWebhookURL("https://api.yourdomain.com/payitgo/ipn"), // optional default for Payments.Create
)
if err != nil {
log.Fatal(err)
}
A *Client is safe for concurrent use: create one and share it.
The Client
type Client struct {
Payments *PaymentsService
Tokens *TokensService
Checkout *CheckoutService
Webhooks *WebhooksService
Payouts *PayoutsService
PayoutBatches *PayoutBatchesService
PayoutWallets *PayoutWalletsService
Events *EventsService
Realtime *RealtimeService
// unexported fields
}
payitgo.Version ("0.7.1") is sent in the User-Agent: payitgo-go/0.7.1
header.
IsLive
GET /v1/webhook · API reference
func (c *Client) IsLive(ctx context.Context) (bool, error)
Returns true for a live key, false for a test key. A key does not say
its mode, so the first call asks payitgo (the Livemode of the key's
webhook; a read-only key may call it) and the answer is kept
for the client's life: later calls make no request. Safe for concurrent use.
Errors a *payitgo.Error, as any call: 401 for a key
payitgo does not know, 403 for a live key while live mode is off. An error
is not kept: the next call asks again.
live, err := client.IsLive(ctx)
if err != nil {
return err
}
if !live {
log.Println("test mode: payments are simulated")
}
Base URL
Every request goes to payitgo's API, default https://api.payitgo.co, so you
need not set it. The address is taken from, in order: WithBaseURL, the
PAYITGO_BASE_URL environment variable, and https://api.payitgo.co:
export PAYITGO_BASE_URL=https://api.payitgo.co
Timeouts, cancellation and the HTTP client
Each request is sent with the client's *http.Client (30-second timeout by
default; replace it with WithHTTPClient) and your ctx. The context bounds
the whole call, retries and waits included; a cancelled or expired context
stops it at once and is not retried. Requests carry the headers
Authorization: Bearer <key> (except the two Checkout calls),
Accept: application/json, Content-Type: application/json (when there is a
body) and User-Agent: payitgo-go/0.7.1.
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
payment, err := client.Payments.Get(ctx, "ORD-1001")
if err != nil {
return err // a *payitgo.Error; once the 10 seconds are up, Status 0 (or ctx.Err() if it was waiting to retry)
}
Test and live mode
The key decides the mode. A test key creates and reads test payments
(no coins: you simulate what the customer sends) and
manages the test webhook; a live key does the same for live ones. The key
does not say which it is: the dashboard shows a Test or Live badge next to
it, and client.IsLive(ctx) asks payitgo. Pair each key with the
webhook secret of the same mode. See Test mode.
Errors
payitgo.Error
A request the API refused, or that got no answer, returns a *payitgo.Error,
and so does a call the library refuses before sending it (Status 400):
type Error struct {
Status int `json:"status"` // the HTTP status; 0 when no answer came
Message string `json:"message"` // the API's error message
}
func (e *Error) Error() string // "payitgo: <Message> (HTTP <Status>)", or "payitgo: <Message>" when Status is 0
| Field | Description |
|---|---|
Status |
The HTTP status, or 0 when no answer came (network error or timeout, after the retries) |
Message |
The API's error message, such as minimum payment in USDT_TRC20 is $6.44 right now (network fees). The status text (such as Bad Gateway) when the answer had no message. request failed: <cause> or reading the response: <cause> when Status is 0 |
Read it with errors.As, branch on Status, and log Message (its wording
may change, see Errors and limits):
Status |
Meaning | Retried by the library |
|---|---|---|
0 |
No answer: DNS, connection, TLS or timeout | Yes |
400 |
The request is invalid (the message says which field). Also a call the library refuses without sending it: Payouts.RetrieveByReference with an empty reference (reference is required) |
No |
401 |
missing api key or invalid api key |
No |
403 |
Not allowed, for example a live key while live mode is off, a storefront key changing the account's webhook or reading its events, or a key without payouts making a payout | No |
404 |
No such payment, payout or batch in the key's mode | No |
409 |
Conflicts with the current state, such as changing a payment's coin once it can no longer change, simulating a payment whose simulation is running, or canceling a payout that was sent already | No |
429 |
Over the rate limit | Yes |
500 and other 5xx |
Something failed on payitgo's side | Yes |
_, err := client.Payments.Create(ctx, &payitgo.PaymentParams{OrderID: "ORD-1", Amount: "1", Token: "BTC"})
var perr *payitgo.Error
if errors.As(err, &perr) && perr.Status == http.StatusBadRequest {
log.Printf("payitgo refused: %s", perr.Message) // e.g. an amount under the coin's minimum
} else if err != nil {
return err
}
Two other kinds of error can come back: ctx.Err() (context.Canceled or
context.DeadlineExceeded) when the context ends while the library waits to
retry, and an encoding/json error when a successful answer is not the JSON
the method expects.
payitgo.ErrSignature
ConstructEvent returns an error wrapping
payitgo.ErrSignature when a notification cannot be trusted. Check it with
errors.Is and answer 400. Its text is
payitgo: webhook signature verification failed: <reason>:
| Reason | Cause |
|---|---|
missing or malformed X-Webhook-Signature header |
No header, or no t or v1 in it |
signature does not match |
The body, the timestamp or the secret differ from what payitgo signed |
malformed timestamp |
t is not a whole number of seconds (checked unless the tolerance is 0) |
timestamp outside the tolerance |
t is further than the tolerance (5 minutes) from your clock |
no webhook secret: pass one, or use WithWebhookSecret |
The client method got no secret and the client has no WithWebhookSecret |
event, err := client.Webhooks.ConstructEvent(body, r.Header.Get("X-Webhook-Signature"))
if errors.Is(err, payitgo.ErrSignature) {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
A body that is correctly signed but is not JSON returns an encoding/json
error instead; payitgo never sends one. Answer 400 to any error from
ConstructEvent.
Retries
A request is retried, up to WithMaxRetries times (default 2, so at most 3
attempts), after a network error or timeout, a 429 or a 5xx. It waits
0.5 s before the first retry and 1 s before the second (500 ms × 2ⁿ), or less
if ctx ends first. Other statuses are never retried. When the last attempt
fails, the call returns a *payitgo.Error with that attempt's status (0,
429 or 5xx).
Every call is retried the same way, and each is safe to repeat:
| Call | Repeating it |
|---|---|
Payments.Create |
Returns the order's open payment instead of a second one (safe retries) |
Payments.SelectToken, Checkout.SelectToken |
The coin the payment has already changes nothing: the repeat returns the payment as it is |
Payments.Simulate |
If the first attempt went through, the repeat returns 409 while that simulation runs: read the payment with Get |
Webhooks.Set, Webhooks.Remove |
Changes nothing the second time |
Webhooks.Test |
Queues one more ping |
Payouts.Request |
With a Reference, returns the payment it already names (200): nothing is paid twice. Without one, a repeat adds a second payment |
Payouts.Send |
If the first attempt went through, the requests have left the list: the repeat answers 400 (or sends the requests added since) |
Payouts.Cancel |
Returns the payment canceled already, as it is: nothing is canceled twice, and no second event is sent |
Payouts.Quote |
Prices again; nothing else changes |
PayoutWallets.SimulateTopUp |
Adds the amount again (test wallets only) |
| Reads | Change nothing |
Payments
Payments.Create
POST /v1/payments · API reference
func (s *PaymentsService) Create(ctx context.Context, p *PaymentParams) (*Payment, error)
Creates a payment for one of your orders. With a Token, the payment comes
back with its deposit address, amount, QR payload and a 15-minute deadline.
Without one, it comes back with TokenOptions and the customer (or your page,
with SelectToken) chooses the coin. While the order
has an open payment, creating it again returns that payment.
p must not be nil. Its fields (PaymentParams):
| Field | JSON | Type | Required | Description |
|---|---|---|---|---|
OrderID |
order_id |
string | yes | Your id for the order, 1 to 128 bytes. One open payment per order and mode |
Amount |
amount |
string | yes | The price, in Currency, as a decimal string: "49.90" |
Currency |
currency |
string | no | The ISO 4217 code of the currency the price is in, such as "EUR", "GBP" or "NGN" (any case; any of the 154 currencies GET /currencies lists). Default USD. payitgo converts the price at the rate of the moment, and every figure on the payment is in this currency from then on, in every response and webhook (your currency) |
Token |
token |
string | no | The coin, such as "USDT_TRC20" (from Tokens.List). Empty: the customer chooses |
Tokens |
tokens |
[]string |
no | Without Token: the coins to offer, such as []string{"USDT_TRC20", "USDT_BEP20"}. Default: every coin you accept whose minimum the amount reaches |
Description |
description |
string | no | What the customer pays for, up to 500 bytes |
Metadata |
metadata |
map[string]string |
no | Your own data: up to 20 keys of up to 40 bytes, values of up to 500 |
CustomerEmail |
customer_email |
string | no | The customer's email address |
SuccessURL |
success_url |
string | no | http(s) URL the hosted checkout links to once the payment is confirmed |
CancelURL |
cancel_url |
string | no | http(s) URL the hosted checkout links back to if the payment closes unpaid |
WebhookURL |
webhook_url |
string | no | https:// URL that gets this payment's notifications instead of your account's webhook URL (per-payment URL). Empty: the client's WithWebhookURL, if any |
Simulate |
simulate |
string | no | Test keys only: the outcome to simulate, a payitgo.Outcome… constant. With Token it starts at once; without, once the coin is chosen |
Empty optional fields are left out of the request.
Returns the *Payment: the new one (201) or the order's
open one (200); both look the same. Fields: the payment
object.
Errors *payitgo.Error with Status 400 for an invalid request: a missing
order_id, amount must be > 0, amount is worth less than a cent,
currency must be the ISO 4217 code of a currency (USD, EUR, GBP, NGN…),
a token you do not accept, an amount under the token's minimum
(minimum payment in BTC is 4.50 EUR right now (network fees); $5.00 for
a payment in dollars) or, without a token, under every coin's
(amount is below the minimum of every token on offer), a webhook_url
that is not public https, a simulate with a live key or an unknown
outcome, and the rest of the create errors. 503
(exchange rate unavailable for currency: try again shortly) when no
exchange rate can be had for currency (after the retries).
Also 401, 403, 429, 500 and 0 as for every call.
// The customer pays in a coin you know:
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
OrderID: "ORD-1001",
Amount: "49.90",
Token: "USDT_TRC20",
Description: "2 x Acme T-shirt",
Metadata: map[string]string{"customer_id": "cus_42"},
CustomerEmail: "[email protected]",
SuccessURL: "https://yourdomain.com/thanks",
CancelURL: "https://yourdomain.com/cart",
})
if err != nil {
return err
}
// payment.DepositAddress, payment.CryptoAmount, payment.QRPayload, payment.ExpiresAt
// The customer chooses the coin (on the hosted page, or yours):
open, err := client.Payments.Create(ctx, &payitgo.PaymentParams{OrderID: "ORD-1002", Amount: "25"})
if err != nil {
return err
}
for _, t := range open.TokenOptions {
fmt.Println(t.Token, t.Minimum, t.AmountDue)
}
// This payment's notifications go to its own URL:
_, err = client.Payments.Create(ctx, &payitgo.PaymentParams{
OrderID: "ORD-1003", Amount: "30", Token: "USDT_TRC20",
WebhookURL: "https://api.yourdomain.com/orders/ORD-1003/ipn",
})
// Priced in euros: every figure on the payment is in EUR, in every response and webhook.
priced, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
OrderID: "ORD-1004", Amount: "45.50", Currency: "EUR", Token: "USDT_TRC20",
})
// priced.Currency "EUR", priced.Amount "45.5", priced.CryptoAmount "49.23"
Payments.Get
GET /v1/payments/{id} · API reference
func (s *PaymentsService) Get(ctx context.Context, id string) (*Payment, error)
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
string | yes | The payment's id, or your order_id for the order's open payment (the payment id is tried first). Escaped for the URL by the library |
Returns the *Payment.
Errors *payitgo.Error 404 (payment not found) for an unknown id, a
payment of the other mode, or an order with no open payment. Plus the
common statuses.
byID, err := client.Payments.Get(ctx, "8f3a2c1e9b7d4a6f05e1c2d3")
if err != nil {
return err
}
byOrder, err := client.Payments.Get(ctx, "ORD-1001") // the order's open payment
if err != nil {
return err
}
if byID.Status == payitgo.StatusConfirmed {
fmt.Println("paid at", byID.ConfirmedAt, "order", byOrder.OrderID)
}
Payments.List
GET /v1/payments · API reference
func (s *PaymentsService) List(ctx context.Context, p *ListParams) (*PaymentList, error)
Payments of the key's mode, newest first. p may be nil. Its fields
(ListParams), each left out of the query when it is the zero
value:
| Field | Type | Default | Description |
|---|---|---|---|
Status |
string | all | Only payments in this status: one of the payitgo.Status… constants |
Chain |
string | all | Only payments on this network, such as "tron" |
Token |
string | all | Only payments in this coin, such as "USDT_TRC20" |
StoreID |
string | all | Only payments of this store (ignored for a storefront key, which sees its own) |
Limit |
int | 50 |
Page size, 1 to 200 (above 200 the API uses 50) |
Offset |
int | 0 |
How many to skip |
Returns a *PaymentList: Payments, Total (matches
across all pages), and the Limit and Offset applied.
Errors the common statuses only. An unknown status, chain or token matches nothing.
// Every confirmed payment, page by page:
var confirmed []payitgo.Payment
for offset := 0; ; {
page, err := client.Payments.List(ctx, &payitgo.ListParams{Status: payitgo.StatusConfirmed, Limit: 100, Offset: offset})
if err != nil {
return err
}
confirmed = append(confirmed, page.Payments...)
offset += page.Limit
if offset >= page.Total {
break
}
}
Payments.SelectToken
POST /v1/payments/{id}/token · API reference
func (s *PaymentsService) SelectToken(ctx context.Context, id, token string) (*Payment, error)
Sets the coin of a payment created without one, once the customer picked it on your own page, or changes it: another coin, while nothing has arrived (Changing the coin). The coin it has already changes nothing: the payment comes back as it is.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
string | yes | The payment's id or your order_id |
token |
string | yes | One of the payment's TokenOptions[].Token, such as "USDT_TRC20" |
Returns the whole *Payment, now with DepositAddress,
CryptoAmount, RateLocked, QRPayload and an ExpiresAt 15 minutes away.
Errors *payitgo.Error:
Status |
Message |
Cause |
|---|---|---|
400 |
token is required |
Empty token |
400 |
token is not one of this payment's options |
A coin not in TokenOptions |
400 |
minimum payment in … is $… right now (it is converted on its way to the merchant, and the exchange takes no less) |
The coin needs a bigger payment than this one: it is converted through the exchange on its way to the merchant, which takes no less, and the merchant pays the fees or hides such coins (hide_below_minimum). Offer the other coins |
400 |
this payment can no longer be paid |
The payment has closed, or it is still pending past its ExpiresAt (an hour to choose the coin, then 15 minutes to pay) |
404 |
payment not found |
No such payment in the key's mode |
409 |
the coin for this payment can no longer be changed |
The payment was created with its coin, something arrived, a test payment's simulation is running, or the coin was changed three times already |
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{OrderID: "ORD-1002", Amount: "25"})
if err != nil {
return err
}
// …your page lists payment.TokenOptions, the customer picks one…
chosen, err := client.Payments.SelectToken(ctx, payment.ID, "USDT_BEP20")
if err != nil {
return err
}
fmt.Println(chosen.CryptoAmount, chosen.Token, chosen.DepositAddress, chosen.ExpiresAt)
Payments.Simulate
POST /v1/payments/{id}/simulate · API reference
func (s *PaymentsService) Simulate(ctx context.Context, id, outcome string) (*Payment, error)
Plays an outcome on a test payment: payitgo sends its deposits, status changes and webhooks about 5 seconds apart, as live coins would, with no coins (Test mode). Test keys only.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
string | yes | The payment's id or your order_id |
outcome |
string | yes | A payitgo.Outcome… constant (what each does) |
Returns the whole *Payment, with its Simulation started.
Simulated deposits have Simulated true; their TxID names no transaction on any chain.
Errors *payitgo.Error:
Status |
Message |
Cause |
|---|---|---|
400 |
outcome is required |
Empty outcome |
400 |
simulate must be one of: confirmed, overpaid, … |
An unknown outcome |
400 |
only test payments can be simulated: use a test key |
A live key |
400 |
choose the payment's coin first |
wrong_asset before a coin is chosen. Any other outcome waits for the coin instead (simulation.state requested) |
400 |
this payment is confirmed: only a pending or partially paid payment can be simulated |
The payment is closed or confirming |
400 |
a BTC address only receives BTC: wrong_asset needs a coin on Tron, Ethereum or BNB Smart Chain |
wrong_asset on a coin that has no other |
404 |
payment not found |
No such payment in the key's mode |
409 |
a simulation is already running for this payment |
Wait until its State is done |
payment, err := client.Payments.Simulate(ctx, "ORD-1002", payitgo.OutcomePartiallyPaid)
if err != nil {
return err
}
fmt.Println(payment.Simulation.Outcome, payment.Simulation.State) // partially_paid running
// once it is done, pay the rest:
payment, err = client.Payments.Simulate(ctx, "ORD-1002", payitgo.OutcomeConfirmed)
Tokens
Tokens.List
GET /v1/tokens · API reference
func (s *TokensService) List(ctx context.Context, p *TokenListParams) ([]TokenInfo, error)
The coins your customers can pay with in the key's mode, with today's network
fee and minimum, in Currency (US dollars without one). With an amount, only
the coins a payment of that amount offers (its token_options), each with
AmountDue when you pass the fees on.
| Parameter | Type | Required | Description |
|---|---|---|---|
p |
*TokenListParams |
no | nil for every coin in dollars, &payitgo.TokenListParams{Amount: "49.90"} for the coins of a payment of that amount, &payitgo.TokenListParams{Amount: "45.50", Currency: "EUR"} for them with every figure in euros. Currency is an ISO 4217 code (any case), USD when empty |
Returns a []TokenInfo (the library unwraps the API's
{"currency": "USD", "tokens": […]}).
Errors *payitgo.Error 400 (amount must be > 0) for an amount that is
not a positive number, 400 (currency must be the ISO 4217 code of a currency (USD, EUR, GBP, NGN…))
for a code that is no currency, 503 (exchange rate unavailable for currency: try again shortly)
when its exchange rate cannot be had, and the common statuses.
tokens, err := client.Tokens.List(ctx, &payitgo.TokenListParams{Amount: "49.90"})
if err != nil {
return err
}
for _, t := range tokens {
fmt.Printf("%s on %s: pay $%s, %s\n", t.Token, t.Chain, t.AmountDue, t.FeeNote)
}
Webhooks
The webhook (IPN) of the key's mode: one URL that receives every notification
of that mode, and the secret that signs them
(Webhooks). A test key manages the test
webhook, a live key the live one. A storefront
key can Get and Test it, but not
Set or Remove it.
Webhooks.Get
GET /v1/webhook · API reference
func (s *WebhooksService) Get(ctx context.Context) (*Webhook, error)
Returns the *Webhook: URL ("" when none is set) and
Secret, the signing secret to pass to WithWebhookSecret. It
always succeeds for a valid key.
webhook, err := client.Webhooks.Get(ctx)
if err != nil {
return err
}
fmt.Println(webhook.URL, webhook.Secret)
Webhooks.Set
PUT /v1/webhook · API reference
func (s *WebhooksService) Set(ctx context.Context, url string) (*Webhook, error)
| Parameter | Type | Required | Description |
|---|---|---|---|
url |
string | yes | An absolute https:// URL on a public host that accepts POST |
Returns the *Webhook with its new URL. The secret does not
change. Setting the URL it already has changes nothing.
Errors *payitgo.Error 400 (url is required, url must use https,
url must be an absolute http(s) URL, url host does not resolve,
url must point at a public host, url must point at your own server, not payitgo's), 403 for a storefront key, 500
(could not set the webhook), and the common statuses.
if _, err := client.Webhooks.Set(ctx, "https://api.yourdomain.com/payitgo/ipn"); err != nil {
return err
}
Webhooks.Remove
DELETE /v1/webhook · API reference
func (s *WebhooksService) Remove(ctx context.Context) (*Webhook, error)
Stops posting the mode's notifications to its URL. Payments created with their
own webhook_url still get theirs, and the secret is kept.
Returns the *Webhook with URL "".
Errors 403 for a storefront key, 500 (could not remove the webhook),
and the common statuses.
Webhooks.Test
POST /v1/webhook/test · API reference
func (s *WebhooksService) Test(ctx context.Context) (*WebhookDelivery, error)
Queues a signed ping notification to the mode's URL; it arrives within about
5 seconds.
Returns the *WebhookDelivery, with Status
payitgo.DeliveryPending.
Errors *payitgo.Error 400 (no webhook url is set for this mode: set one first), 500 (could not queue the test), and the
common statuses.
delivery, err := client.Webhooks.Test(ctx)
if err != nil {
return err
}
fmt.Println(delivery.ID, delivery.EventType, delivery.URL) // 6710c3a1f2b4e5d6a7b8c9d0 ping https://…
Webhooks.ConstructEvent
No request · how verification works
func (s *WebhooksService) ConstructEvent(payload []byte, signatureHeader string, secret ...string) (*Event, error)
Verifies a notification with a 5-minute tolerance and returns its event. It
computes the HMAC-SHA256 of t + "." + payload with the secret, compares it
with v1 in constant time (hmac.Equal), checks that t is within 5 minutes
of your clock, and only then parses the body.
| Parameter | Type | Required | Description |
|---|---|---|---|
payload |
[]byte |
yes | The raw request body, exactly as received (io.ReadAll(r.Body)). A body decoded and encoded again will not verify (keep the raw body) |
signatureHeader |
string | yes | r.Header.Get("X-Webhook-Signature") |
secret |
string | no | The signing secret, as payitgo gave it. Default: the client's WithWebhookSecret. A non-empty secret passed here wins |
For another tolerance, use
payitgo.ConstructEventWithTolerance.
Returns the *Event.
Errors an error wrapping payitgo.ErrSignature with
the reason, or an encoding/json error for a signed body that is not JSON.
Answer 400.
event, err := client.Webhooks.ConstructEvent(body, r.Header.Get("X-Webhook-Signature"))
if err != nil {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
if event.Type == payitgo.EventPaymentConfirmed {
p, err := event.Payment()
if err == nil {
fmt.Println(p.OrderID)
}
}
ConstructEvent and ConstructEventWithTolerance
const DefaultTolerance = 5 * time.Minute
func ConstructEvent(payload []byte, signatureHeader, secret string) (*Event, error)
func ConstructEventWithTolerance(payload []byte, signatureHeader, secret string, tolerance time.Duration) (*Event, error)
The same check without a client, for code that has the secret but no API key.
ConstructEvent uses DefaultTolerance. ConstructEventWithTolerance takes
your own; 0 turns the timestamp check off (only for tests with captured
bodies).
event, err := payitgo.ConstructEvent(body, r.Header.Get("X-Webhook-Signature"), os.Getenv("PAYITGO_WEBHOOK_SECRET"))
if err != nil {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
Errors an error wrapping payitgo.ErrSignature with
the reason, or an encoding/json error for a signed body that is not JSON.
Events
Events.List
GET /v1/events · any account key (read-only ones too) ·
API reference
func (s *EventsService) List(ctx context.Context, p *EventListParams) (*EventPage, error)
Every event of the key's mode is kept, sent or not, and listed here oldest
first, each exactly as its notification carried it: replay what your system
missed, from the last event it handled. p may be nil. Its fields
(EventListParams), each left out of the query when it is the
zero value:
| Field | Type | Default | Description |
|---|---|---|---|
Types |
[]string |
all | Only these types, sent comma-separated as type: exact (payitgo.EventPayoutItemSent) or a family ("payout_item.*") |
After |
string | none | An event's ID: only the events after it. Keep the last one you handled |
CreatedAfter |
time.Time |
none | Only the events created after it, sent as RFC 3339 in UTC. Ignored with After |
Limit |
int | 100 |
Page size, 1 to 200 |
Returns an *EventPage: Events, each an Event
that the Event methods (event.PayoutItem(), …) decode as on a webhook, and
HasMore. While HasMore, call again with After set to the last event's
ID. Events of the last 5 seconds are left for the next read, so moving
forward never skips one; ping events are never listed. They have the same
IDs as the notifications, so the ones you handled already are skipped by
your usual check. A key without payouts gets claim links without their URL
and PIN.
Errors *payitgo.Error:
Status |
Message |
Cause |
|---|---|---|
400 |
type must be event types, such as payout_item.sent or payout_item.* |
A type that is not one |
400 |
limit must be 1 to 200 |
Limit over 200 |
400 |
after is not an event of this mode |
An unknown id, or the other mode's |
403 |
a storefront's key cannot read the account's events: use an account key |
A storefront key |
// After an outage: replay the payout events missed since the last one handled.
after := lastEventID(ctx) // your code: the last event ID you handled
for {
page, err := client.Events.List(ctx, &payitgo.EventListParams{Types: []string{"payout_item.*"}, After: after, Limit: 200})
if err != nil {
return err
}
for _, event := range page.Events {
if err := handleEvent(ctx, event); err != nil { // your webhook's code: it skips event IDs it has seen
return err
}
after = event.ID
}
if !page.HasMore {
return nil
}
}
Realtime
Realtime.Listen
socket.io /v1 · any key · API reference
func (s *RealtimeService) Listen(ctx context.Context, l Listener) error
Keeps one connection to payitgo with the client's key and hands l every
change to the key's payments the moment payitgo knows it: a deposit seen,
each confirmation, the final status. Those of the key's mode only, and of its
own store for a storefront key. It
runs until ctx ends and then returns ctx.Err(): call it in its own
goroutine. It never gives up on its own. A dropped or refused connection is
tried again after a pause that grows to a minute, and a drop of up to two
minutes is resumed with every update it missed. Fulfil orders from the
webhooks; use this for what people watch.
Listener's functions are called from Listen's goroutine, one at a time
and in order: return quickly and hand slow work to another goroutine. Any of
them may be nil.
| Field | Type | Called |
|---|---|---|
Payment |
func(*PaymentUpdate) |
With every change. PaymentUpdate.Type is what happened (payment.detecting, payment.confirmations, payment.confirmed…, all of them); PaymentUpdate.Payment is the whole *Payment after it, as Payments.Get returns it |
Connected |
func(resumed bool) |
Each time the connection is up. resumed is false on the first one and after a drop that could not be resumed: then read again (Payments.Get) the payments you follow, since an update may have been missed |
Disconnected |
func(err error) |
When the connection drops or is refused, with why. payitgo's refusals are a *payitgo.RealtimeError |
*payitgo.RealtimeError has Code and Message. Code is "" for a
network error, or payitgo's reason: invalid_key, forbidden (the account
is suspended or not confirmed, or live mode is off), ip_not_allowed (the
key's allowed IPs),
key_revoked, key_changed (its allowed IPs changed: it connects again) or
suspended.
// Push every change to the customer's checkout screen in your app.
ctx, stop := context.WithCancel(context.Background())
defer stop()
go client.Realtime.Listen(ctx, payitgo.Listener{
Payment: func(u *payitgo.PaymentUpdate) {
screens.Push(u.Payment.OrderID, u.Payment) // your code: e.g. your own socket to the browser
},
Connected: func(resumed bool) {
if !resumed {
refreshOpenOrders(ctx) // your code: Payments.Get for the payments on screen
}
},
Disconnected: func(err error) {
var re *payitgo.RealtimeError
if errors.As(err, &re) && re.Code == "key_revoked" {
alertOps("the payitgo key was revoked") // your code
}
},
})
Checkout
These two calls use the public checkout API:
they are sent without your API key and are keyed by the payment's
checkout_token. They return the payer's view of a payment. On your
server you rarely need them: Payments.Get and Payments.SelectToken return
more. The client still needs a valid key to be created.
Checkout.Get
GET /checkout/{checkout_token} · API reference
func (s *CheckoutService) Get(ctx context.Context, checkoutToken string) (*Payment, error)
| Parameter | Type | Required | Description |
|---|---|---|---|
checkoutToken |
string | yes | The payment's CheckoutToken |
Returns a *Payment without your private fields:
MerchantID, Metadata, CustomerEmail, WebhookURL, CheckoutToken and
CheckoutURL are empty. Reading it from your server does not count as the customer opening the
checkout page.
Errors *payitgo.Error 404 (payment not found), 0 and 5xx.
Checkout.SelectToken
POST /checkout/{checkout_token}/token · API reference
func (s *CheckoutService) SelectToken(ctx context.Context, checkoutToken, token string) (*Payment, error)
| Parameter | Type | Required | Description |
|---|---|---|---|
checkoutToken |
string | yes | The payment's CheckoutToken |
token |
string | yes | One of the payment's TokenOptions[].Token |
Returns the payer's view of the *Payment with its coin,
address, amount and a 15-minute deadline.
Errors the same as Payments.SelectToken, and
429 (rate limit exceeded) when choices come too fast from one visitor.
view, err := client.Checkout.Get(ctx, "b28d4f61e9a03c75d2e8f1a6")
if err != nil {
return err
}
if view.Token == "" {
chosen, err := client.Checkout.SelectToken(ctx, "b28d4f61e9a03c75d2e8f1a6", "USDT_TRC20")
if err != nil {
return err
}
fmt.Println(chosen.DepositAddress)
}
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
(Mass payouts). Each payment is in one of the payout coins
(USDT_TRC20, USDT_BEP20, BTC, …); amounts are decimal strings in the coin.
A payment can also be a claim link, whose recipient chooses the
coin and address, or be converted on its way into a coin
your wallet does not hold.
Reading (Retrieve, RetrieveByReference, Payouts.List, Inbox,
PayoutBatches.Retrieve, PayoutWallets.List) works with any key. Everything else needs a key with
payouts turned on in the dashboard
(Payout keys): any other key gets a
403 (this api key cannot make payouts: turn payouts on for it in the dashboard). The key decides the mode: a test key works with test batches and
the test wallet, on paper, and every id of the other mode is a 404.
There are two ways to pay:
- Payout requests, one by one. Your system sends each client's payout
request as it comes in (
Payouts.Request). payitgo checks and prices it at once and keeps it in your open list with its costs; you send the list when you choose (Payouts.Send), or it goes by itself (auto-send, in your payout settings). Sending moves the valid requests into a batch of their own (Payout requests). - Batches. A whole list at once (payroll, prizes), made in the dashboard
under Pay people, typed, pasted or uploaded as a CSV file. Read one with
PayoutBatches.Retrieve.
Either way, a submitted batch waits for its approvals (when your
payout settings ask for them), then for
the wallet to hold what it needs (why it waits),
and is sent: each payment gets its TxID and a webhook.
// A client asks for a withdrawal: checked and priced into your open list.
item, err := client.Payouts.Request(ctx, &payitgo.PayoutParams{
Reference: "WD-7731", // your id for it: the same reference again returns this payment
Asset: "USDT_TRC20",
Address: "TR7mNkucnhLZoJQLLJ6DR88jpLQufWxUJi",
Amount: "120",
Name: "Ana Silva",
})
if err != nil {
return err
}
if item.Status == payitgo.PayoutItemInvalid {
return fmt.Errorf("refused: %s", item.Errors[0].Message) // kept in the list, never sent
}
// Later (or from a schedule): top up what the list needs, then send it.
inbox, err := client.Payouts.Inbox(ctx, nil)
if err != nil {
return err
}
for _, c := range inbox.Coverage {
if c.TopUp != "0" {
log.Printf("send %s %s to %s", c.TopUp, c.Asset, c.Address)
}
}
batch, err := client.Payouts.Send(ctx) // every valid request
if err != nil {
return err
}
fmt.Println(batch.ID, batch.Status) // e.g. 6a1f3c8e2d9b4a7051c3e8f2 processing
Every write is safe to repeat: a payout request with a Reference
returns the payment that reference already names (200 instead of
201, and the library returns it the same way), so retry after a timeout with
the same reference (references and retries).
Payouts.Request
POST /v1/payouts · a key with payouts on ·
API reference
func (s *PayoutsService) Request(ctx context.Context, p *PayoutParams) (*PayoutItem, error)
Adds one of your clients' payout requests to your open list, checked and priced
at once. p must not be nil. Its fields (PayoutParams):
| Field | JSON | Type | Required | Description |
|---|---|---|---|---|
Reference |
reference |
string | no, but send one | Your id for the payment (a withdrawal request's), unique in its mode. A reference another payment carries returns that payment |
Asset |
asset |
string | yes | A payout coin, such as "USDT_TRC20" or "BTC" (any case) |
Address |
address |
string | yes, unless a claim link | The recipient's address on the coin's network. Left out for a claim link |
Amount |
amount |
string | yes | How much of the coin, as a decimal string: "120". When the recipient pays the fees, they come out of it |
Tag |
tag |
*uint32 |
no | An XRP destination tag; refused for any other coin |
Name, Email, Note |
name, email, note |
string | no | Who it is for, and why: kept with it and shown in the dashboard. A claim link is emailed to Email; otherwise nothing is sent to it |
Claim |
claim |
bool | no | true makes a claim link (no Address), emailed to Email, or without one, its Claim.URL yours to share. Claim links are opt-in: an Email without an Address is refused like any missing address |
ClaimAssets |
claim_assets |
[]string |
no | The other coins a claim link's recipient may choose, paid at the same dollar value (up to 10). Giving them makes the payment a claim link |
WebhookURL |
webhook_url |
string | no | https:// URL on a public host that gets this payment's events, signed with the same secret: it comes before its batch's WebhookURL and your webhook's URL. A request keeps it when it is sent into a batch. The payments of one call may name at most 10 different ones |
Returns the *PayoutItem: PayoutItemReady with its Fee
and Debit (what it takes from the wallet), or PayoutItemInvalid with
Errors saying why (the checks). An
invalid request is kept in the list too, and never sent. The new request
(201) and the one its reference already names (200) look the same.
Errors *payitgo.Error 400 for an unusable WebhookURL (webhook_url: url must use https, webhook_url: url host does not resolve, webhook_url: url must point at a public host, webhook_url: url must point at your own server, not payitgo's) or
for a request the payout wallet cannot pay with those already waiting
(your payout wallet cannot pay this request and those already in your list; send … first, then try again, nothing added; 503 when its balance
cannot be checked just now, to send again), 403 for a key without payouts (or without
the IP limit your payout rules require), 409 (your list of payout requests is full: send or cancel some first), and the common statuses. A
request's own problems are its Errors, never an error. Whether a request in
another coin than the wallet's is converted follows your
payout settings.
item, err := client.Payouts.Request(ctx, &payitgo.PayoutParams{
Reference: "WD-7731", Asset: "USDT_BEP20", Address: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", Amount: "250",
})
if err != nil {
return err
}
for _, w := range item.Warnings {
log.Printf("%s: %s", w.Code, w.Message) // e.g. new_recipient: the payment waits after funding
}
Payouts.Inbox
GET /v1/payouts/inbox · any key · API reference
func (s *PayoutsService) Inbox(ctx context.Context, p *PayoutListParams) (*PayoutInbox, error)
Your open list of payout requests. p may be nil; its Status keeps the
requests in one status or several, comma-separated ("ready",
"ready,invalid"), Limit (1 to 200, default 50) and Offset page them
(PayoutListParams).
Returns a *PayoutInbox: Inbox, the list itself (a
PayoutBatch with Inbox and Open true, its Totals and
Counts); Coverage, what sending its valid requests needs of each coin
(Needed) against what the wallet can spend (Spendable), and the TopUp to
send to Address first; and one page of the requests (Items, Total).
inbox, err := client.Payouts.Inbox(ctx, &payitgo.PayoutListParams{Status: payitgo.PayoutItemReady, Limit: 200})
if err != nil {
return err
}
fmt.Println(inbox.Inbox.Counts.Ready, "ready, worth $"+inbox.Inbox.TotalUSD)
Payouts.Send
POST /v1/payouts/send · a key with payouts on ·
API reference
func (s *PayoutsService) Send(ctx context.Context, ids ...string) (*PayoutBatch, error)
Sends your open payout requests: those of ids, or every valid one when none is
given. They move into a new batch, priced again at today's fees and submitted:
it then waits for its approvals and funds, or starts at once. Invalid requests,
and those not named, stay in the list. Each request sent raises
payout_item.processing (its BatchID is the new batch).
Returns the new *PayoutBatch: PayoutBatchPendingApproval,
PayoutBatchAwaitingFunds (its Waiting says what to send where) or
PayoutBatchProcessing. More than 100 requests are checked in the background:
the batch comes back PayoutBatchValidating and is submitted once quoted. If
the batch cannot be submitted (none of its requests is valid any more at
today's prices, or it is over your limit per batch), the requests go back to
your list, each saying why (payout_item.returned), that batch is canceled
(payout_batch.canceled, CanceledBy payitgo.PayoutCanceledBySystem), and
Send returns the error. A batch priced in the background is canceled the same way, and your
team gets a "Payout requests not sent" notification.
Errors *payitgo.Error:
Status |
Message |
Cause |
|---|---|---|
400 |
no payout request to send · no valid payout request to send |
The list is empty, or holds no valid request |
400 |
payout request … is not a valid request waiting in your list |
One of ids is not a valid request in the list |
400 |
none of the requests is valid any more: they are back in your list, each saying why |
Priced again, none can be paid |
400 |
this batch takes $…, over your limit of $… per batch |
Over your limit per batch: the requests are back in the list |
Repeating a Send that went through sends nothing twice: the requests have left
the list, so it answers 400 (or sends the requests added since).
Payouts.Cancel
DELETE /v1/payouts/{id} · a key with payouts on ·
API reference
func (s *PayoutsService) Cancel(ctx context.Context, id string) (*PayoutItem, error)
Takes a request still in your open list out of it: it is canceled
(CancelReason payitgo.PayoutCancelRemoved), its reference is free again
(ReleasedReference), and its record stays, without a BatchID: Retrieve
keeps answering it. A payment already sent but not on its way yet is canceled
like any payment (payitgo.PayoutCancelCanceled): funded, its money stays in
the wallet and its fee comes back (Fees); not funded yet,
its batch is totalled again, and canceled when nothing is left in it. Either
way payout_item.canceled is sent.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
string | yes | The payment's id. Escaped for the URL by the library |
Returns the *PayoutItem, Status PayoutItemCanceled. A
payment canceled already comes back as it is: safe to retry, and nothing is
canceled or announced twice.
Errors 404 (not found), also for the other mode's payment; 409 (the payment is sent, or failed, expired) once it has ended; and the
common statuses.
item, err := client.Payouts.Cancel(ctx, "4e6a8c0b2d4f6a1c3e5b7d9a")
if err != nil {
return err
}
fmt.Println(item.CancelReason, item.ReleasedReference) // removed WD-7731
Payouts.Retrieve and Payouts.RetrieveByReference
GET /v1/payouts/{id} · GET /v1/payouts?reference= · any key ·
API reference
func (s *PayoutsService) Retrieve(ctx context.Context, id string) (*PayoutItem, error)
func (s *PayoutsService) RetrieveByReference(ctx context.Context, reference string) (*PayoutItem, error)
One payment to a recipient, by its id or by your reference: a payout request,
or a payment of any batch. By reference, the payment that carries it now; if
none does, the latest payment that gave it back (canceled, failed or expired,
with it as ReleasedReference): what became of a request sent with it. Both
are escaped for the URL by the library.
Returns the *PayoutItem. Errors 404 (not found)
for no such payment in the key's mode. An empty reference is refused by the
library without a request: a *payitgo.Error with Status 400 (reference is required), since GET /v1/payouts without one lists payments.
item, err := client.Payouts.RetrieveByReference(ctx, "WD-7731")
if err != nil {
return err
}
if item.Status == payitgo.PayoutItemSent {
fmt.Println("paid:", item.TxID, item.ExplorerURL)
}
Payouts.List
GET /v1/payouts · any key · API reference
func (s *PayoutsService) List(ctx context.Context, p *PayoutPageParams) (*PayoutPage, error)
Every payment of the key's mode, whatever its batch (requests in your list,
removed ones, every batch's), oldest change first: to bring your system
back in sync after it was down, or to check it is. p may be nil. Its fields
(PayoutPageParams), each left out of the query when it is the
zero value:
| Field | Type | Default | Description |
|---|---|---|---|
Status |
[]string |
all | Only payments in these statuses (payitgo.PayoutItem… constants), sent comma-separated. The ended ones: PayoutItemSent, PayoutItemFailed, PayoutItemCanceled, PayoutItemExpired |
UpdatedSince |
time.Time |
none | Only payments changed at or after it, sent as RFC 3339 in UTC: for your first read |
Cursor |
string | none | The NextCursor of the page before: the payments changed after the last one it listed |
Limit |
int | 50 |
Page size, 1 to 200 |
Returns a *PayoutPage: Items, HasMore and
NextCursor. Read with UpdatedSince the first time, then with Cursor set
to NextCursor while HasMore; when HasMore is false, keep NextCursor
and call again later with it to get what changed since. An empty page has no
NextCursor: keep the one you passed. Changes of the last 5 seconds are left
for the next read, so a cursor never skips one.
Errors *payitgo.Error 400 (limit must be 1 to 200, cursor is not one this API gave), and the common statuses.
cursor := loadCursor(ctx) // your code: "" the first time
for {
p := &payitgo.PayoutPageParams{Cursor: cursor, Limit: 200}
if cursor == "" {
p.UpdatedSince = time.Now().AddDate(0, -1, 0)
}
page, err := client.Payouts.List(ctx, p)
if err != nil {
return err
}
for _, item := range page.Items {
syncWithdrawal(ctx, item) // your code: act on item.Status, if item.UpdatedAt is newer than yours
}
if page.NextCursor != "" {
cursor = page.NextCursor
saveCursor(ctx, cursor)
}
if !page.HasMore {
return nil
}
}
Payouts.Quote
POST /v1/payout-quotes · a key with payouts on ·
API reference
func (s *PayoutsService) Quote(ctx context.Context, p *PayoutQuoteParams) (*PayoutQuote, error)
What up to 100 payments would cost, checked and priced exactly as in a batch,
without keeping anything: show a client their fee before they ask for a payout.
p.FeePaidBy is payitgo.FeePaidByMerchant (fees on top) or
payitgo.FeePaidByRecipient (out of each amount); empty takes your payout
settings' default. p.Convert is payitgo.PayoutSameNetwork (each payment
from the wallet's own coin) or payitgo.PayoutConvert (every payment not in
p.ConvertFrom paid from it, converted on its way),
and empty takes your payout settings' default. p.ConvertFrom is the coin
the wallet pays converted payments from, such as "USDT_TRC20". p.Items
are PayoutParams.
Returns a *PayoutQuote: Quote (the totals a batch of
them would have, with its Convert and ConvertFrom) and Items, each payment with its fees and issues, with no id
or times.
Errors 400 (quote between 1 and 100 payments, fee_paid_by must be merchant or recipient, convert must be same_network or convert,
convert_from: payouts are not paid from …), 403, and the
common statuses.
q, err := client.Payouts.Quote(ctx, &payitgo.PayoutQuoteParams{
FeePaidBy: payitgo.FeePaidByRecipient,
Items: []payitgo.PayoutParams{{Asset: "USDT_BEP20", Address: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", Amount: "120"}},
})
if err != nil {
return err
}
fmt.Println(q.Items[0].Fee, q.Items[0].SendAmount) // 0.61183421 119.38816579
PayoutBatches.Retrieve
GET /v1/payout-batches/{id} · any key · API reference
func (s *PayoutBatchesService) Retrieve(ctx context.Context, id string) (*PayoutBatch, error)
A batch by its id, whether made in the dashboard or by
Payouts.Send.
Returns the *PayoutBatch. Errors 404 (not found),
also for a batch of the other mode.
PayoutWallets.List
GET /v1/payout-wallets · any key · API reference
func (s *PayoutWalletsService) List(ctx context.Context) ([]PayoutWallet, error)
Your payout wallet of the key's mode: one PayoutWallet per
network (Chain "tron", "bsc", "ethereum", …), each with its Address to top up and,
per coin, its Balance, Reserved, Spendable and Needed (what batches
waiting for funds need beyond Spendable: the top-up to send). It is made the
first time it is asked for, and never changes. Send it only its network's payout
coins (the payout wallet).
wallets, err := client.PayoutWallets.List(ctx)
if err != nil {
return err
}
for _, w := range wallets {
for _, a := range w.Assets {
fmt.Printf("%s on %s: %s spendable, send %s to %s\n", a.Asset, w.Network, a.Spendable, a.Needed, w.Address)
}
}
Withdrawals back to your own payout addresses are made in the dashboard, by the owner (Withdrawals): an API key never sends the wallet's money anywhere but to your recipients.
PayoutWallets.SimulateTopUp
POST /v1/payout-wallets/{asset}/simulate-top-up · a test key with payouts on ·
API reference
func (s *PayoutWalletsService) SimulateTopUp(ctx context.Context, asset, amount string) ([]PayoutWallet, error)
Adds amount (a decimal string over 0, up to 10,000,000) of asset to the test
wallet's paper balance, and funds any test batch waiting for it. Test payments
are then "sent" on paper within seconds: each gets a made-up TxID (on no
chain, with no ExplorerURL), and the webhooks are sent as live.
Returns the test wallets. Errors 400 (only a test wallet is topped up on paper: use a test key, payouts in … are not available yet, amount must be over 0 and at most 10000000), 403.
test, err := payitgo.NewClient(os.Getenv("PAYITGO_TEST_KEY"))
if err != nil {
return err
}
if _, err := test.PayoutWallets.SimulateTopUp(ctx, "USDT_TRC20", "1000"); err != nil {
return err
}
Claim links
Claim links pay someone whose address you do not
have. Leave Address out of a PayoutParams (a payout
request, a batch item or a quote item) and set Claim (giving ClaimAssets
does too). With an Email, the link is emailed there; 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 the
link, chooses the coin (Asset, or one of ClaimAssets, paid at the same
dollar value) and their address, and the payment goes. 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: "[email protected]", // the link is emailed there
ClaimAssets: []string{"USDT_BEP20", "BTC"}, // the other coins they may choose
})
if err != nil {
return err
}
fmt.Println(item.Claim.URL) // the link: yours to share when there is no email, with Claim.PIN
Read item.Claim (PayoutClaim):
| Field | Description |
|---|---|
URL |
The link |
PIN, PINLocked |
A link without an email: the 6 digits its recipient enters to claim it. Give it another way than the link (a call, a text message), so the link alone pays no one. PINLocked after 5 wrong PINs, until a new PIN is made in the dashboard |
Email, Emailed, LastEmailAt |
Where the link is emailed, how often it was, and when last |
Assets |
The other coins the recipient may choose |
ExpiresAt |
Set when its batch is funded: the payment is PayoutItemClaimable until then, and PayoutItemExpired after (never claimed, its money free again in the wallet); Extended counts how often it was pushed back |
ClaimedAt |
When the recipient claimed it: the payment's Asset, Address and amounts are then what they chose |
FundedAsset, FundedAmount |
When they chose another coin: what it was funded with |
Its events are payout_item.claimed and payout_item.claim_expired. Emailing a
link again and extending it are done in the dashboard. A claim link with an
address, or with an email that is not one, is invalid (invalid_address,
invalid_email).
Converted payments
Converted payments pay a coin your wallet does not
hold. With Convert set to payitgo.PayoutConvert and ConvertFrom (a coin
the wallet holds) on Payouts.Quote, every payment in
another coin is paid from ConvertFrom, converted on its way
(claim links aside). Payout requests follow your payout
settings.
q, err := client.Payouts.Quote(ctx, &payitgo.PayoutQuoteParams{
Convert: payitgo.PayoutConvert, ConvertFrom: "USDT_TRC20",
Items: []payitgo.PayoutParams{{Asset: "BTC", Address: "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", Amount: "0.01"}},
})
if err != nil {
return err
}
if c := q.Items[0].Convert; c != nil {
fmt.Println(c.To, c.Estimate, q.Items[0].Asset, q.Items[0].Debit) // BTC, about what arrives, USDT_TRC20, what the wallet gives
}
A converted payment's Asset, Chain, Amount, Fee (converting included)
and Debit are in the wallet's coin (ConvertFrom). Its Address is the
recipient's on the network of the coin they receive. Read item.Convert (PayoutConversion):
| Field | Description |
|---|---|
To, Ticker, Network |
The coin the recipient receives |
ToAmount |
What you asked to pay, in To |
Estimate |
About what arrives, at the rate when it was priced |
AmountOut |
What arrived, once it is sent |
A batch with converted payments holds its prices for 15 minutes instead of an
hour. A coin that cannot be paid from ConvertFrom makes the payment invalid
(conversion_unavailable).
Payout webhooks
Each step of a batch and of each payment raises a notification, signed like
every other with the secret of its mode
(Webhooks). A payment's events go to its own
WebhookURL (a payout request's or a batch row's), else to its batch's
WebhookURL, else to your webhook's URL; a batch's events go to its
WebhookURL, else to your webhook's URL. Withdrawals and schedules always go
to the webhook's URL. Decode Data with the Event methods:
| Event | Constant | Data |
|---|---|---|
payout_batch.quoted · .pending_approval · .approved · .rejected · .awaiting_funds · .processing · .completed · .canceled |
EventPayoutBatch… |
event.PayoutBatch() |
payout_item.processing · .returned · .sent · .failed · .canceled · .claimed · .claim_expired |
EventPayoutItem… |
event.PayoutItem() |
payout_wallet.withdrawn · .withdrawal_failed |
EventPayoutWalletWithdrawn, EventPayoutWalletWithdrawalFailed |
event.PayoutWithdrawal(): with FailReason when it failed (its money stays in the wallet) |
payout_schedule.run |
EventPayoutScheduleRun |
event.PayoutSchedule(): the schedule, with LastBatchID (the batch it made) or LastError |
payout_schedule.funding_needed |
EventPayoutScheduleFundingNeeded |
event.PayoutScheduleFunding(): the schedule, and the Shortfall to send before its next run |
payout_item.processing says a payout request left your list for a batch of
its own (BatchID is the new batch); payout_item.returned that it came back
to your list, because its batch could not be submitted or it was no longer
valid when priced again (Status PayoutItemInvalid, Errors say why): not
final. payout_item.canceled is sent for every canceled payment, whatever
canceled it, with CancelReason (a payitgo.PayoutCancel… constant),
CanceledBy, CanceledAt, and CancelNote for a rejection.
payout_batch.canceled is also sent when payitgo cancels a batch itself
(CanceledBy payitgo.PayoutCanceledBySystem).
Schedules are set up in the dashboard; their batches
(Source "schedule") then raise the batch and payment events above.
switch event.Type {
case payitgo.EventPayoutItemSent:
item, err := event.PayoutItem()
if err == nil {
err = markWithdrawalPaid(ctx, item.Reference, item.TxID) // idempotent
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError) // payitgo retries
return
}
case payitgo.EventPayoutItemFailed, payitgo.EventPayoutItemCanceled:
item, _ := event.PayoutItem() // item.FailReason, or item.CancelReason; the money stays in your wallet
reopenWithdrawal(ctx, item.ReleasedReference) // never sent: its reference was given back
case payitgo.EventPayoutBatchAwaitingFunds:
batch, _ := event.PayoutBatch() // batch.Waiting: what it waits for, and the Shortfall to send
alertFinance(ctx, batch)
}
Staying in sync
Every payment, a payout request or a batch row, ends PayoutItemSent,
PayoutItemFailed, PayoutItemCanceled or PayoutItemExpired, whoever acted
on it (your system, your team in the dashboard, or payitgo), and each end
raises one event: payout_item.sent, .failed, .canceled or
.claim_expired. Each event is delivered at least once and keeps its ID
however often it is sent: deduplicate on event.ID. Events can arrive in any
order: act on the payment's Status and its latest UpdatedAt, never on the
order they arrive in. To replay events your system missed, call
client.Events.List with After set to the last event ID you
handled; to resync the payments themselves, call
client.Payouts.List and keep its NextCursor
(Staying in sync).
Types
Amounts are decimal strings ("49.9"): parse them with a decimal package, not
float64. Times are time.Time, optional times *time.Time. Optional fields
the API leaves out are the zero value ("", false, nil).
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"` // a Status… constant
Livemode bool `json:"livemode"`
Simulation *Simulation `json:"simulation,omitempty"` // a test payment's simulated outcome
Token string `json:"token"` // "" until the coin is chosen
Chain string `json:"chain"` // "" until the coin is chosen
TokenOptions []TokenInfo `json:"token_options,omitempty"` // while the coin can be chosen or changed
PreviousCoins []PreviousCoin `json:"previous_coins,omitempty"` // coins chosen before Token: Token, Chain, DepositAddress, DestinationTag, CryptoAmount, RateLocked
DepositAddress string `json:"deposit_address"`
DestinationTag *uint32 `json:"destination_tag,omitempty"` // XRP only
CryptoAmount string `json:"crypto_amount"` // what the customer sends, in the coin
CryptoReceived string `json:"crypto_received"` // what arrived, in the coin
Confirmations int64 `json:"confirmations"` // the latest deposit's, out of ConfirmationsRequired: "12 of 20" while detecting
ConfirmationsRequired int64 `json:"confirmations_required"` // what makes a deposit final on the payment's network
DetectedAt *time.Time `json:"detected_at,omitempty"` // when the first deposit was seen
Currency string `json:"currency"` // what the payment is priced in: an ISO 4217 code ("USD" unless you gave one), or a payment link's coin
Amount string `json:"amount"` // the price, in Currency
AmountDue string `json:"amount_due"` // what the customer pays, in Currency: the price, plus the fees when you pass them on
AmountReceived string `json:"amount_received"` // what arrived so far, in Currency
AmountExtra string `json:"amount_extra,omitempty"` // what of AmountDue only reaches the exchange's minimum: you receive it
FeesPaidByCustomer bool `json:"fees_paid_by_customer"`
Settlement string `json:"settlement"` // "custodial" or "direct"
RateLocked string `json:"rate_locked"` // the coin's price in Currency, locked when the coin was chosen
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"`
}
Statuses (lifecycle):
const (
StatusPending = "pending"
StatusPartiallyPaid = "partially_paid"
StatusDetecting = "detecting"
StatusConfirmed = "confirmed" // the only one that means you have been paid
StatusUnderpaid = "underpaid"
StatusExpired = "expired"
StatusFailed = "failed"
)
Simulation
A test payment's simulated outcome. nil
when it has none.
type Simulation struct {
Outcome string `json:"outcome"` // an Outcome… constant
State string `json:"state"` // a Simulation… constant
}
const (
OutcomeConfirmed = "confirmed"
OutcomeOverpaid = "overpaid"
OutcomePartiallyPaid = "partially_paid"
OutcomeUnderpaid = "underpaid"
OutcomeExpired = "expired"
OutcomeFailed = "failed"
OutcomeWrongAsset = "wrong_asset"
OutcomePaidLate = "paid_late"
OutcomePaidTwice = "paid_twice"
SimulationRequested = "requested" // asked for on create, waiting for the coin
SimulationRunning = "running"
SimulationDone = "done"
)
Deposit
One transfer to the payment's address (the deposit object).
type Deposit struct {
TxID string `json:"tx_id"`
Token string `json:"token"` // the asset that arrived
Chain string `json:"chain"`
Amount string `json:"amount"`
Value string `json:"value"` // its worth in the payment's currency
Counted bool `json:"counted"` // counts toward the payment
Late bool `json:"late,omitempty"` // arrived after the payment had closed
Status string `json:"status"` // "pending", "confirmed" or "failed"
SeenAt time.Time `json:"seen_at"`
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
From string `json:"from,omitempty"` // the sender, when the network reports it: where a refund would go
To string `json:"to,omitempty"` // the address it was sent to: the payment's, or a previous coin's
Block int64 `json:"block,omitempty"` // the block (XRP: the ledger) that holds it
MadeAt *time.Time `json:"made_at,omitempty"` // that block's time
FailedAt *time.Time `json:"failed_at,omitempty"` // when it failed
FailReason string `json:"fail_reason,omitempty"` // "transaction not found on chain" or "confirmation timeout"
Simulated bool `json:"simulated,omitempty"` // played by a test payment's simulation: its TxID is on no chain
}
PaymentParams
The parameters of Payments.Create.
type PaymentParams struct {
OrderID string `json:"order_id"`
Amount string `json:"amount"` // the price, in Currency
Currency string `json:"currency,omitempty"` // its ISO 4217 code ("EUR"); "USD" 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"` // test keys only: an Outcome… constant
}
ListParams
The parameters of Payments.List.
type ListParams struct {
Status string
Chain string
Token string
StoreID string // store_id
Limit int
Offset int
}
PaymentList
type PaymentList struct {
Payments []Payment `json:"payments"`
Total int `json:"total"` // matches across all pages
Limit int `json:"limit"` // the page size applied
Offset int `json:"offset"` // the offset applied
}
TokenInfo
A coin the customer can pay with (the TokenInfo object).
type TokenInfo struct {
Token string `json:"token"`
Chain string `json:"chain"`
Minimum string `json:"minimum"` // the smallest amount accepted right now, in the listing's currency like every figure here
NetworkFee string `json:"network_fee"` // the network fee right now
NetworkFeeBps int `json:"network_fee_bps,omitempty"` // for a coin that is converted: the share the network fee adds on top
AmountDue string `json:"amount_due,omitempty"` // with an amount, when you pass the fees on
AmountExtra string `json:"amount_extra,omitempty"` // what of AmountDue only reaches the exchange's minimum: you receive it
FeeNote string `json:"fee_note"`
}
type TokenListParams struct {
Amount string // "" lists every coin
Currency string // the ISO 4217 code the figures are in; "" is USD
}
Webhook
The webhook of the key's mode (the webhook object).
type Webhook struct {
Livemode bool `json:"livemode"`
URL string `json:"url"` // "" when none is set (null in the API)
Secret string `json:"secret"` // signs the mode's notifications
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
WebhookDelivery
One notification on its way to one URL (the delivery object).
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 string `json:"payload"` // the exact body posted
Status string `json:"status"` // a Delivery… constant
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"`
}
type WebhookDeliveryAttempt struct {
At time.Time `json:"at"`
URL string `json:"url,omitempty"`
Signed string `json:"signed,omitempty"` // the t of the attempt's signature
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
Response string `json:"response,omitempty"` // the start of your server's answer
Millis int64 `json:"millis,omitempty"`
Note string `json:"note,omitempty"` // a redelivery or resolution, and by whom
}
const (
DeliveryPending = "pending"
DeliverySending = "sending"
DeliveryDelivered = "delivered"
DeliveryFailed = "failed"
DeliveryResolved = "resolved"
TargetAccount = "account" // the mode's webhook URL
TargetPayment = "payment" // the payment's (or payout batch's) own webhook_url
)
Event
A verified notification (the body), or one replayed by
Events.List.
type Event struct {
ID string `json:"id"` // the same on every retry and replay: deduplicate on it
Type string `json:"type"`
Livemode bool `json:"livemode"`
CreatedAt time.Time `json:"created_at"`
Data json.RawMessage `json:"data"`
}
// Payment decodes Data, for payment.* events.
func (e *Event) Payment() (*Payment, error)
// PayoutBatch, PayoutItem, PayoutWithdrawal, PayoutSchedule and
// PayoutScheduleFunding decode Data, for payout_batch.*, payout_item.*,
// payout_wallet.withdrawn and .withdrawal_failed, payout_schedule.run and
// payout_schedule.funding_needed events.
func (e *Event) PayoutBatch() (*PayoutBatch, error)
func (e *Event) PayoutItem() (*PayoutItem, error)
func (e *Event) PayoutWithdrawal() (*PayoutWithdrawal, error)
func (e *Event) PayoutSchedule() (*PayoutSchedule, error)
func (e *Event) PayoutScheduleFunding() (*PayoutScheduleFunding, error)
Data is the payment for payment.* events (decode it with
event.Payment()), the batch, payment to a
recipient, withdrawal or
schedule for
mass payout events, the
settlement for settlement.*, the
payout for payout.*, and
{"message": "pong"} for ping; decode the others with
json.Unmarshal(event.Data, &yours). The event types:
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"
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"
EventPayoutItemClaimExpired = "payout_item.claim_expired"
EventPayoutWalletWithdrawn = "payout_wallet.withdrawn"
EventPayoutWalletWithdrawalFailed = "payout_wallet.withdrawal_failed" // its money stays in the wallet
EventPayoutScheduleRun = "payout_schedule.run"
EventPayoutScheduleFundingNeeded = "payout_schedule.funding_needed"
)
EventPage
What Events.List returns, and its parameters.
type EventPage struct {
Events []Event `json:"events"` // oldest first, as their webhooks carried them
HasMore bool `json:"has_more"` // more follow: read on with After set to the last event's ID
}
type EventListParams struct {
Types []string // exact types or families ("payout_item.*"), sent comma-separated as type; none: all
After string // an event's ID: the events after it
CreatedAfter time.Time // the events created after it (sent as RFC 3339, UTC); ignored with After
Limit int // 1 to 200 (default 100)
}
PayoutParams
One payment to a recipient: a payout request (Payouts.Request)
or an item of a batch or a quote. Empty optional fields are left out of the
request. With it, the parameters of the other payout calls:
type PayoutParams struct {
Reference string `json:"reference,omitempty"` // your id for it, unique in its mode
Asset string `json:"asset"` // a payout coin: "USDT_TRC20", "BTC", …
Address string `json:"address,omitempty"` // left out for a claim link
Tag *uint32 `json:"tag,omitempty"` // an XRP destination tag
Amount string `json:"amount"` // decimal, in the coin: "120"
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"` // a claim link is emailed there
Note string `json:"note,omitempty"`
Claim bool `json:"claim,omitempty"` // a claim link: no Address, its recipient chooses
ClaimAssets []string `json:"claim_assets,omitempty"` // a claim link's other coins (giving them makes one too)
WebhookURL string `json:"webhook_url,omitempty"` // its events go there, before its batch's WebhookURL and the webhook's URL
}
type PayoutQuoteParams struct { // Payouts.Quote
FeePaidBy string `json:"fee_paid_by,omitempty"` // FeePaidByMerchant or FeePaidByRecipient; "" for your settings' default
Convert string `json:"convert,omitempty"` // PayoutSameNetwork or PayoutConvert; "" for your settings'
ConvertFrom string `json:"convert_from,omitempty"` // with PayoutConvert, the coin converted payments are paid from
Items []PayoutParams `json:"items"` // 1 to 100
}
type PayoutListParams struct { // Payouts.Inbox
Status string // one status, or several comma-separated ("sent,failed")
Limit int // 1 to 200 (default 50)
Offset int
}
const (
FeePaidByMerchant = "merchant" // on top: the recipient receives the whole amount
FeePaidByRecipient = "recipient" // out of each amount
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
)
PayoutItem
One payment to a recipient: a payout request, or a row of a batch
(the payment object). 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 are empty
and the times zero. A request removed from your list has no BatchID; a
canceled payment says why, by whom and when (CancelReason, CanceledBy,
CanceledAt). A claim link has Claim, and no Address
until it is claimed; a converted payment has Convert,
its amounts in the wallet's coin.
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; "" once removed from the list
Reference string `json:"reference,omitempty"` // your id for it
RefusedReference string `json:"refused_reference,omitempty"` // a reference another payment carries: it keeps none, and is invalid
ReleasedReference string `json:"released_reference,omitempty"` // canceled or failed (never sent): its reference, free for a new payment
Row int `json:"row"` // its place in the batch, from 1
Recipient PayoutRecipient `json:"recipient"` // Name, Email, Note
Asset string `json:"asset"` // the coin paid from the wallet
Ticker string `json:"ticker,omitempty"` // "USDT"
IconURL string `json:"icon_url,omitempty"` // an SVG image
Chain string `json:"chain"`
Address string `json:"address"` // as it is sent to (an EVM address checksummed)
Tag *uint32 `json:"tag,omitempty"`
Amount string `json:"amount"` // what you asked to pay
SendAmount string `json:"send_amount"` // what reaches the recipient
Fee string `json:"fee"` // the whole fee, in the coin
Debit string `json:"debit"` // what it takes from the wallet
USDRate string `json:"usd_rate"` // the coin's dollar price when it was priced
AmountUSD string `json:"amount_usd"`
Status string `json:"status"` // a PayoutItem… constant
Errors []PayoutIssue `json:"errors"` // why it is invalid
Warnings []PayoutIssue `json:"warnings"` // worth knowing; it still goes
CoolingUntil *time.Time `json:"cooling_until,omitempty"` // a new recipient's payment waits until then
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"` // PayoutCancelRejected: the approver's reason
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"`
Members map[string]string `json:"members,omitempty"` // the email of the member CanceledBy names, by id
WebhookURL string `json:"webhook_url,omitempty"` // its events go there, before its batch's WebhookURL and the webhook's URL
Claim *PayoutClaim `json:"claim,omitempty"` // a claim link
Convert *PayoutConversion `json:"convert,omitempty"` // a payment converted on its way (its converting part of Fee)
FeeCredit string `json:"fee_credit,omitempty"` // the fee given back for a payment never sent
SentAt *time.Time `json:"sent_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type PayoutRecipient struct {
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
Note string `json:"note,omitempty"`
}
type PayoutIssue struct {
Code string `json:"code"` // an Issue… constant
Field string `json:"field,omitempty"` // asset, amount, address, tag, email, claim_assets or reference
Message string `json:"message"` // for people
Hint string `json:"hint,omitempty"` // what to do
}
type PayoutClaim struct {
Email string `json:"email,omitempty"` // where the link is emailed
Assets []string `json:"assets"` // the other coins its recipient may choose
ExpiresAt *time.Time `json:"expires_at,omitempty"` // set when funded: claimable until then
ClaimedAt *time.Time `json:"claimed_at,omitempty"`
Emailed int `json:"emailed"` // emails sent
LastEmailAt *time.Time `json:"last_email_at,omitempty"`
Extended int `json:"extended"` // how often its end was pushed back
FundedAsset string `json:"funded_asset,omitempty"` // claimed in another coin: what it was funded with…
FundedAmount string `json:"funded_amount,omitempty"` // …and how much
URL string `json:"url,omitempty"` // the link
PIN string `json:"pin,omitempty"` // no email: what the recipient enters, given apart from the link
PINLocked bool `json:"pin_locked,omitempty"` // 5 wrong PINs: locked until a new PIN
}
type PayoutConversion struct {
To string `json:"to"` // the coin the recipient receives
Ticker string `json:"ticker"`
Network string `json:"network"`
ToAmount string `json:"to_amount"` // what you asked to pay, in To
Estimate string `json:"estimate"` // about what arrives
AmountOut string `json:"amount_out,omitempty"` // what arrived, once sent
}
Statuses (the payments):
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 taken out of the open list, before it was sent
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
)
Why a payment was canceled (CancelReason), and who did it when payitgo did
(CanceledBy, also on a batch):
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)
PayoutCanceledBySystem = "system" // CanceledBy when payitgo itself canceled it
)
Issue codes (checking and pricing): an
error leaves its payment out, a warning does not. Codes may be added: treat an
unknown one by the list it is in and show its Message.
const (
IssueUnsupportedAsset = "unsupported_asset" // error
IssueInvalidAmount = "invalid_amount" // error
IssueTooPrecise = "too_precise" // error
IssueInvalidAddress = "invalid_address" // error
IssueWrongNetwork = "wrong_network" // error
IssueOwnWallet = "own_wallet" // error
IssueDuplicateReference = "duplicate_reference" // error
IssueSanctioned = "sanctioned" // error
IssueContractRecipient = "contract_recipient" // error
IssueBelowMinimum = "below_minimum" // error
IssueOverLimit = "over_limit" // error
IssueFeeExceedsAmount = "fee_exceeds_amount" // error
IssueDuplicatePayment = "duplicate_payment" // warning
IssueNewHolder = "new_holder" // warning
IssueActivation = "activation" // warning
IssueCheckFailed = "check_failed" // warning
IssueNewRecipient = "new_recipient" // warning
IssueInvalidEmail = "invalid_email" // error
IssueConversionUnavailable = "conversion_unavailable" // error
)
PayoutBatch
A set of payments checked, priced, approved and funded together
(the batch object). Your open list of payout
requests is one too, with Inbox and Open true: it is never submitted
itself.
type PayoutBatch struct {
ID string `json:"id"`
MerchantID string `json:"merchant_id"`
Livemode bool `json:"livemode"`
Reference string `json:"reference,omitempty"`
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 string `json:"created_by"` // a team member's id, or the API key's (ByAPIKey)
ByAPIKey bool `json:"by_api_key"`
FeePaidBy string `json:"fee_paid_by"` // FeePaidByMerchant or FeePaidByRecipient
Convert string `json:"convert"` // PayoutSameNetwork or PayoutConvert
ConvertFrom string `json:"convert_from,omitempty"` // with PayoutConvert: the coin converted payments are paid from
WebhookURL string `json:"webhook_url,omitempty"` // its events, and its payments' without their own, go there
Status string `json:"status"` // a PayoutBatch… constant
Waiting *PayoutWaiting `json:"waiting,omitempty"` // while it waits
Totals []PayoutAssetTotal `json:"totals"` // its payments that go, per coin
Counts PayoutCounts `json:"counts"` // its payments by status
TotalUSD string `json:"total_usd"` // what it takes from the wallet, in dollars
QuoteExpiresAt *time.Time `json:"quote_expires_at,omitempty"` // its prices hold until then
ApprovalsNeeded int `json:"approvals_needed"`
Approvals []PayoutApproval `json:"approvals"` // UserID, At
Rejection *PayoutDecision `json:"rejection,omitempty"` // By, At, Reason
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"`
}
type PayoutWaiting struct {
Reason string `json:"reason"` // a PayoutWait… constant
Note string `json:"note"` // for people
Since time.Time `json:"since"`
Shortfall []PayoutShortfall `json:"shortfall,omitempty"` // for PayoutWaitFunds: what to send where
}
type PayoutShortfall struct {
Asset string `json:"asset"`
Network string `json:"network"`
Amount string `json:"amount"`
Address string `json:"address"` // your payout wallet's address on Network
}
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"` // how many payments
Amount string `json:"amount"`
SendAmount string `json:"send_amount"`
Fee string `json:"fee"`
Debit string `json:"debit"` // what the wallet gives
DebitUSD string `json:"debit_usd"` // and in dollars
SavedUSD string `json:"saved_usd"` // what sending them together saves in network fees
}
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"` // claim links waiting for their recipients
Expired int `json:"expired"` // claim links never claimed
}
Statuses (a batch's life) and why it waits:
const (
PayoutBatchValidating = "validating" // its payments are being checked and priced
PayoutBatchQuoted = "quoted" // checked and priced: submit it while its prices hold
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)
PayoutWaitFunds = "funds" // send the Shortfall: it starts by itself once the money arrives
PayoutWaitDailyLimit = "daily_limit" // funded from 00:00 UTC
PayoutWaitPaused = "paused" // payitgo paused payouts on your account: contact support
)
PayoutInbox
What Payouts.Inbox returns.
type PayoutInbox struct {
Inbox PayoutBatch `json:"inbox"` // the list: Totals, Counts, TotalUSD
Coverage []PayoutCoverage `json:"coverage"` // per coin: what sending the valid requests needs
Items []PayoutItem `json:"items"` // one page of the requests
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type PayoutCoverage struct {
Asset string `json:"asset"`
Ticker string `json:"ticker"`
Network string `json:"network"`
Needed string `json:"needed"` // the valid requests' debits
Spendable string `json:"spendable"` // what the wallet can spend
TopUp string `json:"top_up"` // what to send to Address first; "0" when covered
Address string `json:"address"`
}
PayoutQuote
What Payouts.Quote returns.
type PayoutQuote struct {
Quote PayoutQuoteTotals `json:"quote"`
Items []PayoutItem `json:"items"` // each with its fees and issues; no ids or times
}
type PayoutQuoteTotals struct {
Livemode bool `json:"livemode"`
FeePaidBy string `json:"fee_paid_by"`
Convert string `json:"convert"` // PayoutSameNetwork or PayoutConvert
ConvertFrom string `json:"convert_from"` // "" without conversion
Totals []PayoutAssetTotal `json:"totals"`
TotalUSD string `json:"total_usd"`
Counts PayoutCounts `json:"counts"`
}
PayoutPage
What Payouts.List returns, and its parameters.
type PayoutPage struct {
Items []PayoutItem `json:"items"` // oldest change first
HasMore bool `json:"has_more"` // more follow: read on from NextCursor
NextCursor string `json:"next_cursor,omitempty"` // the Cursor to read on from; "" for an empty page: keep yours
}
type PayoutPageParams struct {
Status []string // PayoutItem… constants, sent comma-separated; none: all
UpdatedSince time.Time // changed at or after it (sent as RFC 3339, UTC)
Cursor string // the NextCursor of the page before
Limit int // 1 to 200 (default 50)
}
PayoutWallet
Your payout wallet on one network (the wallet object).
type PayoutWallet struct {
Chain string `json:"chain"` // "tron", "bsc", "ethereum", …
Network string `json:"network"` // "Tron", "BNB Smart Chain"
Address string `json:"address"` // where to send that network's payout coins
ExplorerURL string `json:"explorer_url,omitempty"` // live only
Livemode bool `json:"livemode"`
Assets []PayoutWalletAsset `json:"assets"`
Error string `json:"error,omitempty"` // its balances could not be read just now (they are "0")
}
type PayoutWalletAsset struct {
Asset string `json:"asset"`
Ticker string `json:"ticker"`
IconURL string `json:"icon_url"`
Balance string `json:"balance"` // on chain (on paper in test mode)
Reserved string `json:"reserved"` // payments, fees and withdrawals not sent yet
Spendable string `json:"spendable"` // Balance less Reserved
Needed string `json:"needed"` // the top-up batches waiting for funds need
}
PayoutWithdrawal
What payout_wallet.withdrawn and payout_wallet.withdrawal_failed events
carry: a payout wallet's funds sent back to one of your payout addresses
(Withdrawals).
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"` // what left the wallet
Fee string `json:"fee"` // the network's and payitgo's
SendAmount string `json:"send_amount"` // what arrived
AddressID string `json:"address_id"`
Address string `json:"address"`
Tag *uint32 `json:"tag,omitempty"`
Status string `json:"status"` // "requested", "sending", "sent" or "failed"
TxID string `json:"tx_id,omitempty"`
ExplorerURL string `json:"explorer_url,omitempty"`
FailReason string `json:"fail_reason,omitempty"` // why it failed: its money stays in the wallet
RequestedBy string `json:"requested_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
SentAt *time.Time `json:"sent_at,omitempty"`
}
PayoutSchedule
What payout_schedule.* events carry (Schedules):
a batch made again and again, set up in the dashboard, told without its rows
(its recipients stay in the dashboard). Each run makes a batch (Source
"schedule"), submitted when AutoSubmit.
type PayoutSchedule struct {
ID string `json:"id"`
Livemode bool `json:"livemode"`
Name string `json:"name"`
Status string `json:"status"` // "active" or "paused"
Cadence string `json:"cadence"` // "weekly", "biweekly" or "monthly"
Weekday int `json:"weekday"` // weekly and biweekly: 0 (Sunday) to 6
Day int `json:"day"` // monthly: 1 to 28, or -1 for the month's last day
At string `json:"at"` // "09:00"
Timezone string `json:"timezone"` // "Africa/Harare"
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"` // Asset, Ticker, Items, Amount: per coin, each run, fees aside
NextRunAt *time.Time `json:"next_run_at"` // nil when there is none
LastRunAt *time.Time `json:"last_run_at"` // nil before its first run
LastBatchID string `json:"last_batch_id"` // the batch its last run made
LastError string `json:"last_error"` // why its last run made none
Runs int `json:"runs"`
}
type PayoutScheduleFunding struct { // payout_schedule.funding_needed
Schedule PayoutSchedule `json:"schedule"`
Shortfall []PayoutShortfall `json:"shortfall"` // what to send where before its next run
}
Examples
Your own payment page
Show the coins on your own site, create the payment in the coin the customer
picks, and render the amount, address, QR code and deadline from the payment
itself (what to show). net/http and
html/template, with github.com/skip2/go-qrcode
for the QR code:
package main
import (
"encoding/base64"
"errors"
"html/template"
"log"
"net/http"
"os"
"strings"
"github.com/skip2/go-qrcode"
payitgo "github.com/payitgo/go-sdk"
)
var client *payitgo.Client
var networks = map[string]string{
"tron": "Tron (TRC-20)", "ethereum": "Ethereum (ERC-20)", "bsc": "BNB Smart Chain (BEP-20)",
"bitcoin": "Bitcoin", "litecoin": "Litecoin", "dogecoin": "Dogecoin", "xrp": "XRP Ledger",
}
var page = template.Must(template.New("pay").Funcs(template.FuncMap{
"network": func(chain string) string {
if n, ok := networks[chain]; ok {
return n
}
return chain
},
"coin": func(token string) string { return strings.Split(token, "_")[0] },
}).Parse(`
{{if .Tokens}}<form method="post">{{range .Tokens}}
<button name="token" value="{{.Token}}">{{.Token}} on {{network .Chain}}: ${{or .AmountDue $.Total}}</button>
{{end}}</form>{{end}}
{{with .Payment}}
{{if not .Livemode}}<p><b>Test payment:</b> do not send coins to this address.</p>{{end}}
<p>Send exactly <b>{{.CryptoAmount}} {{coin .Token}}</b> on <b>{{network .Chain}}</b> to</p>
<p><code>{{.DepositAddress}}</code></p>
{{if .DestinationTag}}<p>Destination tag (required): <b>{{.DestinationTag}}</b></p>{{end}}
<img src="{{$.QR}}" width="220" height="220" alt="QR code">
<p>Pay before <time datetime="{{.ExpiresAt.Format "2006-01-02T15:04:05Z07:00"}}">{{.ExpiresAt.Format "15:04 MST"}}</time></p>
{{end}}`))
type view struct {
Total string
Tokens []payitgo.TokenInfo
Payment *payitgo.Payment
QR template.URL
}
// GET /pay?order=ORD-1001 lists the coins; POST creates the payment in the chosen one.
func pay(w http.ResponseWriter, r *http.Request) {
order, err := findOrder(r.Context(), r.URL.Query().Get("order")) // your code: ID and Total ("49.90")
if err != nil {
http.NotFound(w, r)
return
}
if r.Method != http.MethodPost {
tokens, err := client.Tokens.List(r.Context(), &payitgo.TokenListParams{Amount: order.Total})
if err != nil {
http.Error(w, "please try again", http.StatusBadGateway)
return
}
page.Execute(w, view{Total: order.Total, Tokens: tokens})
return
}
payment, err := client.Payments.Create(r.Context(), &payitgo.PaymentParams{
OrderID: order.ID, // the same order again returns its open payment
Amount: order.Total,
Token: r.FormValue("token"),
})
var perr *payitgo.Error
if errors.As(err, &perr) {
log.Printf("payitgo %d: %s", perr.Status, perr.Message) // log it; do not show it to the customer
}
if err != nil {
http.Error(w, "We could not start this payment. Please try again.", http.StatusBadGateway)
return
}
renderPayment(w, payment)
}
func renderPayment(w http.ResponseWriter, p *payitgo.Payment) {
png, err := qrcode.Encode(p.QRPayload, qrcode.Medium, 440)
if err != nil {
http.Error(w, "please try again", http.StatusInternalServerError)
return
}
qr := template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(png))
page.Execute(w, view{Payment: p, QR: qr})
}
func main() {
var err error
if client, err = payitgo.NewClient(os.Getenv("PAYITGO_KEY")); err != nil {
log.Fatal(err)
}
http.HandleFunc("/pay", pay)
log.Fatal(http.ListenAndServe(":8080", nil))
}
A payment keeps its coin while it is open: if the customer goes back and picks
another coin, Payments.Create for the same order returns the first payment
unchanged. To let the customer choose on your page after the payment
exists, create it without Token and set the coin with SelectToken:
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{OrderID: order.ID, Amount: order.Total})
if err != nil {
return err
}
// render payment.TokenOptions (each with Token, Chain, Minimum, AmountDue, FeeNote)…
// …and when the customer picks one:
chosen, err := client.Payments.SelectToken(ctx, payment.ID, pickedToken)
if err != nil {
return err
}
renderPayment(w, chosen)
To follow the payment live on the page, connect the page's script to the
socket's default namespace (/) and subscribe with payment.CheckoutToken
(with an acknowledgement): every payment:update then carries the whole
payment (follow it live). No polling.
Fulfil the order from the webhook, never from the page.
A webhook (IPN) handler with net/http
Read the raw body, verify it, handle each event once, and answer 2xx within
10 seconds (answering and retries):
package main
import (
"io"
"log"
"net/http"
"os"
payitgo "github.com/payitgo/go-sdk"
)
var client *payitgo.Client
func ipn(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) // the raw bytes
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
event, err := client.Webhooks.ConstructEvent(body, r.Header.Get("X-Webhook-Signature"))
if err != nil {
w.WriteHeader(http.StatusBadRequest) // not from payitgo, changed, or too old
return
}
ctx := r.Context()
done, err := isProcessed(ctx, event.ID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError) // payitgo retries
return
}
if done {
w.WriteHeader(http.StatusOK) // a retry or redelivery
return
}
live, err := client.IsLive(ctx) // asks payitgo once, then remembers
if err != nil {
w.WriteHeader(http.StatusInternalServerError) // payitgo retries
return
}
if event.Livemode == live { // ignore the other mode's events
switch event.Type {
case payitgo.EventPaymentConfirmed: // final: fulfil
p, err := event.Payment()
if err == nil {
err = markOrderPaid(ctx, p.OrderID, p.ID) // idempotent
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
case payitgo.EventPaymentExpired: // nothing arrived in time
p, err := event.Payment()
if err == nil {
err = releaseOrder(ctx, p.OrderID)
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
if err := markProcessed(ctx, event.ID); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func main() {
var err error
client, err = payitgo.NewClient(os.Getenv("PAYITGO_KEY"),
payitgo.WithWebhookSecret(os.Getenv("PAYITGO_WEBHOOK_SECRET")), // the signing secret of the key's mode
)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/payitgo/ipn", ipn)
log.Fatal(http.ListenAndServe(":8080", nil))
}
isProcessed, markProcessed, markOrderPaid and releaseOrder are your own
code: store processed event ids in a table with a unique key, and make
fulfilment safe to run twice. A 500 makes payitgo retry the notification. More
in handle events safely.
Test mode
Build everything with your test key: the same calls, simulated payments instead of coins, and the test webhook with its own secret (Test mode).
client, err := payitgo.NewClient(os.Getenv("PAYITGO_TEST_KEY")) // your test key
if err != nil {
return err
}
live, err := client.IsLive(ctx)
if err != nil {
return err
}
fmt.Println(live) // false
// Point the TEST webhook at your development server and read its secret.
hook, err := client.Webhooks.Set(ctx, "https://dev.yourdomain.com/payitgo/ipn")
if err != nil {
return err
}
fmt.Println(hook.Secret) // test mode's signing secret: your dev PAYITGO_WEBHOOK_SECRET
// A signed ping arrives within seconds.
if _, err := client.Webhooks.Test(ctx); err != nil {
return err
}
// A test payment that pays itself: payment.detecting, then payment.confirmed,
// arrive at the test webhook within half a minute.
payment, err := client.Payments.Create(ctx, &payitgo.PaymentParams{
OrderID: "TEST-1", Amount: "10", Token: "USDT_TRC20", Simulate: payitgo.OutcomeConfirmed,
})
if err != nil {
return err
}
fmt.Println(payment.Livemode, payment.Simulation.State) // false running
// Another outcome on a payment you already have:
if _, err := client.Payments.Simulate(ctx, "TEST-2", payitgo.OutcomeUnderpaid); err != nil {
return err
}
Never send real coins to a test address: nothing watches it (why).
Check your verification against the example in
the recipe (tolerance 0, because the example is
old):
body := []byte(`{"created_at":"2026-10-10T09:12:44.512837Z","data":{"message":"pong"},"id":"5c0e1f9a2b7d4e3c8a6f1b2d","livemode":false,"type":"ping"}`)
event, err := payitgo.ConstructEventWithTolerance(body,
"t=1791623565,v1=1af0ba31872e3152c422edaf9442c9f0eb4ebd202beebafbaaba14f77336194b",
"a3858862701d1ce11ab06cb5dd9bb941d4849283f81fc0c3f0db0d99a2b82d48",
0,
)
if err != nil {
return err
}
fmt.Println(event.Type) // ping
To test your handler without waiting for a notification, sign a body yourself
and call it with httptest. The handler asks payitgo its key's mode once
(IsLive), so the test gives the client your test key:
func sign(body []byte, secret string, t time.Time) string {
mac := hmac.New(sha256.New, []byte(secret))
fmt.Fprintf(mac, "%d.", t.Unix())
mac.Write(body)
return fmt.Sprintf("t=%d,v1=%s", t.Unix(), hex.EncodeToString(mac.Sum(nil)))
}
func TestIPN(t *testing.T) {
secret := os.Getenv("PAYITGO_WEBHOOK_SECRET")
var err error
client, err = payitgo.NewClient(os.Getenv("PAYITGO_KEY"), payitgo.WithWebhookSecret(secret)) // your test key and its secret
if err != nil {
t.Fatal(err)
}
body := []byte(`{"id":"6710c3a1f2b4e5d6a7b8c9d0","type":"ping","livemode":false,"created_at":"2026-10-10T09:00:00Z","data":{"message":"pong"}}`)
req := httptest.NewRequest(http.MethodPost, "/payitgo/ipn", bytes.NewReader(body))
req.Header.Set("X-Webhook-Signature", sign(body, secret, time.Now()))
rec := httptest.NewRecorder()
ipn(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status %d", rec.Code)
}
}
Going live: put the live key and the live webhook secret in your
production environment, set the live webhook URL with the live key, and keep
the event.Livemode check in your handler (going live).