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
- Variables
- func CleanText(s string) string
- func IsCardTender(paymentType, subType string) bool
- func IsReceiptID(id string) bool
- func ParseTime(s string) time.Time
- func SaveSession(path string, s *Session) error
- func SessionPath(dir, account string) (string, error)
- type Charge
- type ChargeLine
- type Client
- func (c *Client) Check(ctx context.Context, rawURL string) error
- func (c *Client) EnsureFresh(ctx context.Context, minLeft time.Duration) (bool, error)
- func (c *Client) Get(ctx context.Context, target string) (json.RawMessage, error)
- func (c *Client) Invoice(ctx context.Context, orderNumber, invoiceID string) (*Invoice, error)
- func (c *Client) Invoices(ctx context.Context, orderNumber string) (*InvoiceList, error)
- func (c *Client) OnlineOrder(ctx context.Context, orderNumber string) (*OnlineOrder, error)
- func (c *Client) OrderHistory(ctx context.Context, purchaseType string, page, pageSize int) (*OrderHistoryResponse, error)
- func (c *Client) Purchase(ctx context.Context, id string) (*Purchase, error)
- func (c *Client) Refresh(ctx context.Context) error
- func (c *Client) Session() *Session
- func (c *Client) StoreOrder(ctx context.Context, receiptID string) (*StoreOrder, error)
- func (c *Client) Summaries(ctx context.Context, opts ListOptions) ([]Summary, bool, error)
- type ClientOption
- type HistoryLister
- type Invoice
- type InvoiceLine
- type InvoiceList
- type InvoicePayment
- type InvoiceSummary
- type Item
- type ListOptions
- type Money
- type OnlineOrder
- type OrderHistoryResponse
- type OrderLine
- type OrderSummary
- type Package
- type Payment
- type PaymentTransaction
- type ProductClassification
- type Purchase
- type PurchaseItem
- type Session
- type StoreOrder
- type Summary
- type SummaryItem
- type Totals
Constants ¶
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" )
const ( PurchaseOnline = "ONLINE" PurchaseStore = "STORE" )
Purchase types accepted by OrderHistory.
const ( KindOnline = "online" KindStore = "store" )
Kinds of purchase.
const DefaultRefreshURL = "https://www.target.com/orders"
DefaultRefreshURL is the page whose load renews an expired login.
Variables ¶
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 ¶
CleanText decodes HTML entities and strips markup from text Target sends (item descriptions).
func IsCardTender ¶
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 ¶
IsReceiptID reports whether id is an in-store receipt id (digit groups joined by dashes) rather than an online order number (digits).
func ParseTime ¶
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 ¶
SaveSession writes the session atomically with mode 0600 (it holds login cookies).
func SessionPath ¶
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 ¶
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 ¶
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 ¶
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) Invoices ¶
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 ¶
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 ¶
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 ¶
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) StoreOrder ¶
StoreOrder returns the details of an in-store receipt.
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 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 (&, ™), and Target sometimes leaves the catalog fields (description, product type) out of a line.
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 ¶
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.
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.
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 ¶
LoadSession reads a saved session.
func ParseSession ¶
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 ¶
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.
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.
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.
Source Files
¶
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. |