target

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 23 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

target-go

Reads your own target.com order history: online orders, in-store purchases linked to your Target Circle account, and the card charges (invoices) of online orders. It comes as:

  • a Go library (github.com/daslicious/target-go, package target);
  • target-cli, which prints orders as JSON for any language or script;
  • an MCP server (target-cli mcp), so an AI assistant can look up what you bought;
  • PROTOCOL.md, field notes on Target's APIs, for writing a client in another language.

Target has no public API for this. target-go calls the JSON APIs target.com's own order pages use, with a login copied out of your browser, and renews that login on its own: it can run unattended (from cron, a server) for as long as Target keeps the login valid. It is unofficial, it breaks when Target changes those APIs, and it is meant for reading your own orders.

Status: in daily use since 2026-10-11 by itemize (a fork), which writes Target items into Monarch transactions.

Save a login

target-go needs a login no browser keeps using: Target replaces the refresh token on every renewal, and a browser renewing the same login would kill target-go's copy (and the other way round).

  1. In Chrome, open an Incognito window (Ctrl+Shift+N) and sign in at target.com.

  2. Open target.com/orders, then DevTools (F12) → Network, filter history, and reload.

  3. Right-click the history request marked {} (not the empty-box preflight) → Copy → Copy as cURL (bash).

  4. Save it (it is replayed first, and saved only if Target accepts it):

    xclip -o -selection clipboard | target-cli set-session              # Linux
    pbpaste | target-cli set-session                                     # macOS
    
  5. Close the Incognito window without signing out.

Logins are saved to ~/.config/target-go/session-<account>.json (mode 0600; -account NAME chooses another, TARGET_SESSION_DIR another directory, -session FILE or TARGET_SESSION a file). A fresh sign-in gives a 4-hour access token; each renewal gives 24 hours. Any command renews an expired token before it runs and saves the result right away.

CLI

go install github.com/daslicious/target-go/cmd/target-cli@latest
target-cli status                                # the saved login; no network
target-cli orders -days 30                       # history entries: id, date, total, item names
target-cli orders -since 2026-09-01 -type online -details   # with items, prices, payments, charges
target-cli order 912000000000001                 # one online order with its charges
target-cli order 6000-1234-0000-0001             # one in-store receipt
target-cli raw '/post_orders/v1/orders/history?page_number=1&page_size=10&order_purchase_type=ONLINE'
target-cli refresh                               # renew now (once the access token has expired)

Output is JSON on stdout; logs and warnings go to stderr (-v logs every request). Exit status: 0 ok, 1 error, 2 usage, 3 the login is missing or no longer accepted, 4 Target's bot protection answered (wait an hour or more). Requests are paced 3-5 seconds apart, so -details takes a few seconds per order.

order and orders -details print a Purchase:

{
  "id": "912000000000001", "kind": "online",          // or "store"
  "placed_at": "2026-10-10T17:02:11Z", "date": "2026-10-10",   // date: local calendar day
  "total": 64.18, "subtotal": 61.15, "tax": 4.03,
  "card_charged": 64.18,                               // less gift cards, coupons, after-total discounts
  "items": [{"tcin": "12345678", "name": "Gala Apples - 3lb Bag", "quantity": 2,
             "unit_price": 4.19, "price": 8.38, "product_type": "GROCERY"}],
  "payments": [{"type": "MASTERCARD", "sub_type": "APPLEPAY", "name": "Mastercard", "amount": 64.18, "card": true}],
  "charges": [                                         // online: one per card charge, oldest first
    {"invoice_id": "62000000000000001", "charged_at": "…", "date": "2026-10-10", "total": 41.27,
     "card_charged": 41.27, "payments": […],
     "lines": [{"tcin": "…", "name": "…", "quantity": 1, "amount": 21.54},   // after discounts, with tax
               {"tcin": "…", "name": "PAPER_BAG", "quantity": 2, "amount": 0.20, "fee": true}]}
  ]
}

An online order shipped in parts can be charged once per shipment, so match bank transactions to charges, not to total. In-store receipts are one charge, card_charged.

MCP server

target-cli mcp serves every saved login in the session directory over stdio, with three read-only tools:

Tool What
list_orders orders placed in a period (days, or since/until; kind: online, store or all) with totals and item names
get_order one order or receipt as a Purchase (above)
login_status the saved logins and when their tokens expire, without contacting Target

Every tool takes an optional account (a saved login's name). For Claude Code:

claude mcp add target-orders -- target-cli mcp

Other clients: run target-cli mcp as a stdio server, with TARGET_SESSION_DIR set if the logins aren't in ~/.config/target-go.

Library

client, err := target.Open(path)                     // a saved login; renewals are saved back to it
if err != nil { … }
if _, err := client.EnsureFresh(ctx, 15*time.Minute); err != nil { … }

summaries, complete, err := client.Summaries(ctx, target.ListOptions{Since: time.Now().AddDate(0, 0, -30)})
p, err := client.Purchase(ctx, summaries[0].ID)

// Target's own responses, for fields the Purchase view leaves out:
order, err := client.OnlineOrder(ctx, "912000000000001")
receipt, err := client.StoreOrder(ctx, "6000-1234-0000-0001")
invoices, err := client.Invoices(ctx, "912000000000001")   // invoices.Charges(): the charges, oldest first
raw, err := client.Get(ctx, "/post_orders/v1/912000000000001")

Logins: ParseSession reads a pasted cURL command or Cookie header, SaveSession/LoadSession store it, and Refresh renews it. A client made with Open re-reads the file before renewing and saves the renewal at once, under a lock (<file>.lock) that other programs using the same file take too, so they can share a login on one machine. With NewClient, saving is up to you.

Errors: ErrNotAuthenticated (no login, or Target rejected it, or it can't be renewed), ErrBlocked (bot protection or HTTP 429), ErrNotFound. Requests are paced with WithPacing (default 3 s plus up to 2 s of jitter); WithDumpDir saves every response.

Development

go test -race ./...

The test data is synthetic: Target's response shapes with made-up order numbers and amounts.

License

MIT; see LICENSE.

Documentation

Overview

Package target reads a person's own order history from target.com: online orders, in-store receipts linked to their Target Circle account, and the invoices (charges) of online orders. It calls the JSON APIs target.com's own order pages use, with a signed-in browser session copied out of DevTools, and renews that session without a browser. PROTOCOL.md describes the APIs.

Index

Constants

View Source
const (
	// DefaultBaseURL is the host target.com's order pages call.
	DefaultBaseURL = "https://api.target.com"
	// DefaultAPIKey is the public key target.com's web pages send as x-api-key (seen in 2026). A
	// saved session carries the key the browser actually used, which takes precedence.
	DefaultAPIKey = "ff457966e64d5e877fdbad070f276d18ecec4a01"
	// DefaultUserAgent is used only when the saved session has no user-agent header.
	DefaultUserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"
)
View Source
const (
	PurchaseOnline = "ONLINE"
	PurchaseStore  = "STORE"
)

Purchase types accepted by OrderHistory.

View Source
const (
	KindOnline = "online"
	KindStore  = "store"
)

Kinds of purchase.

View Source
const DefaultRefreshURL = "https://www.target.com/orders"

DefaultRefreshURL is the page whose load renews an expired login.

Variables

View Source
var (
	// ErrNotAuthenticated means Target rejected the saved login, or there is none.
	ErrNotAuthenticated = errors.New("target auth check failed")
	// ErrBlocked means Target's bot protection (PerimeterX/HUMAN) answered instead of the API, or
	// it rate-limited the client (HTTP 429).
	ErrBlocked = errors.New("target blocked the request (bot protection)")
	// ErrNotFound means Target answered 404.
	ErrNotFound = errors.New("target: not found")
)

Callers may match on these errors' messages (itemize's daily job greps for the first two to send alerts), so keep them stable.

Functions

func CleanText

func CleanText(s string) string

CleanText decodes HTML entities and strips markup from text Target sends (item descriptions).

func IsCardTender

func IsCardTender(paymentType, subType string) bool

IsCardTender reports whether a tender of this type and subtype is money charged to a card or bank account, which is what shows up on a statement. Not charged: gift cards, cash, manufacturer coupons (MANUFACTURERCOUPON) and adjustments such as the reusable-bag discount (GENERALLEDGERADJUSTMENT / BAGDISCOUNT).

func IsReceiptID

func IsReceiptID(id string) bool

IsReceiptID reports whether id is an in-store receipt id (digit groups joined by dashes) rather than an online order number (digits).

func ParseTime

func ParseTime(s string) time.Time

ParseTime reads Target's timestamps ("2026-02-01T19:31:36-06:00", "2026-02-01T19:31:36.000Z", "2026-02-01T19:31:36", "2026-02-01"). It returns the zero time if none fits. In-store receipts carry a Central time offset whatever the store's own time zone.

func SaveSession

func SaveSession(path string, s *Session) error

SaveSession writes the session atomically with mode 0600 (it holds login cookies).

func SessionPath

func SessionPath(dir, account string) (string, error)

SessionPath returns <dir>/session-<account>.json; account defaults to "default".

Types

type Charge

type Charge struct {
	InvoiceID   string       `json:"invoice_id"`
	ChargedAt   string       `json:"charged_at" jsonschema:"RFC 3339 as Target sent it"`
	Date        string       `json:"date" jsonschema:"YYYY-MM-DD in the local time zone"`
	Total       float64      `json:"total" jsonschema:"invoice total, including what coupons and gift cards paid"`
	CardCharged float64      `json:"card_charged"`
	Payments    []Payment    `json:"payments"`
	Lines       []ChargeLine `json:"lines"`
}

Charge is one invoice of an online order: one card charge.

type ChargeLine

type ChargeLine struct {
	TCIN     string  `json:"tcin,omitempty"`
	Name     string  `json:"name"`
	Quantity float64 `json:"quantity"`
	Amount   float64 `` /* 133-byte string literal not displayed */
	Fee      bool    `json:"fee,omitempty" jsonschema:"not an item of the order, e.g. the bag fee (PAPER_BAG)"`
}

ChargeLine is a line of a Charge.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client calls Target's order APIs with a saved Session. Requests are spaced out (3 s plus up to 2 s of random jitter by default) because Target's bot protection challenges clients that make quick bursts. Requests may be made from several goroutines (they are paced one at a time), but not while Refresh or EnsureFresh runs.

func NewClient

func NewClient(session *Session, opts ...ClientOption) *Client

NewClient creates a client for the given session.

func Open

func Open(path string, opts ...ClientOption) (*Client, error)

Open loads the session saved at path (see SaveSession) and returns a client tied to that file. Refresh and EnsureFresh then re-read the file first, in case another process renewed the login, and save a renewed login back at once. They hold a lock on the file (path + ".lock") meanwhile, so programs that share a session file on one machine don't renew with a refresh token another has already used up.

func (*Client) Check

func (c *Client) Check(ctx context.Context, rawURL string) error

Check replays a GET of rawURL (a target.com URL, normally the session's SourceURL) and returns nil if Target answered it. It reports ErrNotAuthenticated or ErrBlocked like the other calls.

func (*Client) EnsureFresh

func (c *Client) EnsureFresh(ctx context.Context, minLeft time.Duration) (bool, error)

EnsureFresh makes sure the access token has at least minLeft to run, renewing the login if not, and reports whether it renewed it. Target renews only an expired token, so a token with less than minLeft left is first waited out (at most minLeft plus 30 s). Renewed tokens last 24 hours.

func (*Client) Get

func (c *Client) Get(ctx context.Context, target string) (json.RawMessage, error)

Get fetches any JSON API on Target's API host with the session and returns the body as Target sent it. target is a path with an optional query ("/post_orders/v1/912000000000001") or a whole https URL on target.com. Errors are reported like the other calls'.

func (*Client) Invoice

func (c *Client) Invoice(ctx context.Context, orderNumber, invoiceID string) (*Invoice, error)

Invoice returns the lines and payments of one invoice of an online order.

func (*Client) Invoices

func (c *Client) Invoices(ctx context.Context, orderNumber string) (*InvoiceList, error)

Invoices lists the invoices of an online order: one per charge, plus any refunds. An order not charged yet has none (Target may answer 404 for it, as for an unknown order).

func (*Client) OnlineOrder

func (c *Client) OnlineOrder(ctx context.Context, orderNumber string) (*OnlineOrder, error)

OnlineOrder returns the details of an online order.

func (*Client) OrderHistory

func (c *Client) OrderHistory(ctx context.Context, purchaseType string, page, pageSize int) (*OrderHistoryResponse, error)

OrderHistory returns one page (1-based) of online or in-store order summaries, newest first.

func (*Client) Purchase

func (c *Client) Purchase(ctx context.Context, id string) (*Purchase, error)

Purchase fetches one order or receipt by id. For an online order it also reads the invoice of every charge: two requests plus one per charge, where a receipt takes one.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context) error

Refresh renews an expired access token the way a browser's page load does: it loads www.target.com/orders with the expired accessToken and a valid refreshToken, and keeps the new cookies only if they hold a signed-in token for the same account. Target renews only an expired token (see EnsureFresh). Anything else is reported as ErrNotAuthenticated or ErrBlocked, and the session is left alone.

The refresh token rotates on renewal, and every other copy of the login stops renewing. A client made with Open re-reads its session file first and saves the renewed login there at once, under the file's lock; with NewClient, the caller must save the session right away.

func (*Client) Session

func (c *Client) Session() *Session

Session returns the client's session. Renewals update it in place.

func (*Client) StoreOrder

func (c *Client) StoreOrder(ctx context.Context, receiptID string) (*StoreOrder, error)

StoreOrder returns the details of an in-store receipt.

func (*Client) Summaries

func (c *Client) Summaries(ctx context.Context, opts ListOptions) ([]Summary, bool, error)

Summaries lists the orders placed in the chosen period, newest first. It reads one history page per 10 orders of each kind. complete is false if it stopped at MaxPages.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client.

func WithBaseURL

func WithBaseURL(u string) ClientOption

WithBaseURL points the client at another host (tests).

func WithDumpDir

func WithDumpDir(dir string) ClientOption

WithDumpDir saves every response body under dir (for building test fixtures from real data). The files hold order details, so they're written 0600.

func WithHTTPClient

func WithHTTPClient(h *http.Client) ClientOption

WithHTTPClient replaces the HTTP client.

func WithLogger

func WithLogger(l *slog.Logger) ClientOption

WithLogger sets the logger.

func WithPacing

func WithPacing(minInterval, jitter time.Duration) ClientOption

WithPacing sets the minimum gap between requests and the extra random jitter added to it.

func WithRefreshURL

func WithRefreshURL(u string) ClientOption

WithRefreshURL points Refresh at another server (tests).

type HistoryLister

type HistoryLister interface {
	OrderHistory(ctx context.Context, purchaseType string, page, pageSize int) (*OrderHistoryResponse, error)
}

HistoryLister is what HistorySince pages through: a Client, or a stand-in in tests.

type Invoice

type Invoice struct {
	ID          string           `json:"id"`
	Type        string           `json:"type"`
	Date        string           `json:"date"`
	TotalAmount Money            `json:"total_amount"`
	Payments    []InvoicePayment `json:"payments"`
	Lines       []InvoiceLine    `json:"lines"`
}

Invoice is post_order_invoices/v1/orders/{order_number}/invoices/{id}: the lines one charge paid for. TotalAmount includes what coupons and gift cards paid.

type InvoiceLine

type InvoiceLine struct {
	OrderLineKey    string  `json:"order_line_key"`
	Quantity        float64 `json:"quantity"`
	UnitPrice       Money   `json:"unit_price"`
	TotalTax        Money   `json:"total_tax"`
	EffectiveAmount Money   `json:"effective_amount"`
	Item            Item    `json:"item"`
}

InvoiceLine is one line of an invoice. EffectiveAmount is what the line cost: after its discounts, with its shipping and its own tax. An invoice's effective amounts add up to its total. Item has only tcin and description; Target's product type is on the order line with the same key. A line whose key isn't on the order is a fee (the bag fee comes as a PAPER_BAG line).

type InvoiceList

type InvoiceList struct {
	Invoices []InvoiceSummary `json:"invoices"`
}

InvoiceList is post_order_invoices/v1/orders/{order_number}/invoices: one invoice per charge of an online order, plus refunds. An order shipped in several packages can be charged once per shipment, and each charge is a separate card transaction.

func (*InvoiceList) Charges

func (l *InvoiceList) Charges() []InvoiceSummary

Charges returns the invoices that charged the order (not its returns or refunds), oldest first.

type InvoicePayment

type InvoicePayment struct {
	Type         string `json:"type"`
	SubType      string `json:"sub_type"`
	SubTypeValue string `json:"sub_type_value"`
	TotalCharged Money  `json:"total_charged"`
}

InvoicePayment is one tender of an invoice.

func (InvoicePayment) IsCard

func (p InvoicePayment) IsCard() bool

IsCard reports whether the tender was charged to a card or account (see IsCardTender).

type InvoiceSummary

type InvoiceSummary struct {
	ID     string `json:"id"`
	Type   string `json:"type"`
	Date   string `json:"date"`
	Amount Money  `json:"amount"`
}

InvoiceSummary is one entry of an InvoiceList. Type is SHIPMENT for a charge (store pickups included); Amount is the invoice total.

type Item

type Item struct {
	TCIN                  string                `json:"tcin"`
	Description           string                `json:"description"`
	UnitPrice             Money                 `json:"unit_price"`
	ListPrice             Money                 `json:"list_price"`
	ProductClassification ProductClassification `json:"product_classification"`
}

Item is the product on an order line. Description can contain HTML entities (&#38;, &#8482;), and Target sometimes leaves the catalog fields (description, product type) out of a line.

func (Item) Name

func (i Item) Name() string

Name returns the description as plain text: HTML entities decoded, markup and extra spaces removed.

type ListOptions

type ListOptions struct {
	Since time.Time // placed at or after (required)
	Until time.Time // placed before; zero for no end
	// Kinds is KindOnline, KindStore or both (the default).
	Kinds []string
	// MaxPages caps the history pages read per kind (10 orders a page); default 10.
	MaxPages int
}

ListOptions selects orders for Summaries.

type Money

type Money float64

Money is a dollar amount that Target may send as a string ("12.34"), a number, or null.

func (*Money) UnmarshalJSON

func (m *Money) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts "12.34", "$12.34", "1,234.56", 12.34, "" and null.

type OnlineOrder

type OnlineOrder struct {
	OrderNumber string               `json:"order_number"`
	OrderDate   string               `json:"order_date"`
	OrderType   string               `json:"order_type"`
	Summary     Totals               `json:"summary"`
	Packages    []Package            `json:"packages"`
	Payments    []PaymentTransaction `json:"payments"`
}

OnlineOrder is post_orders/v1/{order_number}. Items are grouped by package (shipment).

func (*OnlineOrder) Lines

func (o *OnlineOrder) Lines() []OrderLine

Lines returns the order's item lines from every package Target didn't cancel.

type OrderHistoryResponse

type OrderHistoryResponse struct {
	TotalOrders int            `json:"total_orders"`
	TotalPages  int            `json:"total_pages"`
	Orders      []OrderSummary `json:"orders"`
}

OrderHistoryResponse is one page of order summaries: post_orders/v1/orders/history (online) or guest_order_aggregations/v1/order_history (in store).

type OrderLine

type OrderLine struct {
	OrderLineKey     string   `json:"order_line_key"`
	LineNumber       int      `json:"line_number"`
	Quantity         *float64 `json:"quantity"`
	OriginalQuantity float64  `json:"original_quantity"`
	Item             Item     `json:"item"`
}

OrderLine is one item line. In-store history entries have only original_quantity; the other responses have quantity as well.

func (OrderLine) Qty

func (l OrderLine) Qty() float64

Qty returns the line's quantity: quantity when present, else original_quantity, else 1. Lines in a cancelled package keep their quantity (see Package.Cancelled).

type OrderSummary

type OrderSummary struct {
	OrderNumber       string      `json:"order_number"`
	StoreReceiptID    string      `json:"store_receipt_id"`
	StoreID           string      `json:"store_id"`
	PlacedDate        string      `json:"placed_date"`
	OrderDate         string      `json:"order_date"`
	OrderPurchaseType string      `json:"order_purchase_type"`
	OrderType         string      `json:"order_type"`
	Summary           Totals      `json:"summary"`
	OrderLines        []OrderLine `json:"order_lines"`
	Packages          []Package   `json:"packages"`
}

OrderSummary is one order in a history list. The two lists differ: in-store entries have store_receipt_id, placed_date and order_lines; online entries have order_number, order_date and packages. Neither has item prices.

func HistorySince

func HistorySince(ctx context.Context, l HistoryLister, purchaseType string, since time.Time, pageSize, maxPages int) (orders []OrderSummary, complete bool, err error)

HistorySince reads order history pages (newest first) until a page reaches back past since, the history ends, or maxPages pages have been read. complete is false if it stopped at maxPages with more pages left. The last page can hold orders older than since; callers filter by date.

func (OrderSummary) Date

func (s OrderSummary) Date() string

Date returns when the order was placed, as Target sent it.

func (OrderSummary) ID

func (s OrderSummary) ID() string

ID returns the order number, or the receipt id for an in-store purchase.

func (OrderSummary) Lines

func (s OrderSummary) Lines() []OrderLine

Lines returns the order's item lines from either list format, without cancelled packages.

type Package

type Package struct {
	GroupingMetadata struct {
		Status string `json:"status"` // e.g. STAT_ORDER_PICKED_UP, STAT_DELIVERED, STAT_CANCELED
	} `json:"grouping_metadata"`
	Fulfillment struct {
		Status struct {
			Key string `json:"key"` // as GroupingMetadata.Status
		} `json:"status"`
	} `json:"fulfillment"`
	OrderLines []OrderLine `json:"order_lines"`
}

Package is one shipment, pickup or delivery of an online order.

func (Package) Cancelled

func (p Package) Cancelled() bool

Cancelled reports whether Target cancelled the package: the items it couldn't supply (out of stock, or a later date the guest declined) are moved to a package of their own with status STAT_CANCELED. Their quantity stays as ordered, but they weren't charged.

type Payment

type Payment struct {
	Type    string  `json:"type" jsonschema:"Target's tender type, e.g. TARGETDEBIT, VISA, MANUFACTURERCOUPON"`
	SubType string  `json:"sub_type,omitempty"`
	Name    string  `json:"name,omitempty" jsonschema:"the tender's name as target.com shows it"`
	Amount  float64 `json:"amount"`
	Card    bool    `json:"card" jsonschema:"charged to a card or account (not a gift card, coupon or discount)"`
}

Payment is a tender of a Purchase or Charge.

type PaymentTransaction

type PaymentTransaction struct {
	PaymentType string `json:"payment_type"`
	// The subtype is payment_sub_type on receipts and payment_subtype on online orders.
	PaymentSubType string `json:"payment_sub_type"`
	PaymentSubtype string `json:"payment_subtype"`
	// The name target.com shows: payment_sub_type_value on receipts, guest_display_payment_type
	// on online orders.
	SubTypeValue string `json:"payment_sub_type_value"`
	DisplayType  string `json:"guest_display_payment_type"`
	Amount       Money  `json:"amount"`
}

PaymentTransaction is one tender: payment_transactions on a receipt, payments on an online order. Besides cards, Target lists gift cards, manufacturer coupons and adjustments such as the reusable-bag discount as tenders; IsCard tells them apart.

func (PaymentTransaction) DisplayName

func (p PaymentTransaction) DisplayName() string

DisplayName returns the tender's name as target.com shows it ("Target Circle Debit Card").

func (PaymentTransaction) IsCard

func (p PaymentTransaction) IsCard() bool

IsCard reports whether the tender was charged to a card or account (see IsCardTender).

func (PaymentTransaction) SubType

func (p PaymentTransaction) SubType() string

SubType returns the tender's subtype from either response format.

type ProductClassification

type ProductClassification struct {
	ProductTypeName    string `json:"product_type_name"`
	ProductSubtypeName string `json:"product_subtype_name"`
}

ProductClassification is Target's own category for an item (e.g. GROCERY, APPAREL, HOME).

type Purchase

type Purchase struct {
	ID          string         `json:"id" jsonschema:"order number (online) or receipt id (in store)"`
	Kind        string         `json:"kind" jsonschema:"online or store"`
	PlacedAt    string         `json:"placed_at" jsonschema:"when it was placed, RFC 3339 as Target sent it"`
	Date        string         `json:"date" jsonschema:"the day it was placed, YYYY-MM-DD in the local time zone"`
	StoreID     string         `json:"store_id,omitempty" jsonschema:"Target store number (in store)"`
	Total       float64        `json:"total" jsonschema:"grand total in dollars"`
	Subtotal    float64        `json:"subtotal" jsonschema:"item prices before order discounts and tax"`
	Tax         float64        `json:"tax"`
	CardCharged float64        `` /* 132-byte string literal not displayed */
	Items       []PurchaseItem `json:"items"`
	Payments    []Payment      `json:"payments"`
	Charges     []Charge       `` /* 156-byte string literal not displayed */
}

Purchase is an online order or in-store receipt with its items, payments and, for an online order, its charges.

func PurchaseFromOnline

func PurchaseFromOnline(o *OnlineOrder, invoices []*Invoice) *Purchase

PurchaseFromOnline converts an online order and the invoices of its charges (none if it hasn't been charged yet, or they weren't read). CardCharged adds up what the invoices charged to cards; without invoices it's the total less what gift cards paid.

func PurchaseFromStore

func PurchaseFromStore(s *StoreOrder) *Purchase

PurchaseFromStore converts an in-store receipt.

type PurchaseItem

type PurchaseItem struct {
	TCIN           string  `json:"tcin,omitempty" jsonschema:"Target's item number"`
	Name           string  `json:"name"`
	Quantity       float64 `json:"quantity"`
	UnitPrice      float64 `json:"unit_price"`
	Price          float64 `json:"price" jsonschema:"unit price times quantity, before order discounts and tax"`
	ProductType    string  `json:"product_type,omitempty" jsonschema:"Target's category, e.g. GROCERY"`
	ProductSubtype string  `json:"product_subtype,omitempty"`
}

PurchaseItem is an item line of a Purchase. Cancelled lines are left out.

type Session

type Session struct {
	Cookie  string            `json:"cookie"`
	APIKey  string            `json:"api_key,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	SavedAt time.Time         `json:"saved_at"`
	// SourceURL is the request the session was copied from (a known-good URL to test it with).
	SourceURL string `json:"source_url,omitempty"`
	// RefreshedAt is when Refresh last renewed the login.
	RefreshedAt time.Time `json:"refreshed_at,omitempty"`
}

Session is a signed-in target.com browser session: its cookies, the x-api-key the page used and the browser's other request headers (user-agent etc.), so requests look like that browser's.

func LoadSession

func LoadSession(path string) (*Session, error)

LoadSession reads a saved session.

func ParseSession

func ParseSession(raw string, now time.Time) (*Session, error)

ParseSession builds a Session from what a person copies out of Chrome DevTools: either a whole "Copy as cURL (bash)" of an api.target.com request (best: it carries the cookies, the x-api-key and the browser's headers) or just the Cookie header value.

func (*Session) AccessTokenExpiry

func (s *Session) AccessTokenExpiry() (time.Time, bool)

AccessTokenExpiry reads the expiry of the accessToken cookie, a JWT that target.com's API accepts as the login. It reports false if there is no such cookie or it can't be read.

func (*Session) Account

func (s *Session) Account() string

Account returns the Target account (guest id) the login belongs to, from the accessToken or idToken cookie, or "" if neither can be read.

func (*Session) SignedIn

func (s *Session) SignedIn() bool

SignedIn reports whether the access token is a signed-in one; Target hands out anonymous guest tokens too.

type StoreOrder

type StoreOrder struct {
	StoreReceiptID      string               `json:"store_receipt_id"`
	StoreID             string               `json:"store_id"`
	OrderPurchaseDate   string               `json:"order_purchase_date"`
	OrderType           string               `json:"order_type"`
	GrandTotal          Money                `json:"grand_total"`
	Summary             Totals               `json:"summary"`
	OrderLines          []OrderLine          `json:"order_lines"`
	PaymentTransactions []PaymentTransaction `json:"payment_transactions"`
}

StoreOrder is guest_order_aggregations/v1/{receipt_id}/store_order_details, one in-store receipt.

type Summary

type Summary struct {
	ID        string        `json:"id" jsonschema:"order number (online) or receipt id (in store)"`
	Kind      string        `json:"kind" jsonschema:"online or store"`
	PlacedAt  string        `json:"placed_at" jsonschema:"when it was placed, RFC 3339 as Target sent it"`
	Date      string        `json:"date" jsonschema:"the day it was placed, YYYY-MM-DD in the local time zone"`
	Total     float64       `json:"total" jsonschema:"grand total in dollars"`
	OrderType string        `json:"order_type,omitempty" jsonschema:"Target's order type, e.g. Sales or STORES"`
	Items     []SummaryItem `json:"items"`
}

Summary is an order history entry. History entries carry no prices, and an in-store entry may list fewer items than its receipt.

func SummaryOf

func SummaryOf(s OrderSummary) Summary

SummaryOf converts a history entry.

type SummaryItem

type SummaryItem struct {
	TCIN     string  `json:"tcin,omitempty" jsonschema:"Target's item number"`
	Name     string  `json:"name"`
	Quantity float64 `json:"quantity"`
}

SummaryItem is an item of a Summary.

type Totals

type Totals struct {
	GrandTotal        Money `json:"grand_total"`
	TotalProductPrice Money `json:"total_product_price"`
	TotalTaxes        Money `json:"total_taxes"`
}

Totals is the pricing block of an order.

Directories

Path Synopsis
cmd
target-cli command
Command target-cli reads your own target.com order history and prints it as JSON, or serves it to AI assistants as an MCP server.
Command target-cli reads your own target.com order history and prints it as JSON, or serves it to AI assistants as an MCP server.

Jump to

Keyboard shortcuts

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