Documentation
¶
Overview ¶
Package balikobot is a zero-dependency client for the Balíkobot shipping API v2.
The client covers the documented endpoints for carrier branches, packages, labels, tracking, pickup orders and account capabilities. It performs no logging, caching, persistence or automatic retries. Every method maps the provider answer to a small set of sentinel errors, so the caller decides how to react to a retryable outage or a permanent rejection.
Requests use HTTP Basic authentication: Config.User is the API user and Config.APIKey is the API password. All JSON responses are read with a hard byte limit and every request carries the caller's context.
Index ¶
- Constants
- Variables
- func ResolveBranchID(carrierCode carrier.Code, service, branchID, branchZip string) string
- type ActivatedServices
- type AddPackageRequest
- type AddPackageResult
- type Branch
- type CODCapability
- type Carrier
- type Client
- func (client *Client) ActivatedServices(ctx context.Context, carrierCode carrier.Code) (ActivatedServices, error)
- func (client *Client) AddPackage(ctx context.Context, carrierCode carrier.Code, request AddPackageRequest) (AddPackageResult, error)
- func (client *Client) Branches(ctx context.Context, carrierCode carrier.Code, service string, ...) ([]Branch, error)
- func (client *Client) COD(ctx context.Context, carrierCode carrier.Code) ([]ServiceCOD, error)
- func (client *Client) CarrierCapabilities(ctx context.Context, carrierScope ...[]carrier.Code) ([]Carrier, error)
- func (client *Client) Close()
- func (client *Client) Countries(ctx context.Context, carrierCode carrier.Code) ([]ServiceCountries, error)
- func (client *Client) DownloadLabel(ctx context.Context, labelURL string) ([]byte, string, error)
- func (client *Client) DropPackage(ctx context.Context, carrierCode carrier.Code, packageID string) error
- func (client *Client) Labels(ctx context.Context, carrierCode carrier.Code, packageID string) (string, error)
- func (client *Client) OrderBatch(ctx context.Context, carrierCode carrier.Code, packageID string) (OrderResult, error)
- func (client *Client) OrderPickup(ctx context.Context, carrierCode carrier.Code, request PickupRequest) (PickupResult, error)
- func (client *Client) OrderViewLabels(ctx context.Context, carrierCode carrier.Code, orderID string, ...) (string, error)
- func (client *Client) Overview(ctx context.Context, carrierCode carrier.Code, matchEID string) ([]OverviewPackage, error)
- func (client *Client) TrackStatus(ctx context.Context, carrierCode carrier.Code, carrierID string) (TrackStatusResult, error)
- func (client *Client) WhoAmI(ctx context.Context) (WhoAmI, error)
- type Config
- type OrderResult
- type OverviewPackage
- type PickupRequest
- type PickupResult
- type Service
- type ServiceCOD
- type ServiceCountries
- type TrackStatusResult
- type TransientError
- type WhoAmI
- type WhoAmICarrier
Constants ¶
const ( // DefaultBaseURL is the production Balíkobot API v2 endpoint. DefaultBaseURL = "https://apiv2.balikobot.cz" // DefaultTimeout is the request timeout used when Config.Timeout is zero. DefaultTimeout = 30 * time.Second // DefaultMaxResponseBytes is the JSON response size limit used when // Config.MaxResponseBytes is zero. DefaultMaxResponseBytes = 8 << 20 )
Variables ¶
var ( // that the request never left the client. A retry can succeed. A // TransientError wraps this sentinel when the provider sent a retry hint. ErrUnavailable = errors.New("balikobot: temporarily unavailable") // ErrNotFound reports a documented "no data yet" answer, currently the // missing tracking data of a package the carrier has not scanned yet. ErrNotFound = errors.New("balikobot: resource not found") // ErrInvalidResponse reports a provider answer that violates the protocol, // for example a broken body, a missing status or a foreign label URL. ErrInvalidResponse = errors.New("balikobot: invalid provider response") // ErrInvalidRequest reports arguments rejected locally before any network // call, for example an invalid carrier code or a missing recipient field. ErrInvalidRequest = errors.New("balikobot: invalid request") // ErrRejected reports a permanent refusal of the request or of the // supplied data. Retrying the same request cannot succeed. ErrRejected = errors.New("balikobot: provider permanently rejected the request") // ErrAmbiguous reports that a mutating call may have reached the provider. // Reconcile the result by external reference before any retry. ErrAmbiguous = errors.New("balikobot: request outcome is unknown") )
Functions ¶
func ResolveBranchID ¶
ResolveBranchID derives the branch_id that ADD expects from a stored branch of a carrier. Česká pošta and Slovenská pošta use the branch ZIP without spaces, the Uloženka CP_NP service does the same, PPL strips the KM prefix, and every other carrier uses the stored branch id unchanged.
Types ¶
type ActivatedServices ¶
type ActivatedServices struct {
// ActiveParcel is the provider flag that marks active parcel shipping.
// It is nil when the provider omits the flag.
ActiveParcel *bool
// Services lists the activated services. The Countries and COD fields are
// empty; use CarrierCapabilities for the combined discovery.
Services []Service
}
ActivatedServices is the ACTIVATEDSERVICES answer of one carrier.
type AddPackageRequest ¶
type AddPackageRequest struct {
// EID is the external package reference. It must contain 8 to 40
// alphanumeric or dash characters.
EID string `json:"eid"`
// ServiceType is the carrier service code, for example "1" or "VMCZ".
ServiceType string `json:"service_type"`
// RecName is the recipient name. RecName or RecFirm must be set.
RecName string `json:"rec_name,omitempty"`
// RecFirm is the recipient company. RecName or RecFirm must be set.
RecFirm string `json:"rec_firm,omitempty"`
// RecStreet is the recipient street. It is required.
RecStreet string `json:"rec_street"`
// RecCity is the recipient city. It is required.
RecCity string `json:"rec_city"`
// RecZip is the recipient postal code. It is required.
RecZip string `json:"rec_zip"`
// RecCountry is the ISO 3166-1 alpha-2 destination country. It is
// required.
RecCountry country.Code `json:"rec_country"`
// RecPhone is the recipient phone. RecPhone or RecEmail must be set.
RecPhone string `json:"rec_phone,omitempty"`
// RecEmail is the recipient email. RecPhone or RecEmail must be set.
RecEmail string `json:"rec_email,omitempty"`
// BranchID is the pickup branch reference for branch delivery.
BranchID string `json:"branch_id,omitempty"`
// WeightKG is the package weight in kilograms. It must be positive and at
// most 10000.
WeightKG float64 `json:"weight"`
// LengthCM is the package length in centimeters. It must be positive and
// at most 1000.
LengthCM float64 `json:"length"`
// WidthCM is the package width in centimeters. It must be positive and at
// most 1000.
WidthCM float64 `json:"width"`
// HeightCM is the package height in centimeters. It must be positive and
// at most 1000.
HeightCM float64 `json:"height"`
// Price is the declared value in the currency of CODCurrency. It must not
// be negative and at most 100000000.
Price float64 `json:"price"`
// CODPrice is the cash-on-delivery amount. It must not be negative and at
// most 100000000. A positive amount requires VS.
CODPrice float64 `json:"cod_price,omitzero"`
// CODCurrency is the cash-on-delivery currency. Balíkobot carriers
// validate this field even without a COD amount, so "CZK" or "EUR" is
// required on every ADD.
CODCurrency currency.Code `json:"cod_currency,omitempty"`
// VS is the cash-on-delivery variable symbol. It must be set exactly when
// CODPrice is positive and must be below 10000000000.
VS *int64 `json:"vs,omitempty"`
}
AddPackageRequest is one package for the ADD method. The external reference EID makes ADD idempotent: a repeated request with an already stored EID returns the original record.
type AddPackageResult ¶
type AddPackageResult struct {
// PackageID is the Balíkobot package reference used by labels, ORDER and
// DROP.
PackageID string
// CarrierID is the carrier tracking number.
CarrierID string
// LabelURL is the provider label URL for this package.
LabelURL string
}
AddPackageResult is the accepted package record returned by ADD.
type Branch ¶
type Branch struct {
// ID is the branch identifier used by the carrier.
ID string `json:"ID"`
// Type is the provider branch type, for example "branch" or "box".
Type string `json:"Type"`
// Name is the display name. It falls back to Zip when the provider sends
// no name.
Name string `json:"Name"`
// Street is the street part of the address.
Street string `json:"Street"`
// City is the city part of the address.
City string `json:"City"`
// Zip is the postal code.
Zip string `json:"Zip"`
// Country is the ISO 3166-1 alpha-2 country code. It can be empty when
// the provider omits it for a domestic branch.
Country country.Code `json:"Country"`
// Latitude is the GPS latitude when the provider sent a valid pair.
Latitude *float64 `json:"Latitude"`
// Longitude is the GPS longitude when the provider sent a valid pair.
Longitude *float64 `json:"Longitude"`
}
Branch describes one carrier branch or pickup point.
type CODCapability ¶
type CODCapability struct {
// Country is the ISO 3166-1 alpha-2 destination country.
Country country.Code `json:"Country"`
// Currency is the three-letter currency code.
Currency currency.Code `json:"Currency"`
// MaxAmountMinor is the maximum cash-on-delivery amount in minor units,
// for example 149995 for 1499.95 CZK.
MaxAmountMinor int64 `json:"MaxAmountMinor"`
}
CODCapability is one cash-on-delivery destination of a service.
type Carrier ¶
type Carrier struct {
// CarrierCode is the carrier code used in request paths.
CarrierCode carrier.Code `json:"CarrierCode"`
// Services lists the activated services of the carrier.
Services []Service `json:"Services"`
}
Carrier aggregates the discovered services of one contracted carrier.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a Balíkobot API v2 client. Create it with New. Every method is safe for concurrent use except Close, which must not run concurrently with other calls.
func New ¶
New validates the configuration and returns a client. The user name and the API key must not be empty, and BaseURL must be an absolute URL. The https scheme is mandatory unless the host is a loopback address, which supports local test servers.
func (*Client) ActivatedServices ¶
func (client *Client) ActivatedServices(ctx context.Context, carrierCode carrier.Code) (ActivatedServices, error)
ActivatedServices calls the ACTIVATEDSERVICES method of one carrier and returns the normalized activated services. When the provider reports that parcel shipping is inactive, the service list is empty.
func (*Client) AddPackage ¶
func (client *Client) AddPackage( ctx context.Context, carrierCode carrier.Code, request AddPackageRequest, ) (AddPackageResult, error)
AddPackage calls the ADD method with one package. ADD is idempotent on EID: a repeated request with an already stored EID returns status 208 together with the original record, which maps to a successful result.
func (*Client) Branches ¶
func (client *Client) Branches( ctx context.Context, carrierCode carrier.Code, service string, countryCode country.Code, ) ([]Branch, error)
Branches calls the BRANCHES method and returns the branches of one carrier service in one country. The route depends on the carrier: the selected carriers use the combined service and country segments, Zásilkovna uses the country-only route, and the remaining carriers use the service-only route with a client-side country filter.
func (*Client) COD ¶
COD calls the COD4SERVICES method of one carrier and returns the normalized cash-on-delivery destinations per service. Every country sent by the provider is kept. A carrier without the optional dictionary returns an empty list.
func (*Client) CarrierCapabilities ¶
func (client *Client) CarrierCapabilities( ctx context.Context, carrierScope ...[]carrier.Code, ) ([]Carrier, error)
CarrierCapabilities discovers the contracted carriers and their activated services in one run. Without an argument it discovers every carrier of the account; an explicit empty scope discovers none. At most one scope slice may be passed, and every requested carrier must belong to the account. The returned destinations are restricted to EU countries, matching the reference integration.
func (*Client) Close ¶
func (client *Client) Close()
Close releases the idle connections created by the client. It does nothing for a caller-owned Config.HTTPClient. Repeated calls are safe.
func (*Client) Countries ¶
func (client *Client) Countries(ctx context.Context, carrierCode carrier.Code) ([]ServiceCountries, error)
Countries calls the COUNTRIES4SERVICE method of one carrier and returns the supported destination countries per service. Every country sent by the provider is kept.
func (*Client) DownloadLabel ¶
func (client *Client) DownloadLabel( ctx context.Context, labelURL string, ) ([]byte, string, error)
DownloadLabel fetches a provider label URL server-to-server. The body is read once with a hard byte limit and validated against the declared label media type. The URL host must pass the client label allowlist. The returned body is a copy owned by the caller.
func (*Client) DropPackage ¶
func (client *Client) DropPackage( ctx context.Context, carrierCode carrier.Code, packageID string, ) error
DropPackage calls the DROP method for one package that has not entered ORDER. A body status 404 means that the package is already gone and the call succeeds. A body status 405 marks a package that was already handed to the batch and maps to ErrRejected. An ambiguous DROP answer must be reconciled through Overview before any retry.
func (*Client) Labels ¶
func (client *Client) Labels( ctx context.Context, carrierCode carrier.Code, packageID string, ) (string, error)
Labels asks for a fresh aggregate label URL of one package that has not entered ORDER yet.
func (*Client) OrderBatch ¶
func (client *Client) OrderBatch( ctx context.Context, carrierCode carrier.Code, packageID string, ) (OrderResult, error)
OrderBatch calls the ORDER method, which hands one package over to the carrier batch. ORDER is idempotent on package_ids: a repeated closure of the same dataset returns status 208 with the original order id, so an idempotent retry after an ambiguous answer replays the original record instead of closing the package twice.
func (*Client) OrderPickup ¶
func (client *Client) OrderPickup( ctx context.Context, carrierCode carrier.Code, request PickupRequest, ) (PickupResult, error)
OrderPickup calls the ORDERPICKUP method and books one physical collection, separately from the shipment data handover performed by ORDER. The call performs exactly one HTTP attempt. DPD and DPDCZ take the collection address from the carrier configuration; PPL also defaults its contact information to that configuration.
func (*Client) OrderViewLabels ¶
func (client *Client) OrderViewLabels( ctx context.Context, carrierCode carrier.Code, orderID string, packageID string, ) (string, error)
OrderViewLabels retrieves the label URL of an already closed ORDER. The returned URL is accepted only when the response confirms both the requested order id and the membership of the requested package id.
func (*Client) Overview ¶
func (client *Client) Overview( ctx context.Context, carrierCode carrier.Code, matchEID string, ) ([]OverviewPackage, error)
Overview calls the OVERVIEW method, which lists the packages of a carrier that have not yet been closed by ORDER. matchEID names the single entry whose integrity is required for reconciliation: a malformed entry with a different EID is skipped, while a malformed matching entry fails the call.
func (*Client) TrackStatus ¶
func (client *Client) TrackStatus( ctx context.Context, carrierCode carrier.Code, carrierID string, ) (TrackStatusResult, error)
TrackStatus calls the TRACKSTATUS method for one carrier tracking number and returns the raw provider status. The documented response wraps per-package entries in a packages array. A package entry or HTTP answer with status 404 means that the carrier has no tracking data yet and maps to ErrNotFound. The call is read-only, so transport failures are safe to retry.
type Config ¶
type Config struct {
// BaseURL is the API root, for example "https://apiv2.balikobot.cz". The
// default is DefaultBaseURL. Only the loopback host of a test server may
// use the http scheme.
BaseURL string
// User is the API user. It must not be empty.
User string
// APIKey is the API key used as the HTTP Basic password. It must not be
// empty.
APIKey string
// HTTPClient is an optional caller-owned HTTP client. The client clones
// it, applies Timeout and refuses redirects. Close does not close the
// idle connections of a caller-owned client.
HTTPClient *http.Client
// Timeout is the whole-request timeout. Zero selects DefaultTimeout.
Timeout time.Duration
// MaxResponseBytes is the hard byte limit for a JSON response body. Zero
// selects DefaultMaxResponseBytes. Label downloads use a fixed 4 MiB
// limit.
MaxResponseBytes int
// LabelHosts optionally restricts label downloads to these hosts. A
// leading dot selects a suffix match, so ".balikobot.cz" covers every
// subdomain while "pdf.balikobot.cz" matches one host. When empty, the
// client allows the Balíkobot label hosts, or only the BaseURL origin
// when BaseURL is a loopback test server.
LabelHosts []string
// LiveAccount optionally enables account-mode verification before every
// mutating call. When set, the client first calls WHOAMI and requires the
// live_account flag to equal this value. A failed check blocks the write
// before it is sent. When nil, no account-mode check is performed.
LiveAccount *bool
}
Config configures a Client.
type OrderResult ¶
type OrderResult struct {
// OrderID is the provider batch identifier.
OrderID string
}
OrderResult is the batch reference returned by ORDER.
type OverviewPackage ¶
type OverviewPackage struct {
// EID is the external package reference stored by the provider.
EID string
// PackageID is the Balíkobot package reference.
PackageID string
// CarrierID is the carrier tracking number.
CarrierID string
// LabelURL is the provider label URL for this package.
LabelURL string
}
OverviewPackage is one open package entry returned by OVERVIEW.
type PickupRequest ¶
type PickupRequest struct {
// Date is the collection date in the canonical "2006-01-02" format.
Date string
// WeightKG is the total collection weight in kilograms. It must be
// positive and at most 100000. DPD and DPDCZ send it; PPL takes the
// weight from its carrier configuration.
WeightKG float64
// PackageCount is the number of packages. It must be positive and at most
// 10000. DPD and DPDCZ send it; PPL takes it from its carrier
// configuration.
PackageCount int
// Note is the optional collection note. It must contain at most 255 valid
// characters without line breaks. DPD and DPDCZ send it as "message";
// PPL sends it as "note".
Note string
}
PickupRequest is one physical collection booking for ORDERPICKUP.
type PickupResult ¶
type PickupResult struct {
// ProviderID is the provider pickup reference. PPL returns it; DPD and
// DPDCZ leave it empty.
ProviderID string
// Confirmed reports the provider confirmation. DPD and DPDCZ always
// confirm on success.
Confirmed bool
}
PickupResult is the confirmed collection booking.
type Service ¶
type Service struct {
// Code is the provider service code.
Code string `json:"Code"`
// Name is the provider service name.
Name string `json:"Name"`
// HomeDelivery reports home delivery support. Nil means that the
// provider did not declare the flag.
HomeDelivery *bool `json:"HomeDelivery"`
// BoxDelivery reports box delivery support. Nil means that the provider
// did not declare the flag.
BoxDelivery *bool `json:"BoxDelivery"`
// PickupPointsDelivery reports pickup point delivery support. Nil means
// that the provider did not declare the flag.
PickupPointsDelivery *bool `json:"PickupPointsDelivery"`
// Countries maps the destination country codes supported by the service.
// CarrierCapabilities keeps only EU destinations, matching the reference
// integration.
Countries map[country.Code]bool `json:"Countries"`
// COD lists the supported cash-on-delivery destinations. The combined
// discovery leaves it empty because it does not request the optional COD
// dictionary.
COD []CODCapability `json:"COD"`
}
Service describes one activated carrier service.
type ServiceCOD ¶
type ServiceCOD struct {
// ServiceType is the provider service code.
ServiceType string
// Countries lists the normalized cash-on-delivery destinations.
Countries []CODCapability
}
ServiceCOD is one entry of the COD4SERVICES answer.
type ServiceCountries ¶
type ServiceCountries struct {
// ServiceType is the provider service code.
ServiceType string
// Countries lists the destination country codes exactly as sent, with
// surrounding whitespace trimmed and letters upper-cased.
Countries []country.Code
}
ServiceCountries is one entry of the COUNTRIES4SERVICE answer.
type TrackStatusResult ¶
type TrackStatusResult struct {
// StatusID is the raw provider status code, for example "1", "1.2" or
// "-1".
StatusID string
// StatusText is the provider status description.
StatusText string
}
TrackStatusResult is the latest provider tracking status of one package.
type TransientError ¶
type TransientError struct {
// RetryAfter is the provider retry hint. A zero value means that the
// provider sent no hint and the caller should apply its own backoff.
RetryAfter time.Duration
}
TransientError reports a retryable provider answer and carries the optional Retry-After hint of the provider. It matches ErrUnavailable with errors.Is.
func (*TransientError) Error ¶
func (err *TransientError) Error() string
Error implements the error interface.
func (*TransientError) Unwrap ¶
func (err *TransientError) Unwrap() error
Unwrap returns ErrUnavailable, so errors.Is(err, ErrUnavailable) is true for every transient provider answer.
type WhoAmI ¶
type WhoAmI struct {
// Status is the top-level provider status.
Status int `json:"Status"`
// LiveAccount reports whether the credentials belong to a live account.
// It is nil when the provider omits the flag.
LiveAccount *bool `json:"LiveAccount"`
// Carriers lists the carriers contracted by the account.
Carriers []WhoAmICarrier `json:"Carriers"`
}
WhoAmI is the account information returned by the WHOAMI method.
type WhoAmICarrier ¶
type WhoAmICarrier struct {
// Slug is the carrier code used in request paths.
Slug carrier.Code `json:"Slug"`
// Name is the carrier display name. It can be empty.
Name string `json:"Name"`
}
WhoAmICarrier is one contracted carrier of the account.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package carrier defines the carrier codes used by the Balíkobot API.
|
Package carrier defines the carrier codes used by the Balíkobot API. |
|
Package country defines ISO 3166-1 alpha-2 country codes used by the Balíkobot API.
|
Package country defines ISO 3166-1 alpha-2 country codes used by the Balíkobot API. |
|
Package currency defines ISO 4217 currency codes used by the Balíkobot API.
|
Package currency defines ISO 4217 currency codes used by the Balíkobot API. |