Ruby
The trackified gem. Ruby 3.1+, no runtime dependencies.
The trackified gem uses only the standard library (Net::HTTP). It works in Rails, Sinatra and plain Ruby, and ships RBS type signatures. Source: trackified/trackified-ruby.
Install
gem "trackified"Or run bundle add trackified.
Until it reaches RubyGems
If Bundler can't find the gem yet, take it from GitHub:
gem "trackified", github: "trackified/trackified-ruby", tag: "v0.2.0"Configure
require "trackified"
client = Trackified::Client.new # reads TRACKIFIED_API_KEY and TRACKIFIED_BASE_URLPass options to override the defaults:
client = Trackified::Client.new(
api_key: ENV.fetch("TRACKIFIED_API_KEY"),
base_url: "https://api.trackified.net",
timeout: 30, # seconds, per attempt
max_retries: 2
)The base URL works with or without /v1 at the end.
Check that the API is up. No key is needed for this call:
puts client.health["status"] # "ok"; a 503 raises Trackified::APIErrorResponses are read-only models with a reader for each field (tracking.status). Use model["field"] or model.to_h for anything else the API returns.
Trackings
Create
tracking = client.trackings.create(
tracking_number: "1Z999AA10123456784",
carrier: "ups", # optional: our id or a name like "UPS Ground"; detected when left out
custom_id: "order_1042", # optional: your own reference
customer_email: "ada@example.com" # optional
)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 out and we detect it from the number. If we can't tell, the call raises Trackified::ValidationError with code set to carrier_not_detected.
Get
tracking = client.trackings.get("trk_...")
puts tracking.status, tracking.estimated_delivery
tracking.events.each do |e| # newest first
puts "#{e.occurred_at} #{e.status} #{e.description} #{e.location}"
endList and auto-paginate
# One page
page = client.trackings.list(status: Trackified::TrackingStatus::IN_TRANSIT, limit: 50)
puts "#{page.data.size} of #{page.pagination['total']}"
# Every matching tracking: each walks all later pages
client.trackings.list(status: Trackified::TrackingStatus::DELIVERED).each do |t|
puts "#{t.tracking_number} #{t.delivered_at}"
endA page is Enumerable, so map, select and first(n) work across pages too. Filters: status, carrier, custom_id, tracking_number, plus limit and offset.
Update, stop and retrack
# Change the carrier, custom_id or customer_email. Arguments you leave out stay as they are.
client.trackings.update("trk_...", carrier: "usps")
# Ask for the carrier to be checked again within a minute.
result = client.trackings.retrack("trk_...")
puts result["queued"]
# Stop tracking. The tracking is no longer checked or returned.
client.trackings.delete("trk_...")Bulk create
rows = client.trackings.bulk_create([
{ tracking_number: "1Z999AA10123456784", custom_id: "order_1042" },
{ tracking_number: "9434650110837017316201", carrier: "usps", custom_id: "order_1043" }
])
rows.each do |row|
puts row["ok"] ? row["tracking"].id : row["error"]
endEach row succeeds or fails on its own. Your plan sets the most rows per request. See Rate limits and plans.
Carriers
candidates = client.carriers.detect("1Z999AA10123456784") # best first
puts candidates.first&.carrier, candidates.first&.confidence
# Map a free-text name or another provider's slug to our id. nil if we don't serve it.
match = client.carriers.resolve("FedEx SmartPost")
puts match.carrier, match.confidence, match.matched if match
catalog = client.carriers.catalog(q: "dhl") # the full carrier catalog, as a HashWebhooks
Create an endpoint
webhook = client.webhooks.create(
url: "https://example.com/webhooks/trackified",
event_types: [
Trackified::WebhookEventType::TRACKING_STATUS_CHANGED,
Trackified::WebhookEventType::TRACKING_DELIVERED
]
)
# Store webhook.secret now. It's only returned here.Update, pause and rotate
# Change the URL or events, or pause it. The secret stays the same.
client.webhooks.update(webhook.id, event_types: [Trackified::WebhookEventType::TRACKING_STATUS_CHANGED])
client.webhooks.update(webhook.id, enabled: false)
# New secret, shown once. The old one keeps verifying for 24 hours by default.
rotated = client.webhooks.rotate_secret(webhook.id, expires_in_hours: 24)
puts rotated.secret, rotated["previous_secret_expires_at"]During the window, pass both secrets when you verify (below).
Verify in a Rails controller
request.raw_post is the raw body. ActionController::API has no CSRF check; if your controller inherits from ActionController::Base, add skip_forgery_protection.
class TrackifiedWebhooksController < ActionController::API
def create
event = Trackified::WebhookSignature.construct_event(
request.raw_post,
request.headers["x-tracking-signature"],
ENV.fetch("TRACKIFIED_WEBHOOK_SECRET")
)
if event.status_changed?
Rails.logger.info("#{event.previous_status} -> #{event.current_status}")
end
Rails.logger.info("#{event.type} #{event.tracking.tracking_number}") # the tracking, for any event type
head :ok
rescue Trackified::SignatureVerificationError
head :bad_request
end
endpost "/webhooks/trackified", to: "trackified_webhooks#create"Events and their data
event.data is the raw Hash. event.tracking returns the tracking as a Trackified::Tracking for any type; for tracking.status_changed, event.previous_status and event.current_status give the change. client.webhooks.tracking_of(event) does the same as event.tracking.
Failed carrier checks
A tracking.exception sent because we couldn't reach the carrier carries "tracking_id" and "error", not a tracking, so event.tracking.id is nil for it. Read event.data["tracking_id"] instead. See Webhook events.
Why verification failed
construct_event raises Trackified::SignatureVerificationError with a reason: "missing", "malformed", "timestamp" or "mismatch". verify_detailed returns it without raising; verify returns a boolean:
result = Trackified::WebhookSignature.verify_detailed(raw_body, header, secret)
warn "webhook rejected: #{result.reason}" unless result.valid?All three take one secret or an array of secrets (any may match), and tolerance: in seconds (default 300). Pass both secrets while a rotation is in progress:
event = Trackified::WebhookSignature.construct_event(
raw_body, header, [ENV.fetch("TRACKIFIED_WEBHOOK_SECRET"), ENV.fetch("TRACKIFIED_WEBHOOK_SECRET_OLD")]
)They're also available on client.webhooks.
Errors
begin
client.trackings.create(tracking_number: "ABC123", idempotency_key: "order_1042")
rescue Trackified::ValidationError => e
raise unless e.code == "carrier_not_detected"
# ask the user for the carrier
rescue Trackified::QuotaExceededError
# 402: this month's trackings are used up
rescue Trackified::ConnectionError => e
# "timeout": the outcome is unknown. Retry later with the same idempotency key.
raise unless e.code == "timeout"
rescue Trackified::NotFoundError
# 404
rescue Trackified::RateLimitError => e
warn "retry in #{e.retry_after}s"
rescue Trackified::TrackifiedError => e
warn "#{e.status} #{e.code}: #{e.message} (request #{e.request_id})"
endThe classes are AuthenticationError (401, or no API key), PermissionError (403), NotFoundError (404), ValidationError (400, 422), QuotaExceededError (402), ConflictError (409, including idempotency_in_progress), RateLimitError (429), APIError (5xx and any other status), ConnectionError (no response; code is "timeout" or "connection") and SignatureVerificationError. QuotaExceededError and ConflictError are subclasses of APIError, so 0.1 code that rescued APIError still catches them.
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, pass the same idempotency_key:.
Options
Option | Default | |
|---|---|---|
|
| |
|
| |
|
| Seconds, for opening, reading and writing. |
|
| Retries for network errors, 408, 429 and 5xx. |
| none | Called before each attempt. |
| none | Called after each attempt. |
Request hooks
client = Trackified::Client.new(
on_request: ->(info) { puts "-> #{info[:method]} #{info[:url]} attempt #{info[:attempt]} #{info[:idempotency_key]}" },
on_response: lambda { |info|
puts "<- #{info[:method]} #{info[:url]} #{info[:status] || info[:error]&.code} " \
"#{info[:request_id]} #{info[:duration_ms]}ms replay=#{info[:idempotent_replayed]}"
}
)Each hook gets a Hash and runs once per attempt, so a retried request calls it more than once. attempt is 1 for the first try. status is nil when no response arrived; error is the typed error when the status is 400 or more or the connection failed. A hook that raises is ignored.
trackings.create and trackings.bulk_create take idempotency_key: to replace the generated key. See Pagination, retries and idempotency.