aftership

package module
v3.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 3, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

README

aftership-sdk-go

GoDoc AfterShip SDKs channel

Introduction

AfterShip provides an API to Track & Notify of shipments from hundreds of couriers worldwide. aftership-sdk-go is a SDK to develop Apps using AfterShip API 2023-10 in golang. All endpoints including couriers, tracking, last checkpoint and notification are supported.

You will need to create an account at AfterShip and obtain an API key first to access AfterShip APIs using aftership-go SDK.

Installation

aftership-sdk-go requires a Go version with Modules support and uses import versioning. So please make sure to initialize a Go module before installing aftership-sdk-go:

go mod init github.com/my/repo
go get github.com/aftership/aftership-sdk-go/v3

Import:

import "github.com/aftership/aftership-sdk-go/v3"

Quick Start

package main

import (
        "context"
        "fmt"

        "github.com/aftership/aftership-sdk-go/v3"
)

func main() {

        client, err := aftership.NewClient(aftership.Config{
                APIKey: "YOUR_API_KEY",
        })

        if err != nil {
                fmt.Println(err)
                return
        }

        // Get couriers
        result, err := client.GetCouriers(context.Background())
        if err != nil {
                fmt.Println(err)
                return
        }

        fmt.Println(result)
}

Test

make test

Table of contents

NewClient(config)

Create AfterShip SDK instance with config

  • config - object of request config
    • APIKey - Required, AfterShip API key
    • AuthenticationType - APIKey / AES
    • APISecret - if AuthenticationType is AES, use aes api secret
    • Endpoint - string, AfterShip endpoint, default 'https://api.aftership.com/tracking/2023-10'
    • UserAagentPrefix - string, prefix of User-Agent in headers, default "aftership-sdk-go"

Example:

AuthenticationType APIKey

client, err := aftership.NewClient(aftership.Config{
    APIKey: "YOUR_API_KEY",
    UserAagentPrefix: "aftership-sdk-go",
})

AuthenticationType AES signature

client, err := aftership.NewClient(aftership.Config{
    APIKey:             "YOUR_API_KEY",
    AuthenticationType: aftership.AES, 
    APISecret:          "YOUR_API_SECRET",
})

Rate Limiter

To understand AfterShip rate limit policy, please see Limit section in https://www.aftership.com/docs/tracking/quickstart/rate-limit

You can get the recent rate limit by client.GetRateLimit(). Initially all value are 0.

import (
    "context"
    "fmt"

    "github.com/aftership/aftership-sdk-go/v3"
)

func main() {
    client, err := aftership.NewClient(aftership.Config{
        APIKey: "YOUR_API_KEY",
    })

    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(client.GetRateLimit())

    // terminal output
    /*
    {
        "reset": 0,
        "limit": 0,
        "remaining": 0,
    }
    */

    // Get couriers
    result, err := client.GetCouriers(context.Background())
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }

    // Rate Limit
    fmt.Println(client.GetRateLimit())

    // terminal output
    /*
    {
        "reset": 1588249242,
        "limit": 10,
        "remaining": 9,
    }
    */
}

In case you exceeded the rate limit, you will receive the 429 Too Many Requests error with the following error message:

{
  "code": 429,
  "type": "TooManyRequests",
  "message": "You have exceeded the API call rate limit. Default limit is 10 requests per second.",
  "path": "/couriers",
  "rate_limit": {
    "rest": 1458463600,
    "limit": 10,
    "remaining": 0
  }
}

Error Handling

There are 3 kinds of error

  • SDK Error
  • Request Error
  • API Error
SDK Error

Throw by the new SDK client

client, err := aftership.NewClient(aftership.Config{
    APIKey: "",
})

if err != nil {
    fmt.Println(err)
    return
}

/*
invalid credentials: API Key must not be empty
*/

Throw by the parameter validation in function

client, err := aftership.NewClient(aftership.Config{
    APIKey: "YOUR_API_KEY",
})

// Get notification
param := aftership.SlugTrackingNumber{
    Slug: "dhl",
}

result, err := client.GetNotification(context.Background(), param)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

/*
slug or tracking number is empty, both of them must be provided
*/
Request Error
client, err := aftership.NewClient(aftership.Config{
    APIKey: "YOUR_API_KEY",
})

// Get couriers
result, err := client.GetCouriers(context.Background())
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)
/*
HTTP request failed: Get https://api.aftership.com/v4/couriers: dial tcp: lookup api.aftership.com: no such host
*/
API Error

Error return by the AfterShip API https://www.aftership.com/docs/tracking/quickstart/request-errors

API Error struct of this SDK contain fields:

  • Code - error code for API Error
  • Type - type of the error
  • Message - detail message of the error
  • Path - URI path when making request
  • RateLimit - Optional - When the API gets 429 Too Many Requests error, the error struct will return the RateLimit information as well.
client, err := aftership.NewClient(aftership.Config{
    APIKey: "INVALID_API_KEY",
})

// Get couriers
result, err := client.GetCouriers(context.Background())
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)
/*
{
  "code": 401,
  "type": "Unauthorized",
  "message": "Invalid API key.",
  "path": "/couriers"
}
*/

Examples

/couriers

Get a list of our supported couriers.

GET /couriers

Return a list of couriers activated at your AfterShip account.

result, err := client.GetCouriers(context.Background())
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

GET /couriers/all

Return a list of all couriers.

result, err := client.GetAllCouriers(context.Background())
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

POST /couriers/detect

Return a list of matched couriers based on tracking number format and selected couriers or a list of couriers.

params := aftership.CourierDetectionParams{
    TrackingNumber: "906587618687",
}

result, err := client.DetectCouriers(context.Background(), params)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)
/trackings

Create trackings, update trackings, and get tracking results.

POST /trackings

Create a tracking.

newTracking := aftership.CreateTrackingParams{
    TrackingNumber: "1234567890",
    Slug:           "dhl",
    Title:          "Title Name",
    SMSes: []string{
        "+18555072509",
        "+18555072501",
    },
    Emails: []string{
        "email@yourdomain.com",
        "another_email@yourdomain.com",
    },
    OrderID: "ID 1234",
    CustomFields: map[string]string{
        "product_name":  "iPhone Case",
        "product_price": "USD19.99",
    },
    Language:                  "en",
    OrderPromisedDeliveryDate: "2019-05-20",
    DeliveryType:              "pickup_at_store",
    PickupLocation:            "Flagship Store",
    PickupNote:                "Reach out to our staffs when you arrive our stores for shipment pickup",
}

result, err := client.CreateTracking(context.Background(), newTracking)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

DELETE /trackings/:slug/:tracking_number

Delete a tracking.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1234567890",
}

result, err := client.DeleteTracking(context.Background(), param)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

GET /trackings

Get tracking results of multiple trackings.

multiParams := aftership.GetTrackingsParams{
    Page:  1,
    Limit: 10,
}

result, err := client.GetTrackings(context.Background(), multiParams)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

GET /trackings/:slug/:tracking_number

Get tracking results of a single tracking.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1588226550",
}

result, err := client.GetTracking(context.Background(), param, aftership.GetTrackingParams{})
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

Pro Tip: You can always use /:id to replace /:slug/:tracking_number.

// GET /trackings/:id
var id TrackingID = "5b7658cec7c33c0e007de3c5"

result, err := client.GetTracking(context.Background(), id, aftership.GetTrackingParams{})
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

PUT /trackings/:slug/:tracking_number

Update a tracking.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1588226550",
}

updateReq := aftership.UpdateTrackingParams{
    Title: "New Title",
}

result, err := client.UpdateTracking(context.Background(), param, updateReq)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

POST /trackings/:slug/:tracking_number/retrack

Retrack an expired tracking. Max 3 times per tracking.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1588226550",
}

result, err := client.RetrackTracking(context.Background(), param)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

POST /trackings/:slug/:tracking_number/mark-as-completed

Mark a tracking as completed. The tracking won't auto update until retrack it.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1588226550",
}

result, err := client.MarkTrackingAsCompleted(context.Background(), param, aftership.TrackingCompletedStatusDelivered)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)
/last_checkpoint

Get tracking information of the last checkpoint of a tracking.

GET /last_checkpoint/:slug/:tracking_number

Return the tracking information of the last checkpoint of a single tracking.

param := aftership.SlugTrackingNumber{
    Slug:           "ups",
    TrackingNumber: "1234567890",
}

result, err := client.GetLastCheckpoint(context.Background(), param, aftership.GetCheckpointParams{})
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)
/notifications

Get, add or remove contacts (sms or email) to be notified when the status of a tracking has changed.

GET /notifications/:slug/:tracking_number

Get contact information for the users to notify when the tracking changes.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1588226550",
}

result, err := client.GetNotification(context.Background(), param)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

POST /notifications/:slug/:tracking_number/add

Add notification receivers to a tracking number.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1588226550",
}

data := notification.Data{
    Notification: notification.Notification{
        Emails: []string{"user1@gmail.com", "user2@gmail.com", "invalid EMail @ Gmail. com"},
        Smses:  []string{"+85291239123", "+85261236123", "Invalid Mobile Phone Number"},
    },
}

result, err := client.AddNotification(context.Background(), param, data)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

POST /notifications/:slug/:tracking_number/remove

Remove notification receivers from a tracking number.

param := aftership.SlugTrackingNumber{
    Slug:           "dhl",
    TrackingNumber: "1588226550",
}

data := notification.Data{
    Notification: notification.Notification{
        Emails: []string{"user1@gmail.com"},
        Smses:  []string{"+85291239123"},
    },
}

result, err := client.RemoveNotification(context.Background(), param, data)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(result)

Migrations

  • Checkpoint.Coordinates change type from []string into []float32
  • Tracking struct add fields
  • remove android field from Tracking struct

Help

If you get stuck, we're here to help. The following are the best ways to get assistance working through your issue:

  • Issue Tracker for questions, feature requests, bug reports and general discussion related to this package. Try searching before you create a new issue.
  • Slack AfterShip SDKs: a Slack community, you can find the maintainers and users of this package in #aftership-sdks.
  • Email us in AfterShip support: support@aftership.com

Contributing

For details on contributing to this repository, see the contributing guide.

Documentation

Overview

Package aftership creates a SDK client for AfterShip API

Index

Examples

Constants

View Source
const (
	HeaderAsSignatureHMAC = "as-signature-hmac-sha256"
)
View Source
const VERSION string = "3.1.0"

VERSION is the version number of this package

Variables

This section is empty.

Functions

func GetCanonicalizedHeaders

func GetCanonicalizedHeaders(headers map[string]string) string

func GetCanonicalizedResource

func GetCanonicalizedResource(rawUrl string) (result string, err error)

func GetHMACSignature

func GetHMACSignature(signString string, secret []byte) string

func GetSignString

func GetSignString(method, body, contentType, date, canonicalizedAmHeaders, canonicalizedResource string) (signature string, err error)

func GetSignature

func GetSignature(authenticationType AuthenticationType, secretKey []byte, asHeaders map[string]string, contentType, uri, method, date, body string) (string, string, error)

func Md5Encode

func Md5Encode(source string) (hashed string, err error)

Types

type APIError

type APIError struct {
	Code    int    `json:"code"`
	Type    string `json:"type"`
	Message string `json:"message"`
	Path    string `json:"path"`
}

APIError is the error in AfterShip API calls

func (*APIError) Error

func (e *APIError) Error() string

Error serializes the error object to JSON and returns it as a string.

type AdditionalField

type AdditionalField struct {
	/**
	 * Account number of the shipper for a specific courier. Required by some couriers, such as dynamic-logistics
	 */
	TrackingAccountNumber string `json:"tracking_account_number,omitempty"`

	/**
	 * Origin Country of the shipment for a specific courier. Required by some couriers, such as dhl
	 */
	TrackingOriginCountry string `json:"tracking_origin_country,omitempty"`

	/**
	 * Destination Country of the shipment for a specific courier. Required by some couriers, such as postnl-3s
	 */
	TrackingDestinationCountry string `json:"tracking_destination_country,omitempty"`

	/**
	 * Key of the shipment for a specific courier. Required by some couriers, such as sic-teliway
	 */
	TrackingKey string `json:"tracking_key,omitempty"`

	/**
	 * The postal code of receiver's address. Required by some couriers, such as deutsch-post
	 */
	TrackingPostalCode string `json:"tracking_postal_code,omitempty"`

	/**
	 * Shipping date in YYYYMMDD format. Required by some couriers, such as deutsch-post
	 */
	TrackingShipDate string `json:"tracking_ship_date,omitempty"`

	/**
	 * Located state of the shipment for a specific courier. Required by some couriers, such as star-track-courier
	 */
	TrackingState string `json:"tracking_state,omitempty"`

	/**
	 * Enter ISO Alpha-3 (three letters) to specify the origin of the shipment (e.g. USA for United States).
	 */
	OriginCountryISO3 string `json:"origin_country_iso3,omitempty"`

	/**
	 * Enter ISO Alpha-3 (three letters) to specify the destination of the shipment (e.g. USA for United States). If you use postal service to send international shipments, AfterShip will automatically get tracking results at destination courier as well.
	 */
	DestinationCountryISO3 string `json:"destination_country_iso3,omitempty"`

	/**
	 * The postal of the recipient’s address.
	 */
	DestinationPostalCode string `json:"destination_postal_code,omitempty"`

	/**
	 * The state of the recipient’s address.
	 * (Example: New York)
	 */
	DestinationState string `json:"destination_state,omitempty"`
}

type Address

type Address struct {
	// The country/region of the origin location from where the package is
	// picked up by the carrier to be delivered to the final destination.
	// Use 3 letters of ISO 3166-1 country/region code.
	Country string `json:"country,omitempty"`

	// State, province, or the equivalent location of the origin address.
	// Either `origin_address.state` or `origin_address.postal_code` is required.
	State string `json:"state,omitempty"`

	// City of the origin address.
	PostalCode string `json:"postal_code,omitempty"`

	// Postal code of the origin address.
	// Either `origin_address.state` or `origin_address.postal_code` is required.
	RawLocation string `json:"raw_location,omitempty"`

	// Raw location of the origin address.
	City string `json:"city,omitempty"`
}

type AuthenticationType

type AuthenticationType int64
const (
	APIKey AuthenticationType = iota
	AES
)

type Checkpoint

type Checkpoint struct {
	Slug           string     `json:"slug,omitempty"`
	CreatedAt      *time.Time `json:"created_at,omitempty"`
	CheckpointTime string     `json:"checkpoint_time,omitempty"`
	City           string     `json:"city,omitempty"`
	Coordinates    []float32  `json:"coordinates,omitempty"`
	CountryISO3    string     `json:"country_iso3,omitempty"`
	CountryName    string     `json:"country_name,omitempty"`
	Message        string     `json:"message,omitempty"`
	State          string     `json:"state,omitempty"`
	Location       string     `json:"location,omitempty"`
	Tag            string     `json:"tag,omitempty"`
	Subtag         string     `json:"subtag,omitempty"`
	SubtagMessage  string     `json:"subtag_message,omitempty"`
	Zip            string     `json:"zip,omitempty"`
	RawTag         string     `json:"raw_tag,omitempty"`
}

Checkpoint represents a checkpoint returned by the Aftership API

type Client

type Client struct {
	// The config of Client SDK
	Config Config
	// contains filtered or unexported fields
}

Client is the client for all AfterShip API calls

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient returns the AfterShip client

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(cli)
Output:

func (*Client) AddNotification

func (client *Client) AddNotification(ctx context.Context, identifier TrackingIdentifier, notification Notification) (Notification, error)

AddNotification adds notifications to a single tracking.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Add notification receivers to a tracking number.
param := aftership.SlugTrackingNumber{
	Slug:           "dhl",
	TrackingNumber: "1588226550",
}

data := aftership.Notification{
	Emails: []string{"user1@gmail.com", "user2@gmail.com", "invalid EMail @ Gmail. com"},
	SMSes:  []string{"+85291239123", "+85261236123", "Invalid Mobile Phone Number"},
}

result, err := cli.AddNotification(context.Background(), param, data)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) BatchPredictEstimatedDeliveryDate

func (client *Client) BatchPredictEstimatedDeliveryDate(ctx context.Context, params []EstimatedDeliveryDate) (EstimatedDeliveryDates, error)

BatchPredictEstimatedDeliveryDate Batch predict the estimated delivery dates

Example
cli, err := NewClient(Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

params := []EstimatedDeliveryDate{
	{
		Slug:            "fedex",
		ServiceTypeName: "FEDEX HOME DELIVERY",
		OriginAddress: &Address{
			Country:     "USA",
			State:       "WA",
			PostalCode:  "98108",
			RawLocation: "Seattle, Washington, 98108, USA, United States",
		},
		DestinationAddress: &Address{
			Country:     "USA",
			State:       "CA",
			PostalCode:  "92019",
			RawLocation: "El Cajon, California, 92019, USA, United States",
		},
		Weight: &Weight{
			Unit:  "kg",
			Value: 11,
		},
		PackageCount: 1,
		PickupTime:   "2021-07-01 15:00:00",
		EstimatedPickup: &EstimatedPickup{
			OrderTime:       "2021-07-01 15:04:05",
			OrderCutoffTime: "20:00:00",
			BusinessDays:    []int64{1, 2, 3, 4, 5, 6, 7},
			OrderProcessingTime: &OrderProcessingTime{
				Unit:  "day",
				Value: 0,
			},
		},
	},
}

list, err := cli.BatchPredictEstimatedDeliveryDate(context.Background(), params)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(list)
Output:

func (*Client) CreateTracking

func (client *Client) CreateTracking(ctx context.Context, params CreateTrackingParams) (Tracking, error)

CreateTracking creates a new tracking

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Create a tracking
trackingNumber := strconv.FormatInt(time.Now().Unix(), 10)
newTracking := aftership.CreateTrackingParams{
	TrackingNumber: trackingNumber,
	Slug:           "dhl",
	Title:          "Title Name",
	SMSes: []string{
		"+18555072509",
		"+18555072501",
	},
	Emails: []string{
		"email@yourdomain.com",
		"another_email@yourdomain.com",
	},
	OrderID: "ID 1234",
	CustomFields: map[string]string{
		"product_name":  "iPhone Case",
		"product_price": "USD19.99",
	},
	Language:                  "en",
	OrderPromisedDeliveryDate: "2019-05-20",
	DeliveryType:              "pickup_at_store",
	PickupLocation:            "Flagship Store",
	PickupNote:                "Reach out to our staffs when you arrive our stores for shipment pickup",
	ShipmentType:              "test_type",
	ShipmentTags:              []string{"test_tag1", "test_tag2"},
}

result, err := cli.CreateTracking(context.Background(), newTracking)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) DeleteTracking

func (client *Client) DeleteTracking(ctx context.Context, identifier TrackingIdentifier) (Tracking, error)

DeleteTracking deletes a tracking.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Delete a tracking
param := aftership.SlugTrackingNumber{
	Slug:           "dhl",
	TrackingNumber: "1234567890",
}

result, err := cli.DeleteTracking(context.Background(), param)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) DetectCouriers

func (client *Client) DetectCouriers(ctx context.Context, params CourierDetectionParams) (CourierList, error)

DetectCouriers returns a list of matched couriers based on tracking number format and selected couriers or a list of couriers.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Detect courier
params := aftership.CourierDetectionParams{
	TrackingNumber: "906587618687",
}

list, err := cli.DetectCouriers(context.Background(), params)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(list)
Output:

func (*Client) GetAllCouriers

func (client *Client) GetAllCouriers(ctx context.Context) (CourierList, error)

GetAllCouriers returns a list of all couriers.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Get all couriers
result, err := cli.GetAllCouriers(context.Background())
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) GetCouriers

func (client *Client) GetCouriers(ctx context.Context) (CourierList, error)

GetCouriers returns a list of couriers activated at your AfterShip account.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Get couriers
result, err := cli.GetCouriers(context.Background())
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) GetLastCheckpoint

func (client *Client) GetLastCheckpoint(ctx context.Context, identifier TrackingIdentifier, params GetCheckpointParams) (LastCheckpoint, error)

GetLastCheckpoint returns the tracking information of the last checkpoint of a single tracking.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Get last checkpopint
param := aftership.SlugTrackingNumber{
	Slug:           "ups",
	TrackingNumber: "1234567890",
}

result, err := cli.GetLastCheckpoint(context.Background(), param, aftership.GetCheckpointParams{})

if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) GetNotification

func (client *Client) GetNotification(ctx context.Context, identifier TrackingIdentifier) (Notification, error)

GetNotification gets contact information for the users to notify when the tracking changes. Please note that only customer receivers will be returned. Any email, sms or webhook that belongs to the Store will not be returned.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Get the notification
param := aftership.SlugTrackingNumber{
	Slug:           "dhl",
	TrackingNumber: "1588226550",
}

result, err := cli.GetNotification(context.Background(), param)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) GetRateLimit

func (client *Client) GetRateLimit() RateLimit

GetRateLimit returns the X-RateLimit value in API response headers

func (*Client) GetTracking

func (client *Client) GetTracking(ctx context.Context, identifier TrackingIdentifier, params GetTrackingParams) (Tracking, error)

GetTracking gets tracking results of a single tracking.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Get tracking results of a single tracking.
param := aftership.SlugTrackingNumber{
	Slug:           "dhl",
	TrackingNumber: "1588226550",
}

result, err := cli.GetTracking(context.Background(), param, aftership.GetTrackingParams{})
if err != nil {
	fmt.Println(err)
} else {
	fmt.Println(result)
}

// Get tracking results of a single tracking by id.
paramID := aftership.TrackingID("rymq9l34ztbvvk9md2ync00r")

result, err = cli.GetTracking(context.Background(), paramID, aftership.GetTrackingParams{
	Fields: "tracking_postal_code,title,order_id,shipment_tags",
})
if err != nil {
	fmt.Println(err)
} else {
	fmt.Println(result)
}
Output:

func (*Client) GetTrackings

func (client *Client) GetTrackings(ctx context.Context, params GetTrackingsParams) (PagedTrackings, error)

GetTrackings gets tracking results of multiple trackings.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Get tracking results of multiple trackings.
multiParams := aftership.GetTrackingsParams{
	Page:  1,
	Limit: 10,
}

multiResults, err := cli.GetTrackings(context.Background(), multiParams)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(multiResults)
Output:

func (*Client) MarkTrackingAsCompleted

func (client *Client) MarkTrackingAsCompleted(ctx context.Context, identifier TrackingIdentifier, status TrackingCompletedStatus) (Tracking, error)

MarkTrackingAsCompleted marks a tracking as completed. The tracking won't auto update until retrack it.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

param := aftership.SlugTrackingNumber{
	Slug:           "USPS",
	TrackingNumber: "1587721393824",
}

result, err := cli.MarkTrackingAsCompleted(context.Background(), param, aftership.TrackingCompletedStatusDelivered)
if err != nil {
	fmt.Println(err)
} else {
	fmt.Println(result)
}
Output:

func (*Client) RemoveNotification

func (client *Client) RemoveNotification(ctx context.Context, identifier TrackingIdentifier, notification Notification) (Notification, error)

RemoveNotification removes notifications from a single tracking.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Remove notification receivers from a tracking number.
param := aftership.SlugTrackingNumber{
	Slug:           "dhl",
	TrackingNumber: "1588226550",
}

data := aftership.Notification{
	Emails: []string{"user2@gmail.com"},
	SMSes:  []string{"+85261236123"},
}

result, err := cli.RemoveNotification(context.Background(), param, data)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

func (*Client) RetrackTracking

func (client *Client) RetrackTracking(ctx context.Context, identifier TrackingIdentifier) (Tracking, error)

RetrackTracking retracks an expired tracking. Max 3 times per tracking.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Retrack an expired tracking.
param := aftership.SlugTrackingNumber{
	Slug:           "dhl",
	TrackingNumber: "1588226550",
}

result, err := cli.RetrackTracking(context.Background(), param)
if err != nil {
	fmt.Println(err)
} else {
	fmt.Println(result)
}
Output:

func (*Client) UpdateTracking

func (client *Client) UpdateTracking(ctx context.Context, identifier TrackingIdentifier, params UpdateTrackingParams) (Tracking, error)

UpdateTracking updates a tracking.

Example
cli, err := aftership.NewClient(aftership.Config{
	APIKey: "YOUR_API_KEY",
})

if err != nil {
	fmt.Println(err)
	return
}

// Update a tracking.
param := aftership.SlugTrackingNumber{
	Slug:           "dhl",
	TrackingNumber: "1588226550",
}

updateReq := aftership.UpdateTrackingParams{
	Title:        "New Title",
	ShipmentType: "test_type2",
}

result, err := cli.UpdateTracking(context.Background(), param, updateReq)
if err != nil {
	fmt.Println(err)
	return
}

fmt.Println(result)
Output:

type Config

type Config struct {
	// APIKey.
	APIKey string

	// Authentication Type
	AuthenticationType AuthenticationType

	// apiSecret
	// if AuthenticationType is RSA, use rsa private key
	// if AuthenticationType is AES, use aes api secret
	APISecret string

	// BaseURL is the base URL of AfterShip API. Defaults to 'https://api.aftership.com/tracking/2023-10'
	BaseURL string

	// UserAgentPrefix is the prefix of User-Agent in headers. Defaults to 'aftership-sdk-go'
	UserAgentPrefix string

	// HTTPClient is the HTTP client to use when making requests. Defaults to http.DefaultClient.
	HTTPClient *http.Client
}

Config is the config of AfterShip SDK client

type Courier

type Courier struct {
	Slug                   string   `json:"slug"`                      // Unique code of courier
	Name                   string   `json:"name"`                      // Name of courier
	Phone                  string   `json:"phone"`                     // Contact phone number of courier
	OtherName              string   `json:"other_name"`                // Other name of courier
	WebURL                 string   `json:"web_url"`                   // Website link of courier
	RequiredFields         []string `json:"required_fields"`           // The extra fields need for tracking, such as `tracking_account_number`, `tracking_postal_code`, `tracking_ship_date`, `tracking_key`, `tracking_destination_country`
	OptionalFields         []string `json:"optional_fields"`           // the extra fields which are optional for tracking. Basically it's the same as required_fields, but the difference is that only some of the tracking numbers require these fields.
	DefaultLanguage        string   `json:"default_language"`          // Default language of tracking results
	SupportedLanguages     []string `json:"supported_languages"`       // Other supported languages
	ServiceFromCountryISO3 []string `json:"service_from_country_iso3"` // Country code (ISO Alpha-3) where the courier provides service
}

Courier is the model describing an AfterShip courier

type CourierDetectionParams

type CourierDetectionParams struct {

	// TrackingNumber of a shipment. Mandatory field.
	TrackingNumber string `json:"tracking_number"`

	// Slug If not specified, AfterShip will automatically detect the courier based on the tracking number format and
	// your selected couriers.
	// Use array to input a list of couriers for auto detect.
	Slug []string `json:"slug,omitempty"`

	AdditionalField

	SlugGroup string `json:"slug_group,omitempty"`
}

CourierDetectionParams contains fields required and optional fields for courier detection

type CourierList

type CourierList struct {
	Total    int       `json:"total"`    // Total number of couriers supported by AfterShip.
	Couriers []Courier `json:"couriers"` // Array of Courier describes the couriers information.
}

CourierList is the model describing an AfterShip courier list

type CreateTrackingParams

type CreateTrackingParams struct {
	/**
	 * Tracking number of a shipment.
	 */
	TrackingNumber string `json:"tracking_number"`

	/**
	 * Unique code of each courier. If you do not specify a slug,
	 * AfterShip will automatically detect the courier based on the tracking number format and your selected couriers.
	 */
	Slug string `json:"slug,omitempty"`

	/**
	 * Title of the tracking. Default value as tracking_number
	 */
	Title string `json:"title,omitempty"`

	/**
	 * Text field for order ID
	 */
	OrderID string `json:"order_id,omitempty"`

	/**
	 * Text field for order path
	 */
	OrderIDPath string `json:"order_id_path,omitempty"`

	/**
	 * Custom fields that accept a hash with string, boolean or number fields
	 */
	CustomFields map[string]string `json:"custom_fields,omitempty"`

	/**
	 * Enter ISO 639-1 Language Code to specify the store, customer or order language.
	 */
	Language string `json:"language,omitempty"`

	/**
	 * Promised delivery date of an order inYYYY-MM-DD format.
	 */
	OrderPromisedDeliveryDate string `json:"order_promised_delivery_date,omitempty"`

	/**
	 * The state of the sender’s address
	 */
	OriginState string `json:"origin_state,omitempty"`

	/**
	 * The city of the sender’s address.
	 */
	OriginCity string `json:"origin_city,omitempty"`

	/**
	 * The postal of the sender’s address.
	 */
	OriginPostalCode string `json:"origin_postal_code,omitempty"`

	/**
	 * The sender address that the shipment is shipping from.
	 */
	OriginRawLocation string `json:"origin_raw_location,omitempty"`

	/**
	 * Shipment delivery type: pickup_at_store, pickup_at_courier, door_to_door
	 */
	DeliveryType string `json:"delivery_type,omitempty"`

	/**
	 * Shipment pickup location for receiver
	 */
	PickupLocation string `json:"pickup_location,omitempty"`

	/**
	 * Shipment pickup note for receiver
	 */
	PickupNote string `json:"pickup_note,omitempty"`

	AdditionalField

	/**
	 * Apple iOS device IDs to receive the push notifications.
	 */
	IOS []string `json:"ios,omitempty"`

	/**
	 * Google cloud message registration IDs to receive the push notifications.
	 */
	Android []string `json:"android,omitempty"`

	/**
	 * Email address(es) to receive email notifications.
	 */
	Emails []string `json:"emails,omitempty"`

	/**
	 * Phone number(s) to receive sms notifications. Enter+ and area code before phone number.
	 */
	SMSes []string `json:"smses,omitempty"`

	/**
	 * Customer name of the tracking.
	 */
	CustomerName string `json:"customer_name,omitempty"`

	/**
	 * The shipping address that the shipment is shipping to.
	 */
	DestinationRawLocation string `json:"destination_raw_location,omitempty"`

	/**
	 * Text field for the note
	 */
	Note string `json:"note,omitempty"`

	/**
	 * Slug group is a group of slugs which belong to same courier. For example, when you inpit "fedex-group" as slug_group, AfterShip will detect the tracking with "fedex-uk", "fedex-fims", and other slugs which belong to "fedex". It cannot be used with slug at the same time.
	 */
	SlugGroup string `json:"slug_group,omitempty"`

	/**
	 * Date and time of the order created
	 */
	OrderDate string `json:"order_date,omitempty"`

	/**
	 * Text field for order number
	 */
	OrderNumber string `json:"order_number,omitempty"`

	/**
	 * The carrier’s shipment type. When you input this field, AfterShip will not get updates from the carrier.
	 */
	ShipmentType string `json:"shipment_type,omitempty"`

	/**
	 * Used to add tags to your shipments to help categorize and filter them easily.
	 */
	ShipmentTags []string `json:"shipment_tags,omitempty"`

	/**
	 *  which carrier account you’ve used to handle a shipment
	 */
	CourierConnectionId string `json:"courier_connection_id,omitempty"`

	/**
	 * If a shipment has multiple carriers, you can use the next_couriers field to tell AfterShip who the second carrier is.
	 */
	NextCouriers []NextCourier `json:"next_couriers,omitempty"`
}

CreateTrackingParams provides parameters for new Tracking API request

type EstimatedDelivery

type EstimatedDelivery struct {
	Type        string `json:"type,omitempty"`         // The format of the EDD. Either a single date or a date range.
	Source      string `json:"source,omitempty"`       // The source of the EDD. Either the carrier, AfterShip AI, or based on your custom EDD settings.
	Datetime    string `json:"datetime,omitempty"`     // The latest EDD time.
	DatetimeMin string `json:"datetime_min,omitempty"` // For a date range EDD format, the date and time for the lower end of the range.
	DatetimeMax string `json:"datetime_max,omitempty"` // For a date range EDD format, the date and time for the upper end of the range.
}

EstimatedDelivery represents a latest_estimated_delivery returned by the Aftership API

type EstimatedDeliveryDate

type EstimatedDeliveryDate struct {
	// AfterShip's unique code of courier.Please refer to https://track.aftership.com/couriers/download.
	Slug string `json:"slug,omitempty"`

	// Shipping and delivery options provided by the carrier.
	ServiceTypeName string `json:"service_type_name,omitempty"`

	// The location from where the package is picked up by the carrier to be delivered to the final destination.
	OriginAddress *Address `json:"origin_address,omitempty"`

	// The final destination of the customer where the delivery will be made.
	DestinationAddress *Address `json:"destination_address,omitempty"`

	// AfterShip uses this object to calculate the total weight of the order.
	Weight *Weight `json:"weight,omitempty"`

	// The number of packages.
	PackageCount int64 `json:"package_count,omitempty"`

	// The local pickup time of the package.
	PickupTime string `json:"pickup_time,omitempty"`

	// Either `pickup_time` or `estimated_pickup` is required.
	EstimatedPickup *EstimatedPickup `json:"estimated_pickup,omitempty"`

	// The estimated arrival date of the shipment.
	EstimatedDeliveryDate string `json:"estimated_delivery_date,omitempty"`

	// The reliability of the estimated delivery date based on the trend of the transit time for the similar delivery route and the carrier's delivery performance range from 0.0 to 1.0 (Beta feature).
	ConfidenceScore float64 `json:"confidence_score,omitempty"`

	// Earliest estimated delivery date of the shipment.
	EstimatedDeliveryDateMin string `json:"estimated_delivery_date_min,omitempty"`

	// Latest estimated delivery date of the shipment.
	EstimatedDeliveryDateMax string `json:"estimated_delivery_date_max,omitempty"`
}

EstimatedDeliveryDate represents a aftership_estimated_delivery_date returned by the Aftership API

type EstimatedDeliveryDates

type EstimatedDeliveryDates struct {
	Dates []EstimatedDeliveryDate `json:"estimated_delivery_dates,omitempty"`
}

EstimatedDeliveryDates is a response object of batch predict

type EstimatedPickup

type EstimatedPickup struct {
	// The local order time of the package.
	OrderTime string `json:"order_time,omitempty"`

	// Order cut off time. AfterShip will set 18:00:00 as the default value.
	OrderCutoffTime string `json:"order_cutoff_time,omitempty"`

	// Operating days in a week. Number refers to the weekday.
	// E.g., [1,2,3,4,5] means operating days are from Monday to Friday.
	// AfterShip will set [1,2,3,4,5] as the default value.
	BusinessDays []int64 `json:"business_days,omitempty"`

	OrderProcessingTime *OrderProcessingTime `json:"order_processing_time,omitempty"`

	// The local pickup time of the package.
	PickupTime string `json:"pickup_time,omitempty"`
}

type GetCheckpointParams

type GetCheckpointParams struct {
	// List of fields to include in the response. Use comma for multiple values.
	// Fields to include:slug,created_at,checkpoint_time,city,coordinates,country_iso3,
	// country_name,message,state,tag,zip
	// Default: none, Example: city,tag
	Fields string `url:"fields,omitempty" json:"fields,omitempty"`

	// Support Chinese to English translation for china-ems  and  china-post  only (Example: en)
	Lang string `url:"lang,omitempty" json:"lang,omitempty"`

	AdditionalField
}

GetCheckpointParams is the additional parameters in checkpoint query

type GetTrackingParams

type GetTrackingParams struct {
	/** List of fields to include in the response.
	 * Use comma for multiple values. Fields to include:
	 * tracking_postal_code,tracking_ship_date,tracking_account_number,tracking_key,
	 * tracking_origin_country,tracking_destination_country,tracking_state,title,order_id,
	 * tag,checkpoints,checkpoint_time, message, country_name
	 * Defaults: none, Example: title,order_id
	 */
	Fields string `url:"fields,omitempty" json:"fields,omitempty"`

	/**
	 * Support Chinese to English translation for china-ems and china-post only (Example: en)
	 */
	Lang string `url:"lang,omitempty" json:"lang,omitempty"`

	AdditionalField
}

GetTrackingParams is the additional parameters in single tracking query

type GetTrackingsParams

type GetTrackingsParams struct {
	/**
	 * Destination country of trackings returned by courier.
	 * Use ISO Alpha-3 (three letters).
	 * Use comma for multiple values. (Example: USA,HKG)
	 */
	CourierDestinationCountryIso3 string `url:"courier_destination_country_iso3,omitempty" json:"courier_destination_country_iso3,omitempty"`

	/**
	 * End date and time of trackings created.
	 * (Defaults: now, Example: 2013-04-15T16:41:56+08:00)
	 */
	CreatedAtMax string `url:"created_at_max,omitempty" json:"created_at_max,omitempty"`

	/**
	 * Start date and time of trackings created. AfterShip only stores data of 90 days.
	 * (Defaults: 30 days ago, Example: 2013-03-15T16:41:56+08:00)
	 */
	CreatedAtMin string `url:"created_at_min,omitempty" json:"created_at_min,omitempty"`

	/**
	 * Destination country of trackings. Use ISO Alpha-3 (three letters).
	 * Use comma for multiple values. (Example: USA,HKG)
	 */
	Destination string `url:"destination,omitempty" json:"destination,omitempty"`

	/**
	 * List of fields to include in the response.
	 * Use comma for multiple values. Fields to include: title,  order_id,  tag,
	 * checkpoints,  checkpoint_time,  message,  country_name
	 * Defaults: none, Example: title,order_id
	 */
	Fields string `url:"fields,omitempty" json:"fields,omitempty"`

	/**
	 * Search the content of the tracking record fields:
	 * tracking_number,  title,  order_id,  customer_name,  custom_fields,  order_id,  emails,  smses
	 */
	Keyword string `url:"keyword,omitempty" json:"keyword,omitempty"`

	/**
	 * Number of trackings each page contain. (Default: 100, Max: 200)
	 */
	Limit int `url:"limit,omitempty" json:"limit,omitempty"`

	/**
	 * Origin country of trackings. Use ISO Alpha-3 (three letters). Use comma for multiple values. (Example: USA,HKG)
	 */
	Origin string `url:"origin,omitempty" json:"origin,omitempty"`

	/**
	 * Page to show. (Default: 1)
	 */
	Page int `url:"page,omitempty" json:"page,omitempty"`

	/**
	 * Select return to sender, the value should be true or false,
	 * with optional comma separated.
	 */
	ReturnToSender string `url:"return_to_sender,omitempty" json:"return_to_sender,omitempty"`

	/**
	 * Tags you added to your shipments to help categorize and filter them easily.
	 * Use a comma to separate multiple values (Example: a,b)
	 */
	ShipmentTags string `url:"shipment_tags,omitempty" json:"shipment_tags,omitempty"`

	/**
	 * Unique courier code Use comma for multiple values. (Example: dhl,ups,usps)
	 */
	Slug string `url:"slug,omitempty" json:"slug,omitempty"`

	/**
	 * Current status of tracking.
	 */
	Tag string `url:"tag,omitempty" json:"tag,omitempty"`

	/**
	 * Tracking number of shipments. Use comma to separate multiple values
	 * (Example: RA123456789US,LE123456789US)
	 */
	TrackingNumbers string `url:"tracking_numbers,omitempty" json:"tracking_numbers,omitempty"`

	/**
	 * Total delivery time in days.
	 * (Example: 1)
	 */
	TransitTime int `url:"transit_time,omitempty" json:"transit_time,omitempty"`

	/**
	 * End date and time of trackings updated. (Example: 2013-04-15T16:41:56+08:00)
	 */
	UpdatedAtMax string `url:"updated_at_max,omitempty" json:"updated_at_max,omitempty"`

	/**
	 * Start date and time of trackings updated.
	 * (Example: 2013-04-15T16:41:56+08:00)
	 */
	UpdatedAtMin string `url:"updated_at_min,omitempty" json:"updated_at_min,omitempty"`
}

GetTrackingsParams represents the set of params for get Trackings API

type LastCheckpoint

type LastCheckpoint struct {
	ID             string     `json:"id,omitempty"`
	Slug           string     `json:"slug,omitempty"`
	TrackingNumber string     `json:"tracking_number,omitempty"`
	Tag            string     `json:"tag,omitempty"`
	Subtag         string     `json:"subtag,omitempty"`
	SubtagMessage  string     `json:"subtag_message,omitempty"`
	Checkpoint     Checkpoint `json:"checkpoint"`
}

LastCheckpoint is the last checkpoint API response

type Meta

type Meta struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Type    string `json:"type"`
}

Meta is used to communicate extra information about the response to the developer.

type NextCourier

type NextCourier struct {
	Slug           string `json:"slug"`
	TrackingNumber string `json:"tracking_number"`
	Source         string `json:"source"`
}

type Notification

type Notification struct {
	Emails []string `json:"emails"`
	SMSes  []string `json:"smses"`
}

Notification is the model describing an AfterShip notification

type OrderProcessingTime

type OrderProcessingTime struct {
	// Processing time of an order, from being placed to being picked up.
	// Only support day as value now. AfterShip will set day as the default value.
	Unit string `json:"unit,omitempty"`

	// Processing time of an order, from being placed to being picked up.
	// AfterShip will set 0 as the default value.
	Value int64 `json:"value"`
}

type PagedTrackings

type PagedTrackings struct {
	Limit                         int        `json:"limit"`   // Number of trackings each page contain. (Default: 100)
	Count                         int        `json:"count"`   // Total number of matched trackings, max. number is 10,000
	Page                          int        `json:"page"`    // Page to show. (Default: 1)
	Keyword                       string     `json:"keyword"` // Search the content of the tracking record fields: tracking_number
	Slug                          string     `json:"slug"`
	Origin                        []string   `json:"origin"`
	Destination                   []string   `json:"destination"`
	Tag                           string     `json:"tag"`
	CreatedAtMin                  *time.Time `json:"created_at_min"`
	CreatedAtMax                  *time.Time `json:"created_at_max"`
	LastUpdatedAt                 *time.Time `json:"last_updated_at"`
	ReturnToSender                []bool     `json:"return_to_sender"`
	CourierDestinationCountryIso3 []string   `json:"courier_destination_country_iso3"`
	Trackings                     []Tracking `json:"trackings"` // Array of Hash describes the tracking information.
}

PagedTrackings is a model for data part of the multiple trackings API responses

type RateLimit

type RateLimit struct {
	Reset     int64 `json:"reset"`     // The unix timestamp when the rate limit will be reset.
	Limit     int   `json:"limit"`     // The rate limit ceiling for your account per sec.
	Remaining int   `json:"remaining"` // The number of requests left for the 1 second window.
}

RateLimit is the X-RateLimit value in API response headers

type Response

type Response struct {
	Meta Meta        `json:"meta"`
	Data interface{} `json:"data"`
}

Response is the message envelope for the AfterShip API response

type SlugTrackingNumber

type SlugTrackingNumber struct {
	Slug           string
	TrackingNumber string
}

SlugTrackingNumber is a unique identifier for a single tracking by slug and tracking number

func (SlugTrackingNumber) URIPath

func (stn SlugTrackingNumber) URIPath() (string, error)

URIPath returns the URL path of SlugTrackingNumber

type TooManyRequestsError

type TooManyRequestsError struct {
	APIError
	RateLimit *RateLimit `json:"rate_limit"`
}

TooManyRequestsError is the too many requests error in AfterShip API calls

func (*TooManyRequestsError) Error

func (e *TooManyRequestsError) Error() string

Error serializes the error object to JSON and returns it as a string.

type Tracking

type Tracking struct {
	/**
	 * A unique identifier generated by AfterShip for the tracking.
	 */
	ID string `json:"id"`

	/**
	 * Date and time of the tracking created.
	 */
	CreatedAt *time.Time `json:"created_at"`

	/**
	 * Date and time of the tracking last updated.
	 */
	UpdatedAt *time.Time `json:"updated_at"`

	/**
	 * Date and time the tracking was last updated
	 */
	LastUpdatedAt *time.Time `json:"last_updated_at,omitempty"`

	/**
	 * Tracking number of a shipment.
	 */
	TrackingNumber string `json:"tracking_number"`

	/**
	 * Unique code of each courier.
	 */
	Slug string `json:"slug,omitempty"`

	/**
	 * Whether or not AfterShip will continue tracking the shipments. Value is false when tag (status) is Delivered, Expired, or further updates for 30 days since last update.
	 */
	Active bool `json:"active,omitempty"`

	/**
	 * Custom fields that accept a hash with string, boolean or number fields
	 */
	CustomFields map[string]string `json:"custom_fields,omitempty"`

	/**
	 * Customer name of the tracking.
	 */
	CustomerName string `json:"customer_name,omitempty"`

	/**
	 * Total delivery time in days.
	 * (Example: 1)
	 */
	TransitTime int `url:"transit_time,omitempty" json:"transit_time,omitempty"`

	/**
	 * Destination country of the tracking. ISO Alpha-3 (three letters).
	 * If you use postal service to send international shipments, AfterShip will automatically get tracking results from destination postal service based on destination country.
	 */
	DestinationCountryISO3 string `json:"destination_country_iso3,omitempty"`

	DestinationCity string `json:"destination_city,omitempty"`

	/**
	 * Shipping address that the shipment is shipping to.
	 */
	DestinationRawLocation string `json:"destination_raw_location,omitempty"`

	/**
	 * Destination country of the tracking detected from the courier. ISO Alpha-3 (three letters). Value will be null if the courier doesn't provide the destination country.
	 */
	CourierDestinationCountryISO3 string `json:"courier_destination_country_iso3,omitempty"`

	/**
	 * Email address(es) to receive email notifications.
	 */
	Emails []string `json:"emails,omitempty"`

	/**
	 * Expected delivery date (nullable). Available format: YYYY-MM-DD, YYYY-MM-DDTHH:MM:SS, or YYYY-MM-DDTHH:MM:SS+TIMEZONE
	 */
	ExpectedDelivery string `json:"expected_delivery,omitempty"`

	/**
	 * Text field for the note.
	 */
	Note string `json:"note,omitempty"`

	/**
	 * Text field for order ID
	 */
	OrderID string `json:"order_id,omitempty"`

	/**
	 * Text field for order path
	 */
	OrderIDPath string `json:"order_id_path,omitempty"`

	/**
	 * Date and time of the order created
	 */
	OrderDate string `json:"order_date,omitempty"`

	/**
	 * Origin country of the tracking. ISO Alpha-3 (three letters).
	 */
	OriginCountryISO3 string `json:"origin_country_iso3,omitempty"`

	/**
	 * Number of packages under the tracking (if any).
	 */
	ShipmentPackageCount int `json:"shipment_package_count,omitempty"`

	/**
	 * Date and time the tracking was picked up
	 */
	ShipmentPickupDate string `json:"shipment_pickup_date,omitempty"`

	/**
	 * Date and time the tracking was delivered
	 */
	ShipmentDeliveryDate string `json:"shipment_delivery_date,omitempty"`

	/**
	 * Shipment type provided by carrier (if any).
	 */
	ShipmentType string `json:"shipment_type,omitempty"`

	/**
	 * Shipment weight provided by carrier (if any)
	 */
	ShipmentWeight float64 `json:"shipment_weight,omitempty"`

	/**
	 * Weight unit provided by carrier, either in kg or lb (if any)
	 */
	ShipmentWeightUnit string `json:"shipment_weight_unit,omitempty"`

	/**
	 * Signed by information for delivered shipment (if any).
	 */
	SignedBy string `json:"signed_by,omitempty"`

	/**
	 * Phone number(s) to receive sms notifications. The phone number(s) to receive sms notifications. Phone number should begin with `+` and `Area Code` before phone number. Comma separated for multiple values.
	 */
	SMSes []string `json:"smses,omitempty"`

	/**
	 * Source of how this tracking is added.
	 */
	Source string `json:"source,omitempty"`

	/**
	 * Current status of tracking.
	 */
	Tag string `json:"tag,omitempty"`

	/**
	 * Current subtag of tracking. (See subtag definition)
	 */
	Subtag string `json:"subtag,omitempty"`

	/**
	 * Current status of tracking.
	 */
	SubtagMessage string `json:"subtag_message,omitempty"`

	/**
	 * Title of the tracking.
	 */
	Title string `json:"title,omitempty"`

	/**
	 * Number of attempts AfterShip tracks at courier's system.
	 */
	TrackedCount int `json:"tracked_count,omitempty"`

	/**
	 * Indicates if the shipment is trackable till the final destination.
	 */
	LastMileTrackingSupported bool `json:"last_mile_tracking_supported,omitempty"`

	/**
	 * Store, customer, or order language of the tracking.
	 */
	Language string `json:"language,omitempty"`

	/**
	 * The token to generate the direct tracking link: https://yourusername.aftership.com/unique_token or https://www.aftership.com/unique_token
	 */
	UniqueToken string `json:"unique_token,omitempty"`

	/**
	 * Array of Hash describes the checkpoint information.
	 */
	Checkpoints []Checkpoint `json:"checkpoints,omitempty"`

	/**
	 * Phone number(s) subscribed to receive sms notifications.
	 */
	SubscribedSMSes []string `json:"subscribed_smses,omitempty"`

	/**
	 * Email address(es) subscribed to receive email notifications. Comma separated for multiple values
	 */
	SubscribedEmails []string `json:"subscribed_emails,omitempty"`

	/**
	 * Whether or not the shipment is returned to sender. Value is true when any of its checkpoints has subtagException_010(returning to sender) orException_011(returned to sender). Otherwise value is false
	 */
	ReturnToSender bool `json:"return_to_sender,omitempty"`

	/**
	 * Promised delivery date of an order inYYYY-MM-DD format.
	 */
	OrderPromisedDeliveryDate string `json:"order_promised_delivery_date,omitempty"`

	/**
	 * Shipment delivery type: pickup_at_store, pickup_at_courier, door_to_door
	 */
	DeliveryType string `json:"delivery_type,omitempty"`

	/**
	 * Shipment pickup location for receiver
	 */
	PickupLocation string `json:"pickup_location,omitempty"`

	/**
	 * Shipment pickup note for receiver
	 */
	PickupNote string `json:"pickup_note,omitempty"`

	/**
	 * Official tracking URL of the courier (if any)
	 */
	CourierTrackingLink string `json:"courier_tracking_link,omitempty"`

	/**
	 * date and time of the first attempt by the carrier to deliver the package to the addressee. Available format: YYYY-MM-DDTHH:MM:SS, or YYYY-MM-DDTHH:MM:SS+TIMEZONE
	 */
	FirstAttemptedAt string `json:"first_attempted_at,omitempty"`

	/**
	 * Delivery instructions (delivery date or address) can be modified by visiting the link if supported by a carrier.
	 */
	CourierRedirectLink string `json:"courier_redirect_link,omitempty"`

	AdditionalField

	/**
	 * Whether the tracking is delivered on time or not.
	 */
	OnTimeStatus string `json:"on_time_status,omitempty"`

	/**
	 * The difference days of the on time.
	 */
	OnTimeDifference int `json:"on_time_difference,omitempty"`

	/**
	 * The tags of the order.
	 */
	OrderTags []string `json:"order_tags,omitempty"`

	/**
	 * Estimated delivery time of the shipment provided by AfterShip, indicate when the shipment should arrive.
	 */
	EstimatedDeliveryDate EstimatedDeliveryDate `json:"aftership_estimated_delivery_date,omitempty"`

	/**
	 * Estimated delivery time of the shipment based on your custom EDD settings.
	 */
	CustomEstimatedDeliveryDate EstimatedDelivery `json:"custom_estimated_delivery_date,omitempty"`

	/**
	 * The shipment’s original estimated delivery date.
	 */
	FirstEstimatedDelivery EstimatedDelivery `json:"first_estimated_delivery"`

	/**
	 * Text field for order number
	 */
	OrderNumber string `json:"order_number,omitempty"`

	/**
	 * The latest estimated delivery date.
	 * May come from the carrier, AfterShip AI, or based on your custom settings.
	 * This can appear in 1 of 3 formats based on the data received.
	 *  1. Date only: `YYYY-MM-DD`
	 *  2. Date and time: `YYYY-MM-DDTHH:mm:ss`
	 *  3. Date, time, and time zone: `YYYY-MM-DDTHH:mm:ssZ`
	 */
	LatestEstimatedDelivery EstimatedDelivery `json:"latest_estimated_delivery,omitempty"`

	/**
	 * Tags you added to your shipments to help categorize and filter them easily.
	 */
	ShipmentTags []string `json:"shipment_tags,omitempty"`

	/**
	 * Which carrier account you’ve used to handle a shipment.
	 */
	CourierConnectionId string `json:"courier_connection_id"`

	/**
	 * If a shipment has multiple carriers, you can use the next_couriers field to tell AfterShip who the second carrier is.
	 */
	NextCouriers []NextCourier `json:"next_couriers"`
}

Tracking represents a Tracking returned by the AfterShip API

type TrackingCompletedStatus

type TrackingCompletedStatus string

TrackingCompletedStatus is status to make the tracking as completed

const TrackingCompletedStatusDelivered TrackingCompletedStatus = "DELIVERED"

TrackingCompletedStatusDelivered is reason DELIVERED to make the tracking as completed

const TrackingCompletedStatusLost TrackingCompletedStatus = "LOST"

TrackingCompletedStatusLost is reason LOST to make the tracking as completed

const TrackingCompletedStatusReturnedToSender TrackingCompletedStatus = "RETURNED_TO_SENDER"

TrackingCompletedStatusReturnedToSender is reason RETURNED_TO_SENDER to make the tracking as completed

type TrackingID

type TrackingID string

TrackingID is a unique identifier generated by AfterShip for the tracking.

func (TrackingID) URIPath

func (id TrackingID) URIPath() (string, error)

URIPath returns the URL path of TrackingID

type TrackingIdentifier

type TrackingIdentifier interface {
	URIPath() (string, error)
}

TrackingIdentifier is an identifier for a single tracking

type UpdateTrackingParams

type UpdateTrackingParams struct {
	SMSes                     []string          `json:"smses,omitempty"`
	Emails                    []string          `json:"emails,omitempty"`
	Title                     string            `json:"title,omitempty"`
	CustomerName              string            `json:"customer_name,omitempty"`
	OrderID                   string            `json:"order_id,omitempty"`
	OrderIDPath               string            `json:"order_id_path,omitempty"`
	CustomFields              map[string]string `json:"custom_fields,omitempty"`
	Note                      string            `json:"note,omitempty"`
	Language                  string            `json:"language,omitempty"`
	OrderPromisedDeliveryDate string            `json:"order_promised_delivery_date,omitempty"`
	DeliveryType              string            `json:"delivery_type,omitempty"`
	PickupLocation            string            `json:"pickup_location,omitempty"`
	PickupNote                string            `json:"pickup_note,omitempty"`
	Slug                      string            `json:"slug,omitempty"`
	AdditionalField
	OrderNumber            string `json:"order_number,omitempty"`
	OrderDate              string `json:"order_date,omitempty"`
	ShipmentType           string `json:"shipment_type,omitempty"`
	OriginState            string `json:"origin_state,omitempty"`
	OriginCity             string `json:"origin_city,omitempty"`
	OriginPostalCode       string `json:"origin_postal_code,omitempty"`
	OriginRawLocation      string `json:"origin_raw_location,omitempty"`
	DestinationRawLocation string `json:"destination_raw_location,omitempty"`
}

UpdateTrackingParams represents an update to Tracking details

type Weight

type Weight struct {
	// The weight unit of the package.
	Unit string `json:"unit,omitempty"`

	// The weight of the shipment.
	Value int64 `json:"value,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL