aftership

package module
v2.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2021 License: Apache-2.0 Imports: 14 Imported by: 0

README

aftership-sdk-go

Build Status codecov.io 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 v4 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/v2

Import:

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

Quick Start

package main

import (
        "context"
        "fmt"

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

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
    • Endpoint - string, AfterShip endpoint, default "https://api.aftership.com/v4"
    • UserAagentPrefix - string, prefix of User-Agent in headers, default "aftership-sdk-go"

Example:

client, err := aftership.NewClient(aftership.Config{
    APIKey: "YOUR_API_KEY",
    Endpoint: "https://api.aftership.com/OLDER_VERSIONOUR_API_KEY",
    UserAagentPrefix: "aftership-sdk-go",
})

Rate Limiter

To understand AfterShip rate limit policy, please see Limit section in https://docs.aftership.com/api/4/overview

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

import (
    "context"
    "fmt"

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

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://docs.aftership.com/api/4/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.NewTracking{
    TrackingNumber: "1234567890",
    Slug:           []string{"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

// old version
var api apiV4.CourierHandler = &impl.AfterShipApiV4Impl{
    "<your-api-key>",
    nil,
    nil,
}
res, meta := api.GetCouriers()
if (meta.Code == 200) {
    fmt.Print(res)
}

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

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

fmt.Println(result)

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 VERSION string = "2.0.0"

VERSION is the version number of this package

Variables

This section is empty.

Functions

This section is empty.

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 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    []string   `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) 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:           []string{"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 := 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) (TrackingCouriers, 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",
})
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",
}

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
	// BaseURL is the base URL of AfterShip API. Defaults to 'https://api.aftership.com/v4'
	BaseURL string
	// UserAgentPrefix is the prefix of User-Agent in headers. Defaults to 'aftership-sdk-go'
	UserAgentPrefix string
}

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"`

	// TrackingPostalCode is the postal code of receiver's address.
	// Required by some couriers, such as postnl
	TrackingPostalCode string `json:"tracking_postal_code,omitempty"`

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

	// TrackingAccountNumber of the shipper for a specific courier. Required by some couriers, such as dynamic-logistics
	TrackingAccountNumber string `json:"tracking_account_number,omitempty"`

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

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

	// 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"`
}

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 {
	TrackingNumber             string            `json:"tracking_number"`                        // Tracking number of a shipment.
	Slug                       []string          `json:"slug,omitempty"`                         // 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.
	TrackingPostalCode         string            `json:"tracking_postal_code,omitempty"`         // The postal code of receiver's address. Required by some couriers, such as deutsch-post
	TrackingShipDate           string            `json:"tracking_ship_date,omitempty"`           // Shipping date in YYYYMMDD format. Required by some couriers, such as deutsch-post
	TrackingAccountNumber      string            `json:"tracking_account_number,omitempty"`      // Account number of the shipper for a specific courier. Required by some couriers, such as dynamic-logistics
	TrackingKey                string            `json:"tracking_key,omitempty"`                 // Key of the shipment for a specific courier. Required by some couriers, such as sic-teliway
	TrackingOriginCountry      string            `json:"tracking_origin_country,omitempty"`      // Origin Country of the shipment for a specific courier. Required by some couriers, such as dhl
	TrackingDestinationCountry string            `json:"tracking_destination_country,omitempty"` // Destination Country of the shipment for a specific courier. Required by some couriers, such as postnl-3s
	TrackingState              string            `json:"tracking_state,omitempty"`               // Located state of the shipment for a specific courier. Required by some couriers, such as star-track-courier
	Android                    []string          `json:"android,omitempty"`                      // Google cloud message registration IDs to receive the push notifications.
	IOS                        []string          `json:"ios,omitempty"`                          // Apple iOS device IDs to receive the push notifications.
	Emails                     []string          `json:"emails,omitempty"`                       // Email address(es) to receive email notifications.
	SMSes                      []string          `json:"smses,omitempty"`                        // Phone number(s) to receive sms notifications. Enter+ and area code before phone number.
	Title                      string            `json:"title,omitempty"`                        // Title of the tracking. Default value as tracking_number
	CustomerName               string            `json:"customer_name,omitempty"`                // Customer name of the tracking.
	OriginCountryISO3          string            `json:"origin_country_iso3,omitempty"`          // Enter ISO Alpha-3 (three letters) to specify the origin of the shipment (e.g. USA for United States).
	DestinationCountryISO3     string            `json:"destination_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.
	OrderID                    string            `json:"order_id,omitempty"`                     // Text field for order ID
	OrderIDPath                string            `json:"order_id_path,omitempty"`                // Text field for order path
	CustomFields               map[string]string `json:"custom_fields,omitempty"`                // Custom fields that accept a hash with string, boolean or number fields
	Language                   string            `json:"language,omitempty"`                     // Enter ISO 639-1 Language Code to specify the store, customer or order language.
	OrderPromisedDeliveryDate  string            `json:"order_promised_delivery_date,omitempty"` // Promised delivery date of an order inYYYY-MM-DD format.
	DeliveryType               string            `json:"delivery_type,omitempty"`                // Shipment delivery type: pickup_at_store, pickup_at_courier, door_to_door
	PickupLocation             string            `json:"pickup_location,omitempty"`              // Shipment pickup location for receiver
	PickupNote                 string            `json:"pickup_note,omitempty"`                  // Shipment pickup note for receiver
}

CreateTrackingParams provides parameters for new Tracking API request

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"`
}

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"`
}

GetTrackingParams is the additional parameters in single tracking query

type GetTrackingsParams

type GetTrackingsParams struct {
	Page         int    `url:"page,omitempty" json:"page,omitempty"`                     // Page to show. (Default: 1)
	Limit        int    `url:"limit,omitempty" json:"limit,omitempty"`                   // Number of trackings each page contain. (Default: 100, Max: 200)
	Keyword      string `url:"keyword,omitempty" json:"keyword,omitempty"`               // Search the content of the tracking record fields:tracking_number, title, order_id, customer_name, custom_fields, order_id, emails, smses
	Slug         string `url:"slug,omitempty" json:"slug,omitempty"`                     // Unique courier code Use comma for multiple values. (Example: dhl,ups,usps)
	DeliveryTime int    `url:"delivery_time,omitempty" json:"delivery_time,omitempty"`   // Total delivery time in days.
	Origin       string `url:"origin,omitempty" json:"origin,omitempty"`                 // Origin 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"`       // Destination country of trackings. Use ISO Alpha-3 (three letters). Use comma for multiple values. (Example: USA,HKG)
	Tag          string `url:"tag,omitempty" json:"tag,omitempty"`                       // Current status of tracking. Values include Pending, InfoReceived, InTransit, OutForDelivery, AttemptFail, Delivered, Exception, Expired(See status definition)
	CreatedAtMin string `url:"created_at_min,omitempty" json:"created_at_min,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)"
	CreatedAtMax string `url:"created_at_max,omitempty" json:"created_at_max,omitempty"` // End date and time of trackings created. (Defaults: now, Example: 2013-04-15T16:41:56+08:00)"
	Fields       string `url:"fields,omitempty" json:"fields,omitempty"`                 // "List of fields to include in the http. Use comma for multiple values. Fields to include: title, order_id, tag, checkpoints, checkpoint_time, message, country_name. Defaults: none, Example: title,order_id"
	Lang         string `url:"lang,omitempty" json:"lang,omitempty"`                     // "Default: ” / Example: 'en'. Support Chinese to English translation for china-ems and china-post only"
}

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 Notification

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

Notification is the model describing an AfterShip notification

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)
	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 SingleTrackingOptionalParams

type SingleTrackingOptionalParams struct {
	TrackingPostalCode         string `url:"tracking_postal_code,omitempty" json:"tracking_postal_code,omitempty"`                 // The postal code of receiver's address. Required by some couriers, such asdeutsch-post
	TrackingShipDate           string `url:"tracking_ship_date,omitempty" json:"tracking_ship_date,omitempty"`                     // Shipping date in YYYYMMDD format. Required by some couriers, such asdeutsch-post
	TrackingDestinationCountry string `url:"tracking_destination_country,omitempty" json:"tracking_destination_country,omitempty"` // Destination Country of the shipment for a specific courier. Required by some couriers, such aspostnl-3s
	TrackingAccountNumber      string `url:"tracking_account_number,omitempty" json:"tracking_account_number,omitempty"`           // Account number of the shipper for a specific courier. Required by some couriers, such asdynamic-logistics
	TrackingKey                string `url:"tracking_key,omitempty" json:"tracking_key,omitempty"`                                 // Key of the shipment for a specific courier. Required by some couriers, such assic-teliway
	TrackingOriginCountry      string `url:"tracking_origin_country,omitempty" json:"tracking_origin_country,omitempty"`           // Origin Country of the shipment for a specific courier. Required by some couriers, such asdhl
	TrackingState              string `url:"tracking_state,omitempty" json:"tracking_state,omitempty"`                             // Located state of the shipment for a specific courier. Required by some couriers, such asstar-track-courier
}

SingleTrackingOptionalParams is the optional parameters in single tracking query

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 {
	ID                            string            `json:"id"`                                         // A unique identifier generated by AfterShip for the tracking.
	CreatedAt                     *time.Time        `json:"created_at"`                                 // Date and time of the tracking created.
	UpdatedAt                     *time.Time        `json:"updated_at"`                                 // Date and time of the tracking last updated.
	TrackingNumber                string            `json:"tracking_number"`                            // Tracking number of a shipment.
	TrackingPostalCode            string            `json:"tracking_postal_code,omitempty"`             // The postal code of receiver's address. Required by some couriers, such as deutsch-post
	TrackingShipDate              string            `json:"tracking_ship_date,omitempty"`               // Shipping date in YYYYMMDD format. Required by some couriers, such as deutsch-post
	TrackingAccountNumber         string            `json:"tracking_account_number,omitempty"`          // Account number of the shipper for a specific courier. Required by some couriers, such as dynamic-logistics
	TrackingOriginCountry         string            `json:"tracking_origin_country,omitempty"`          // Origin Country of the shipment for a specific courier. Required by some couriers, such as dhl
	TrackingDestinationCountry    string            `json:"tracking_destination_country,omitempty"`     // Destination Country of the shipment for a specific courier. Required by some couriers, such as postnl-3s
	TrackingState                 string            `json:"tracking_state,omitempty"`                   // Located state of the shipment for a specific courier. Required by some couriers, such as star-track-courier
	TrackingKey                   string            `json:"tracking_key,omitempty"`                     // Key of the shipment for a specific courier. Required by some couriers, such as sic-teliway
	Slug                          string            `json:"slug,omitempty"`                             // Unique code of each courier.
	Active                        bool              `json:"active,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.
	Android                       []string          `json:"android,omitempty"`                          // Google cloud message registration IDs to receive the push notifications.
	CustomFields                  map[string]string `json:"custom_fields,omitempty"`                    // Custom fields that accept a hash with string, boolean or number fields
	DeliveryTime                  int               `json:"delivery_time,omitempty"`                    // Total delivery time in days.
	DestinationCountryISO3        string            `json:"destination_country_iso3,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.
	CourierDestinationCountryISO3 string            `json:"courier_destination_country_iso3,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.
	Emails                        []string          `json:"emails,omitempty"`                           // Email address(es) to receive email notifications.
	ExpectedDelivery              string            `json:"expected_delivery,omitempty"`                // Expected delivery date (nullable). Available format: YYYY-MM-DD, YYYY-MM-DDTHH:MM:SS, or YYYY-MM-DDTHH:MM:SS+TIMEZONE
	IOS                           []string          `json:"ios,omitempty"`                              // Apple iOS device IDs to receive the push notifications.
	OrderID                       string            `json:"order_id,omitempty"`                         // Text field for order ID
	OrderIDPath                   string            `json:"order_id_path,omitempty"`                    // Text field for order path
	OriginCountryISO3             string            `json:"origin_country_iso3,omitempty"`              // Origin country of the tracking. ISO Alpha-3 (three letters).
	UniqueToken                   string            `json:"unique_token,omitempty"`                     // The token to generate the direct tracking link: https://yourusername.aftership.com/unique_token or https://www.aftership.com/unique_token
	ShipmentPackageCount          int               `json:"shipment_package_count,omitempty"`           // Number of packages under the tracking (if any).
	ShipmentType                  string            `json:"shipment_type,omitempty"`                    // Shipment type provided by carrier (if any).
	ShipmentWeight                float64           `json:"shipment_weight,omitempty"`                  // Shipment weight provided by carrier (if any)
	ShipmentWeightUnit            string            `json:"shipment_weight_unit,omitempty"`             // Weight unit provided by carrier, either in kg or lb (if any)
	LastUpdatedAt                 *time.Time        `json:"last_updated_at,omitempty"`                  // Date and time the tracking was last updated
	ShipmentPickupDate            string            `json:"shipment_pickup_date,omitempty"`             // Date and time the tracking was picked up
	ShipmentDeliveryDate          string            `json:"shipment_delivery_date,omitempty"`           // Date and time the tracking was delivered
	SubscribedSMSes               []string          `json:"subscribed_smses,omitempty"`                 // Phone number(s) subscribed to receive sms notifications.
	SubscribedEmails              []string          `json:"subscribed_emails,omitempty"`                // Email address(es) subscribed to receive email notifications. Comma separated for multiple values
	SignedBy                      string            `json:"signed_by,omitempty"`                        // Signed by information for delivered shipment (if any).
	SMSes                         []string          `json:"smses,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.
	Source                        string            `json:"source,omitempty"`                           // Source of how this tracking is added.
	Tag                           string            `json:"tag,omitempty"`                              // Current status of tracking.
	Subtag                        string            `json:"subtag,omitempty"`                           // Current subtag of tracking. (See subtag definition)
	SubtagMessage                 string            `json:"subtag_message,omitempty"`                   // Current status of tracking.
	Title                         string            `json:"title,omitempty"`                            // Title of the tracking.
	TrackedCount                  int               `json:"tracked_count,omitempty"`                    // Number of attempts AfterShip tracks at courier's system.
	LastMileTrackingSupported     bool              `json:"last_mile_tracking_supported,omitempty"`     // Indicates if the shipment is trackable till the final destination.
	Language                      string            `json:"language,omitempty"`                         // Store, customer, or order language of the tracking.
	ReturnToSender                bool              `json:"return_to_sender,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
	OrderPromisedDeliveryDate     string            `json:"order_promised_delivery_date,omitempty"`     // Promised delivery date of an order inYYYY-MM-DD format.
	DeliveryType                  string            `json:"delivery_type,omitempty"`                    // Shipment delivery type: pickup_at_store, pickup_at_courier, door_to_door
	PickupLocation                string            `json:"pickup_location,omitempty"`                  // Shipment pickup location for receiver
	PickupNote                    string            `json:"pickup_note,omitempty"`                      // Shipment pickup note for receiver
	CourierTrackingLink           string            `json:"courier_tracking_link,omitempty"`            // Official tracking URL of the courier (if any)
	CourierRedirectLink           string            `json:"courier_redirect_link,omitempty"`            // Delivery instructions (delivery date or address) can be modified by visiting the link if supported by a carrier.
	FirstAttemptedAt              string            `json:"first_attempted_at,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
	Checkpoints                   []Checkpoint      `json:"checkpoints,omitempty"`                      // Array of Hash describes the checkpoint information.
}

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 TrackingCouriers

type TrackingCouriers struct {
	Total    int       `json:"total"`    // Total number of matched couriers
	Tracking Tracking  `json:"tracking"` // Tracking describes the tracking information.
	Couriers []Courier `json:"couriers"` // A list of matched couriers based on tracking number format.
}

TrackingCouriers is the model describing an AfterShip couriers detect list

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 {
	Emails                 []string          `json:"emails,omitempty"`
	SMSes                  []string          `json:"smses,omitempty"`
	Title                  string            `json:"title,omitempty"`
	CustomerName           string            `json:"customer_name,omitempty"`
	DestinationCountryISO3 string            `json:"destination_country_iso3,omitempty"`
	OrderID                string            `json:"order_id,omitempty"`
	OrderIDPath            string            `json:"order_id_path,omitempty"`
	CustomFields           map[string]string `json:"custom_fields,omitempty"`
}

UpdateTrackingParams represents an update to Tracking details

Jump to

Keyboard shortcuts

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