Go
Call the Pay.com API from Go with typed methods, list iterators, and webhook verification, on the standard library alone.
The Go SDK has a typed method for each API operation, named after its
resource: client.Charges.Create(), client.Holds.Capture(), and
client.ValueLists.Items.Create(). Every method takes a context.Context
first. Fields have Go names, such as TransactionID, with JSON tags for the
API's own.
Requirements and install
You need Go 1.23 or later. The SDK uses the standard library only.
go get github.com/pay-com/pay-com-sdks/goImport github.com/pay-com/pay-com-sdks/go/pay. Create one client and reuse it
across requests. It is safe for concurrent use.
Set your key
Keep the key out of your code. The SDK reads it from PAY_COM_API_KEY:
export PAY_COM_API_KEY='sk-pay-com-sandbox-…'The SDK selects the sandbox or live environment automatically from the key
prefix (sk-pay-com-sandbox- or sk-pay-com-live-). The key is never written
to the SDK's logs or errors.
Create your first charge
Charge a saved payment method. Amounts are integers in minor units (for example,
2000 is $20.00 USD):
package main
import (
"context"
"fmt"
"log"
"github.com/pay-com/pay-com-sdks/go/pay"
)
func main() {
ctx := context.Background()
client, err := pay.NewClient()
if err != nil {
log.Fatal(err)
}
charge, err := client.Charges.Create(ctx, &pay.ChargesCreateParams{
Amount: pay.Int(2000),
Currency: pay.String("usd"),
Source: pay.String("pm_card_685125127054035968"),
Reference: pay.String("order-6735"),
})
if err != nil {
log.Fatal(err)
}
fmt.Println(charge.ID, charge.Status)
}A field you leave nil isn't sent. pay.String, pay.Int, pay.Bool, and
pay.Ptr make the pointers.
The SDK sends a new idempotency key with each POST and DELETE, and the
same one when it retries. To use your own, pass it after the parameters:
client.Charges.Create(ctx, params, pay.WithIdempotencyKey(key)).
It retries twice by default after a network error, a timeout,
409 request_in_progress, 421, 429, 502, 503, or 504. To decide
yourself, pass pay.WithMaxRetries(0), and set a Reference on payments to
help you
find out what was created.
The SDK retries these only after a 429, or when they never left your server:
every PUT and PATCH, WebhookEndpoints.Create(), and
NetworkTokens.RetrieveCryptogram(). If one of these requests receives no
response, check whether it succeeded before sending it again.
When you call PaymentLinks.Update(), pass every field you want to keep,
Amount and Currency included. An update
without amount sets the link's amount to 0.
List every item
A list method returns an iterator over every item on every page, and fetches
each page as you reach it. The same method with Page added to its name,
such as ListPage, gets one page:
package main
import (
"context"
"fmt"
"log"
"github.com/pay-com/pay-com-sdks/go/pay"
)
func main() {
ctx := context.Background()
client, err := pay.NewClient()
if err != nil {
log.Fatal(err)
}
page, err := client.Charges.ListPage(ctx, &pay.ChargesListParams{Limit: pay.Int(10)})
if err != nil {
log.Fatal(err)
}
fmt.Println(len(page.Data), page.HasMore)
for charge, err := range client.Charges.List(ctx, &pay.ChargesListParams{CreatedGreaterThan: pay.String("2026-11-01T00:00:00Z")}) {
if err != nil {
log.Fatal(err)
}
fmt.Println(charge.ID)
}
}Breaking out of the loop stops fetching additional pages. If an error occurs, the iterator yields it as the final item and stops. Lists that use page numbers work the same way.
Catch a decline
A decline is an error of kind pay.ErrPaymentMethod:
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/pay-com/pay-com-sdks/go/pay"
)
func main() {
ctx := context.Background()
client, err := pay.NewClient()
if err != nil {
log.Fatal(err)
}
_, err = client.Charges.Create(ctx, &pay.ChargesCreateParams{
Amount: pay.Int(2000),
Currency: pay.String("usd"),
Source: pay.String("pm_card_685125127054035968"),
})
var perr *pay.Error
switch {
case errors.Is(err, pay.ErrPaymentMethod) && errors.As(err, &perr):
fmt.Println("Declined:", perr.DeclineCode)
case errors.Is(err, pay.ErrInvalidRequest) && errors.As(err, &perr):
fmt.Println("Fix the request:", perr.Code, perr.Message)
case err != nil:
log.Fatal(err)
}
}Every error is a *pay.Error, with Kind, Type, Code, StatusCode, and
the API's response as Body. Include RequestID when contacting Pay.com
support. It is empty when the API didn't get or couldn't read the request. After
retries, Earlier holds an earlier attempt's error. Test the kind with
errors.Is:
| Error kind | Cause |
|---|---|
ErrPaymentMethod | Payment declined by the issuer or blocked by a risk rule (400) |
ErrInvalidRequest | 400 or 422. ErrNotFound, for 404, is one too |
ErrAuthentication | 401 |
ErrPermission | 403 |
ErrIdempotency | An idempotency key in use, or used for another request |
ErrConflict | Any other 409 |
ErrRateLimit | 429 |
ErrAPI | 5xx, a redirect (none is followed), or a response the SDK didn't expect |
ErrConnection | No complete response. ErrTimeout is one too |
ErrUsage | Client-side configuration or usage error detected before sending the request (such as a missing API key) |
If the context cancels a request or its deadline expires, check the error with
errors.Is(err, context.Canceled) or errors.Is(err, context.DeadlineExceeded).
See Handle errors for what to do with each.
Verify a webhook
Pass the raw body, the Pay-Signature header, and the endpoint's whole
signing secret. Cap the body, since anyone can send to your URL. Return HTTP
400 only when ErrSignature is returned. Let other errors return 500 so
Pay.com retries delivery:
package main
import (
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/pay-com/pay-com-sdks/go/pay"
)
func main() {
http.HandleFunc("POST /webhooks", handleWebhook)
log.Fatal(http.ListenAndServe(":3000", nil))
}
func handleWebhook(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 5<<20))
if err != nil {
http.Error(w, "Can't read the body", http.StatusBadRequest)
return
}
event, err := pay.ConstructEvent(body, r.Header.Get(pay.SignatureHeader), os.Getenv("PAY_COM_WEBHOOK_SECRET"))
if errors.Is(err, pay.ErrSignature) {
http.Error(w, "Invalid signature", http.StatusBadRequest)
return
}
if err != nil {
http.Error(w, "Can't check webhooks", http.StatusInternalServerError)
return
}
if event.Type == pay.EventChargeSucceeded {
fmt.Println("Paid:", event.Data.(*pay.Charge).ID)
}
w.WriteHeader(http.StatusOK)
}Skip events whose ID you've
already handled.
event.Data is decoded by the event's type: a *pay.Charge for charge.*
events, and so on. event.RawData is the data as received. In your tests,
pay.GenerateTestHeader(body, secret, time.Time{}) makes a valid header.
Options
Pass these to pay.NewClient().
pay.WithAPIKeystringpay.WithEnvironmentpay.Environmentpay.Sandbox or pay.Live, for a key without either prefix.pay.WithMerchantIDstringpay.WithTimeouttime.Durationpay.WithMaxRetriesintpay.WithBaseURLstringpay.WithHeaderstring, stringpay.WithHTTPClient*http.Clientpay.WithLogLevelslog.Levelpay.WithLogger or slog.Default(). Also read from PAY_COM_LOG.pay.WithMerchantID, pay.WithTimeout, pay.WithMaxRetries,
pay.WithHeader, and pay.WithIdempotencyKey can also be set for one
request, after the method's parameters. The context's deadline bounds the
whole call, retries included. The sandbox's simulate endpoints are under
client.TestHelpers. client.Documents.Upload() takes a pay.Upload with
the file and its content type. See
Upload and download files.