Go
The trackified-go module. Standard library only, Go 1.23+.
github.com/trackified/trackified-go uses only the standard library. Its iterators use range-over-func, so it needs Go 1.23 or later. Source: trackified/trackified-go.
Install
go get github.com/trackified/trackified-go@v0.1.0Configure
import "github.com/trackified/trackified-go"
client, err := trackified.New() // reads TRACKIFIED_API_KEY and TRACKIFIED_BASE_URL
if err != nil {
log.Fatal(err) // no API key configured
}Pass options to override the defaults:
client, err := trackified.New(
trackified.WithAPIKey(os.Getenv("TRACKIFIED_API_KEY")),
trackified.WithBaseURL("https://api.trackified.net"),
trackified.WithTimeout(30*time.Second),
trackified.WithMaxRetries(2),
)The base URL works with or without /v1 at the end. A *trackified.Client is safe for concurrent use. Create one and reuse it. Every call takes a context.Context first.
Check that the API is up. No key is needed for this call:
h, err := client.Health(ctx) // a 503 returns an *APIError
if err != nil {
log.Fatal(err)
}
fmt.Println(h.Status) // "ok"Trackings
Create
t, err := client.Trackings.Create(ctx, &trackified.CreateTrackingParams{
TrackingNumber: "1Z999AA10123456784",
Carrier: "ups", // optional: our id or a name like "UPS Ground"; detected when empty
CustomID: "order_1042", // optional: your own reference
CustomerEmail: "ada@example.com", // optional
})
if err != nil {
log.Fatal(err)
}
fmt.Println(t.ID, t.Status)Carrier takes our carrier id, a carrier or service name ("USPS Priority Mail"), or another provider's slug ("dhl_express"). The tracking stores our id. Leave Carrier empty and we detect it from the number. If we can't tell, the call returns a *trackified.ValidationError with Code set to carrier_not_detected.
Get
t, err := client.Trackings.Get(ctx, "trk_...")
if err != nil {
log.Fatal(err)
}
fmt.Println(t.Status, t.EstimatedDelivery)
for _, e := range t.Events { // newest first
fmt.Println(e.OccurredAt, e.Status, e.Description, e.Location)
}List and auto-paginate
// One page
page, err := client.Trackings.List(ctx, &trackified.TrackingListParams{
ListParams: trackified.ListParams{Limit: 50},
Status: trackified.StatusInTransit,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(len(page.Data), "of", page.Pagination.Total)
// Every matching tracking, fetching pages as needed
for t, err := range client.Trackings.All(ctx, &trackified.TrackingListParams{Status: trackified.StatusDelivered}) {
if err != nil {
log.Fatal(err)
}
fmt.Println(t.TrackingNumber, t.DeliveredAt)
}Filters: Status, Carrier, CustomID, TrackingNumber, plus Limit and Offset in ListParams. Pass nil for no filters.
Prefer an explicit loop? ListAutoPaging returns an iterator with Next, Current and Err:
it := client.Trackings.ListAutoPaging(ctx, nil)
for it.Next() {
fmt.Println(it.Current().ID)
}
if err := it.Err(); err != nil {
log.Fatal(err)
}Update, stop and retrack
// Change the carrier, custom ID or customer email. Empty fields stay as they are.
_, err = client.Trackings.Update(ctx, "trk_...", &trackified.UpdateTrackingParams{Carrier: "usps"})
// Ask for the carrier to be checked again within a minute.
r, err := client.Trackings.Retrack(ctx, "trk_...")
fmt.Println(r.Queued)
// Stop tracking. The tracking is no longer checked or returned.
_, err = client.Trackings.Delete(ctx, "trk_...")Bulk create
res, err := client.Trackings.BulkCreate(ctx, []trackified.CreateTrackingParams{
{TrackingNumber: "1Z999AA10123456784", CustomID: "order_1042"},
{TrackingNumber: "9434650110837017316201", Carrier: "usps", CustomID: "order_1043"},
}, "") // "" generates an idempotency key
if err != nil {
log.Fatal(err)
}
for _, row := range res.Data {
if row.OK {
fmt.Println(row.Tracking.ID)
} else {
fmt.Println(row.Error)
}
}Each row succeeds or fails on its own. Your plan sets the most rows per request. See Rate limits and plans.
Carriers
d, err := client.Carriers.Detect(ctx, "1Z999AA10123456784")
if err != nil {
log.Fatal(err)
}
if len(d.Candidates) > 0 { // best first
fmt.Println(d.Candidates[0].Carrier, d.Candidates[0].Confidence)
}
// Map a free-text name or another provider's slug to our id. nil if we don't serve it.
m, err := client.Carriers.Resolve(ctx, "FedEx SmartPost")
if err == nil && m != nil {
fmt.Println(m.Carrier, m.Confidence, m.Matched)
}
catalog, err := client.Carriers.Catalog(ctx, &trackified.CatalogParams{Query: "dhl"}) // the full carrier catalogWebhooks
Create an endpoint
w, err := client.Webhooks.Create(ctx, &trackified.CreateWebhookParams{
URL: "https://example.com/webhooks/trackified",
EventTypes: []trackified.WebhookEventType{
trackified.EventTypeTrackingStatusChanged,
trackified.EventTypeTrackingDelivered,
},
})
if err != nil {
log.Fatal(err)
}
// Store w.Secret now. It's only returned here.Leave EventTypes empty and you get tracking.updated and tracking.delivered.
Update, pause and rotate
// Change the URL or events, or pause it. The secret stays the same.
_, err = client.Webhooks.Update(ctx, w.ID, &trackified.UpdateWebhookParams{
EventTypes: []trackified.WebhookEventType{trackified.EventTypeTrackingStatusChanged},
})
off := false
_, err = client.Webhooks.Update(ctx, w.ID, &trackified.UpdateWebhookParams{Enabled: &off})
// New secret, shown once. The old one keeps verifying for 24 hours by default.
hours := 24
rotated, err := client.Webhooks.RotateSecret(ctx, w.ID, &trackified.RotateSecretParams{ExpiresInHours: &hours})
if err != nil {
log.Fatal(err)
}
fmt.Println(rotated.Secret, rotated.PreviousSecretExpiresAt)During the window, pass both secrets when you verify (below).
Verify in net/http
Read the raw body with io.ReadAll before anything decodes it.
package main
import (
"io"
"log"
"net/http"
"os"
"github.com/trackified/trackified-go"
)
func main() {
secret := os.Getenv("TRACKIFIED_WEBHOOK_SECRET")
http.HandleFunc("POST /webhooks/trackified", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
event, err := trackified.ConstructEvent(body, r.Header.Get(trackified.SignatureHeader), secret)
if err != nil {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
if event.Type == trackified.EventTypeTrackingStatusChanged {
if sc, err := event.StatusChange(); err == nil {
log.Printf("%s -> %s", sc.PreviousStatus, sc.CurrentStatus)
}
}
if t, err := trackified.TrackingOf(event); err == nil { // the tracking, for any event type
log.Printf("%s %s", event.Type, t.TrackingNumber)
}
w.WriteHeader(http.StatusNoContent)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}Events and their data
event.Data is raw JSON. event.StatusChange() decodes a tracking.status_changed event into PreviousStatus, CurrentStatus and Tracking. trackified.TrackingOf(event) (or event.Tracking()) returns the tracking for any type.
Failed carrier checks
A tracking.exception sent because we couldn't reach the carrier carries {tracking_id, error}, not a tracking. TrackingOf then gives a Tracking with an empty ID. Decode event.Data with json.Unmarshal if you need the error. See Webhook events.
Why verification failed
ConstructEvent returns a *trackified.SignatureVerificationError whose Reason is missing, malformed, timestamp or mismatch (the Reason… constants). It still matches errors.Is(err, trackified.ErrInvalidSignature). VerifyDetailed returns the reason without an error; VerifyWebhook returns a bool:
// body: the raw request body; header: the x-tracking-signature value
res := trackified.VerifyDetailed(body, header, []string{secret})
if !res.Valid {
log.Printf("webhook rejected: %s", res.Reason)
}A header may carry several v1= signatures. While a rotation is in progress, pass both secrets to ConstructEventSecrets (or VerifyDetailed); any match is valid:
event, err := trackified.ConstructEventSecrets(body, header, []string{
os.Getenv("TRACKIFIED_WEBHOOK_SECRET"),
os.Getenv("TRACKIFIED_WEBHOOK_SECRET_OLD"),
})Each takes an optional tolerance as the last argument (default trackified.DefaultTolerance, 5 minutes). They're also on client.Webhooks.
Errors
Every API error unwraps to *trackified.TrackifiedError. Match a kind with errors.As:
_, err := client.Trackings.Create(ctx, &trackified.CreateTrackingParams{TrackingNumber: "ABC123", IdempotencyKey: "order_1042"})
var ve *trackified.ValidationError
var qe *trackified.QuotaExceededError
var ce *trackified.ConnectionError
var nf *trackified.NotFoundError
var rl *trackified.RateLimitError
var te *trackified.TrackifiedError
switch {
case err == nil:
case errors.As(err, &ve) && ve.Code == "carrier_not_detected":
// ask the user for the carrier
case errors.As(err, &qe):
// 402: this month's trackings are used up
case errors.As(err, &ce) && ce.Code == "timeout":
// The outcome is unknown. Retry later with the same IdempotencyKey.
case errors.As(err, &nf):
// 404
case errors.As(err, &rl):
log.Printf("retry in %s", rl.RetryAfter)
case errors.As(err, &te):
log.Printf("%d %s: %s (request %s)", te.StatusCode, te.Code, te.Message, te.RequestID)
default:
log.Fatal(err) // context cancelled, or a decode error
}The types are *AuthenticationError (401), *PermissionError (403), *NotFoundError (404), *ValidationError (400, 422), *QuotaExceededError (402), *ConflictError (409, including idempotency_in_progress), *RateLimitError (429), *APIError (5xx) and *ConnectionError (no response; Code is timeout or connection).
A timeout means the outcome is unknown: the request may have reached us. The library's own retries reuse the idempotency key, so a create is never doubled. If you retry yourself later, set the same IdempotencyKey.
Options
Option | Default | |
|---|---|---|
|
| |
|
| |
| 30s | Sets the timeout on the HTTP client. |
| 2 | Retries for network errors, 408, 429 and 5xx. |
| a new | Replaces the HTTP client. Pass it before |
| Adds your product token, such as | |
| Functions called before and after each attempt. |
Request hooks
client, err := trackified.New(trackified.WithHooks(trackified.Hooks{
OnRequest: func(r trackified.RequestInfo) {
log.Printf("-> %s %s attempt %d %s", r.Method, r.URL, r.Attempt, r.IdempotencyKey)
},
OnResponse: func(r trackified.ResponseInfo) {
log.Printf("<- %s %s %d %s %s replay=%t err=%v", r.Method, r.URL, r.Status, r.RequestID, r.Duration, r.IdempotentReplayed, r.Err)
},
}))Each hook runs once per attempt, so a retried request calls them more than once. Attempt is 1 for the first try. Status is 0 when no response arrived; Err is the typed error when the status is 400 or more or the connection failed. A hook that panics is recovered and ignored.
Set IdempotencyKey on CreateTrackingParams, or pass a key to BulkCreate, to replace the generated key. See Pagination, retries and idempotency.