invoist

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 24 Imported by: 0

README

Invoist Go library

Go Reference

The official Go client for the Invoist API. Invoist reads invoices, receipts and bills and gives you back what is on them as structured data: the sender, the amounts, the due date, every line, and anything that looks worth a second look.

It needs Go 1.26 or newer and has no dependencies outside the standard library.

Install

go get github.com/invoisthq/invoist-go
import invoist "github.com/invoisthq/invoist-go"

Get a key

A business workspace creates API keys in the dashboard under Integrations. A household creates them under Settings, AI assistants. A key is shown only once, so keep it in your secret store. It is a server-side secret: never put it in a mobile app or a web page.

A business: read an invoice

client, err := invoist.New(os.Getenv("INVOIST_API_KEY"))
if err != nil {
	log.Fatal(err)
}
file, err := invoist.FileFromPath("invoice.pdf")
if err != nil {
	log.Fatal(err)
}
result, err := client.ExtractAndWait(ctx, file, nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(*result.Extraction.VendorName, *result.Extraction.TotalCents, *result.Extraction.Currency)

Extract uploads a PDF, PNG or JPEG and returns at once, while the reading happens in the background. ExtractAndWait also waits for the result, and WaitForExtraction waits for a document you uploaded earlier. A reading that failed is returned, not raised: check Extraction.Status and Extraction.ErrorMessage.

Uploading a file the workspace already has returns the existing document with Duplicate set, and costs nothing. For a file that is the same document but not the same bytes, pass an idempotency key: client.Extract(ctx, file, &invoist.ExtractParams{IdempotencyKey: "order-1042"}).

The other business methods are ExtractBatch, ListDocuments, GetDocument, GetDocumentFile, ListReviewQueue, ResolveReviewItem, ListCategories, GetUsage, GetStats, and ListWebhookEndpoints, CreateWebhookEndpoint and DeleteWebhookEndpoint.

A household: what is left to pay

client, err := invoist.New(os.Getenv("INVOIST_API_KEY"))
if err != nil {
	log.Fatal(err)
}
bills, err := client.Bills.List(ctx, &invoist.ListBillsParams{Paid: new(false)})
if err != nil {
	log.Fatal(err)
}
for _, b := range bills {
	fmt.Println(*b.VendorName, *b.DueDate, *b.TotalCents, *b.Currency)
}

A household's methods are grouped on client.Bills: List, Get, GetFile, Summary, Stats, MarkPaid and MarkUnpaid. Emails that wait for someone to approve their sender are on client.HeldEmails.List. Marking a bill paid needs a key the household allowed to do that (the bills:write scope).

Months are "YYYY-MM" strings; invoist.MonthOf(time.Now()) makes one, in your local time zone (invoist.DateOf does the same for dates).

What you get back

The types are generated from the API's OpenAPI description, so they match what the server sends. Fields use Go names, with the API's JSON names in their tags (TotalCents is total_cents).

  • Money is an int64 count of minor units: TotalCents: 48000 with Currency: "EUR" is €480.00. There are no floats, so nothing is rounded.
  • Dates are "YYYY-MM-DD" strings. Timestamps are time.Time.
  • A field the API can leave out or send as null is a pointer.
  • Fields a newer API adds are ignored, so an API update never breaks your build or your decoding.

Every method takes a context.Context first. Cancel it to stop a request, a wait between retries, or a WaitForExtraction loop.

Errors

Every failed call returns an *invoist.InvoistError:

_, err := client.GetDocument(ctx, id)
var apiErr *invoist.InvoistError
if errors.As(err, &apiErr) {
	switch {
	case apiErr.IsNotFound():
		// there is no such document
	case apiErr.IsAuthError():
		// the key is wrong or revoked
	case apiErr.IsPermissionError():
		// the key may not do this
	default:
		log.Printf("%s: %s (request %s)", apiErr.Code, apiErr.Message, apiErr.RequestID)
	}
}
Field Meaning
Status The HTTP status, or 0 when no response arrived
Code A stable code such as not_found or rate_limited. Branch on this
Message Text for people. It can change, so don't branch on it
RequestID The X-Request-Id header. Quote it when you contact support
Body The raw response body

The library sets its own codes when the API didn't send one: unexpected_response (the body wasn't an API error, such as a proxy's error page), network_error and timeout (no response arrived), and extraction_timeout (WaitForExtraction gave up).

A cancelled or expired context returns the context's own error (context.Canceled or context.DeadlineExceeded), not an InvoistError.

Retries and timeouts

A request that gets no response, a 429 or a 5xx is tried again, up to twice. The client waits as long as the response's Retry-After header says, or otherwise 0.5s, then 1s, then 2s and so on, varied by up to 20% and never more than 8s. If Retry-After asks for more than 60 seconds, the client doesn't wait: the call returns that error straight away. Other errors are not retried. Uploads are retried too: the API recognises a file it already has, so a retried upload never makes a second document.

client, err := invoist.New(key,
	invoist.WithMaxRetries(4),              // default 2; 0 turns retries off
	invoist.WithTimeout(30*time.Second),    // per attempt; default 60s
	invoist.WithBaseURL("http://localhost:8080"),
	invoist.WithHTTPClient(&http.Client{Transport: myTransport}),
)

Webhooks

Invoist can call your server when something happens, such as a document being read (invoist.EventExtractionCompleted). Register a URL with CreateWebhookEndpoint and keep the Secret it returns: it is shown only once.

Check every delivery with VerifyWebhook. Pass it the raw request body, exactly as received. Decoding the JSON and encoding it again changes the bytes, and the signature will no longer match.

http.HandleFunc("/webhooks/invoist", func(w http.ResponseWriter, r *http.Request) {
	payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
	if err != nil {
		http.Error(w, "unreadable body", http.StatusBadRequest)
		return
	}
	event, err := invoist.VerifyWebhook(payload, r.Header.Get(invoist.SignatureHeader), secret)
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	if event.Type == invoist.EventExtractionCompleted {
		var data struct {
			DocumentID string `json:"document_id"`
		}
		_ = event.DecodeData(&data)
		// fetch it with client.GetDocument(r.Context(), data.DocumentID)
	}
	w.WriteHeader(http.StatusNoContent)
})

VerifyWebhook rejects a delivery whose timestamp is more than five minutes from your clock, either way (invoist.WithTolerance changes that). It accepts any of several signatures, which is what you receive while a secret is being replaced. A delivery that fails returns an InvoistError with status 400 and the code invalid_signature or signature_too_old; answer it with a 400.

Each delivery also carries X-Invoist-Event (the event type) and X-Invoist-Delivery (an id that stays the same when a delivery is retried, so you can skip repeats).

Development

bash scripts/generate.sh   # regenerate the types from openapi.yaml
go vet ./... && go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 ./...
go test ./...

scripts/generate.sh reads testdata/openapi.yaml, the API's spec, and rewrites internal/generated/types.go and types_gen.go. Both are committed; running it again must change nothing. The tests run the shared conformance vectors in testdata/conformance. Live tests run only when INVOIST_API_KEY is set (and INVOIST_BASE_URL, to use another server); they only read.

MIT licensed. See LICENSE.

Documentation

Overview

Package invoist is the official Go client for the Invoist API, which reads invoices, receipts and bills and returns their contents as structured data.

Getting started

Create a client with an API key, then call its methods. Every method takes a context.Context first; cancel it to stop a request, a retry wait, or a WaitForExtraction poll.

client, err := invoist.New(os.Getenv("INVOIST_API_KEY"))
if err != nil {
	log.Fatal(err)
}
file, err := invoist.FileFromPath("invoice.pdf")
if err != nil {
	log.Fatal(err)
}
result, err := client.ExtractAndWait(ctx, file, nil)

A business workspace's methods (Extract, ListDocuments, ListReviewQueue, webhook endpoints, ...) are on *Client. A household's bills (Invoist Personal) are on Client.Bills and Client.HeldEmails:

unpaid, err := client.Bills.List(ctx, &invoist.ListBillsParams{Paid: new(false)})

Types

The request and response types are generated from the API's OpenAPI description and re-exported here (Document, Extraction, Bill, ...). Field names follow Go casing, with the API's JSON names in the struct tags. Money is always an int64 count of minor units, such as cents, never a float. Dates are "YYYY-MM-DD" strings and timestamps are time.Time. A field the API may leave out or send as null is a pointer. Fields a newer API adds are ignored.

Errors

Every failure the API reports, and every request that got no response, is an *InvoistError. Branch on its Code, or use its predicates:

var apiErr *invoist.InvoistError
if errors.As(err, &apiErr) && apiErr.IsNotFound() {
	// ...
}

A cancelled or expired context returns the context's own error instead.

Retries

A request that gets no response, a 429, or a 5xx is retried up to twice (WithMaxRetries changes that), waiting as long as the response's Retry-After header says, or otherwise 0.5s, 1s, 2s ... with ±20% jitter, at most 8s. A Retry-After above 60s is not waited for: the call returns that response's error at once. Uploads are retried too: the API recognises a file it already has, so a retried upload never creates a second document.

Webhooks

VerifyWebhook checks a delivery's X-Invoist-Signature header and returns the event. Pass it the raw request body, unparsed.

Example

A business workspace: upload an invoice and wait for what was read.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	client, err := invoist.New(os.Getenv("INVOIST_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	file, err := invoist.FileFromPath("invoice.pdf")
	if err != nil {
		log.Fatal(err)
	}
	result, err := client.ExtractAndWait(context.Background(), file, nil)
	if err != nil {
		log.Fatal(err)
	}
	x := result.Extraction
	if x.Status == invoist.ExtractionStatusDone && x.TotalCents != nil {
		fmt.Printf("%s: %d.%02d %s\n", deref(x.VendorName), *x.TotalCents/100, *x.TotalCents%100, deref(x.Currency))
	}
}

func deref(s *string) string {
	if s == nil {
		return ""
	}
	return *s
}

Index

Examples

Constants

View Source
const (
	// DefaultBaseURL is the production API.
	DefaultBaseURL = "https://api.invoi.st"
	// DefaultTimeout bounds each attempt of a request, including reading
	// the response. It is generous because uploads can be large.
	DefaultTimeout = 60 * time.Second
	// DefaultMaxRetries is how many times a retryable failure is retried,
	// so a call makes at most DefaultMaxRetries+1 attempts.
	DefaultMaxRetries = 2
)
View Source
const (
	// DefaultWaitTimeout is how long WaitForExtraction polls by default.
	DefaultWaitTimeout = 120 * time.Second
	// DefaultPollInterval is WaitForExtraction's default pause between polls.
	DefaultPollInterval = 2 * time.Second
)
View Source
const (
	// CodeUnexpectedResponse means the response was not the API's
	// {"error":{"code","message"}} envelope: a proxy's HTML page, an empty
	// body, or JSON this library could not read.
	CodeUnexpectedResponse = "unexpected_response"
	// CodeNetworkError means no response arrived (Status is 0).
	CodeNetworkError = "network_error"
	// CodeTimeout means the request took longer than the client's timeout
	// (Status is 0).
	CodeTimeout = "timeout"
	// CodeExtractionTimeout means WaitForExtraction gave up before the
	// extraction finished (Status is 0).
	CodeExtractionTimeout = "extraction_timeout"
	// CodeInvalidSignature means a webhook's signature header was missing,
	// malformed, or did not match (Status is 400).
	CodeInvalidSignature = "invalid_signature"
	// CodeSignatureTooOld means a webhook's timestamp is outside the
	// allowed tolerance (Status is 400).
	CodeSignatureTooOld = "signature_too_old"
	// CodeInvalidPayload means a correctly signed webhook body is not a
	// JSON event (Status is 400).
	CodeInvalidPayload = "invalid_payload"
)

Error codes the library itself sets on an *InvoistError, alongside the codes the API sends in its error envelope.

View Source
const (
	BillKindCreditNote          = generated.BillKindCreditNote
	BillKindDebtCollection      = generated.BillKindDebtCollection
	BillKindInvoice             = generated.BillKindInvoice
	BillKindPaymentConfirmation = generated.BillKindPaymentConfirmation
	BillKindReceipt             = generated.BillKindReceipt
	BillKindReminder            = generated.BillKindReminder
)

The values of BillKind the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	BillLetterKindDebtCollection = generated.BillLetterKindDebtCollection
	BillLetterKindReminder       = generated.BillLetterKindReminder
)

The values of BillLetterKind the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	DocumentApprovalStateApproved         = generated.DocumentApprovalStateApproved
	DocumentApprovalStateChangesRequested = generated.DocumentApprovalStateChangesRequested
	DocumentApprovalStateDraft            = generated.DocumentApprovalStateDraft
	DocumentApprovalStateReady            = generated.DocumentApprovalStateReady
)

The values of DocumentApprovalState the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	DocumentSourceAPI       = generated.DocumentSourceAPI
	DocumentSourceDashboard = generated.DocumentSourceDashboard
	DocumentSourceEmail     = generated.DocumentSourceEmail
	DocumentSourceSandbox   = generated.DocumentSourceSandbox
	DocumentSourceStorage   = generated.DocumentSourceStorage
)

The values of DocumentSource the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	DocumentStatusDone       = generated.DocumentStatusDone
	DocumentStatusFailed     = generated.DocumentStatusFailed
	DocumentStatusPending    = generated.DocumentStatusPending
	DocumentStatusProcessing = generated.DocumentStatusProcessing
)

The values of DocumentStatus the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	ExtractionCategorySourceMemory = generated.ExtractionCategorySourceMemory
	ExtractionCategorySourceModel  = generated.ExtractionCategorySourceModel
	ExtractionCategorySourceUser   = generated.ExtractionCategorySourceUser
)

The values of ExtractionCategorySource the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	ExtractionDocumentKindCreditNote          = generated.ExtractionDocumentKindCreditNote
	ExtractionDocumentKindDebtCollection      = generated.ExtractionDocumentKindDebtCollection
	ExtractionDocumentKindInvoice             = generated.ExtractionDocumentKindInvoice
	ExtractionDocumentKindPaymentConfirmation = generated.ExtractionDocumentKindPaymentConfirmation
	ExtractionDocumentKindReceipt             = generated.ExtractionDocumentKindReceipt
	ExtractionDocumentKindReminder            = generated.ExtractionDocumentKindReminder
)

The values of ExtractionDocumentKind the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	ExtractionJobStatusFailed    = generated.ExtractionJobStatusFailed
	ExtractionJobStatusQueued    = generated.ExtractionJobStatusQueued
	ExtractionJobStatusRunning   = generated.ExtractionJobStatusRunning
	ExtractionJobStatusSucceeded = generated.ExtractionJobStatusSucceeded
)

The values of ExtractionJobStatus the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	ExtractionStatusDone    = generated.ExtractionStatusDone
	ExtractionStatusFailed  = generated.ExtractionStatusFailed
	ExtractionStatusPending = generated.ExtractionStatusPending
)

The values of ExtractionStatus the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	FraudIndicatorSeverityHigh   = generated.FraudIndicatorSeverityHigh
	FraudIndicatorSeverityLow    = generated.FraudIndicatorSeverityLow
	FraudIndicatorSeverityMedium = generated.FraudIndicatorSeverityMedium
)

The values of FraudIndicatorSeverity the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	FraudIndicatorSourceEngine = generated.FraudIndicatorSourceEngine
	FraudIndicatorSourceModel  = generated.FraudIndicatorSourceModel
)

The values of FraudIndicatorSource the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	HeldEmailHoldReasonNewSender        = generated.HeldEmailHoldReasonNewSender
	HeldEmailHoldReasonNoPlan           = generated.HeldEmailHoldReasonNoPlan
	HeldEmailHoldReasonQuotaUsed        = generated.HeldEmailHoldReasonQuotaUsed
	HeldEmailHoldReasonUnverifiedSender = generated.HeldEmailHoldReasonUnverifiedSender
)

The values of HeldEmailHoldReason the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	HeldEmailSenderFailed   = generated.HeldEmailSenderFailed
	HeldEmailSenderUnknown  = generated.HeldEmailSenderUnknown
	HeldEmailSenderVerified = generated.HeldEmailSenderVerified
)

The values of HeldEmailSender the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	QualityIssuesBlurry      = generated.QualityIssuesBlurry
	QualityIssuesCropped     = generated.QualityIssuesCropped
	QualityIssuesHandwritten = generated.QualityIssuesHandwritten
	QualityIssuesLowContrast = generated.QualityIssuesLowContrast
	QualityIssuesPartial     = generated.QualityIssuesPartial
	QualityIssuesRotated     = generated.QualityIssuesRotated
)

The values of QualityIssues the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	ReviewReasonAmountAnomaly      = generated.ReviewReasonAmountAnomaly
	ReviewReasonAmountOverLimit    = generated.ReviewReasonAmountOverLimit
	ReviewReasonBankDetailsChanged = generated.ReviewReasonBankDetailsChanged
	ReviewReasonDuplicate          = generated.ReviewReasonDuplicate
	ReviewReasonLowConfidence      = generated.ReviewReasonLowConfidence
	ReviewReasonMissingPoNumber    = generated.ReviewReasonMissingPoNumber
	ReviewReasonPoorQuality        = generated.ReviewReasonPoorQuality
	ReviewReasonTotalMismatch      = generated.ReviewReasonTotalMismatch
	ReviewReasonUnusualVendor      = generated.ReviewReasonUnusualVendor
)

The values of ReviewReason the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	ReviewStatusDismissed = generated.ReviewStatusDismissed
	ReviewStatusPending   = generated.ReviewStatusPending
	ReviewStatusResolved  = generated.ReviewStatusResolved
)

The values of ReviewStatus the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	StatsOverviewPlanGrowth  = generated.StatsOverviewPlanGrowth
	StatsOverviewPlanScale   = generated.StatsOverviewPlanScale
	StatsOverviewPlanStarter = generated.StatsOverviewPlanStarter
)

The values of StatsOverviewPlan the API documents. Compare against these; a newer API may send a value this version does not list.

View Source
const (
	// SignatureHeader carries the signature VerifyWebhook checks:
	// "t=<unix seconds>,v1=<hex HMAC-SHA256>".
	SignatureHeader = "X-Invoist-Signature"
	// EventHeader carries the event's type, such as "extraction.completed".
	EventHeader = "X-Invoist-Event"
	// DeliveryHeader carries an id for this delivery attempt, the same on
	// every retry of one delivery: use it to ignore repeats.
	DeliveryHeader = "X-Invoist-Delivery"
)

Webhook request headers.

View Source
const DefaultWebhookTolerance = 5 * time.Minute

DefaultWebhookTolerance is how far a webhook's timestamp may be from the current time, either way, before VerifyWebhook rejects it.

View Source
const Version = "1.0.1"

Version is this library's version. It is sent in the User-Agent header and matches the module's release tag (v1.0.0 is Version "1.0.0").

Variables

View Source
var ErrMissingAPIKey = errors.New("invoist: an API key is required (create one in the Invoist dashboard and pass it to invoist.New)")

ErrMissingAPIKey is returned by New when the API key is empty.

Functions

func DateOf

func DateOf(t time.Time) string

DateOf formats t's date in local time as the API's "YYYY-MM-DD", for BillsSummaryParams.Today.

func MonthOf

func MonthOf(t time.Time) string

MonthOf formats t's year and month in local time as the API's "YYYY-MM", for ListBillsParams.Month and BillsStatsParams.Month.

Example

MonthOf formats a time for the month filters.

package main

import (
	"fmt"
	"time"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	fmt.Println(invoist.MonthOf(time.Date(2026, time.October, 31, 0, 0, 0, 0, time.UTC)))
}
Output:
2026-10

Types

type BatchResult

BatchResult is what ExtractBatch returns: one entry per file, in the order the files were given, and how many were accepted and rejected.

type BatchResultItem

type BatchResultItem = generated.BatchResultItem

BatchResultItem is the API's BatchResultItem schema. One file's outcome from POST /v1/extract/batch. A rejected file carries `error` and omits the document fields; an accepted one carries the document fields and omits `error`.

type Bill

type Bill = generated.Bill

Bill is the API's Bill schema. One bill in a household's list.

type BillChain

type BillChain = generated.BillDetail_Chain

BillChain is the API's BillDetail.Chain schema. The bill and its letters, when it has any.

type BillChainMember

type BillChainMember = generated.BillChainMember

BillChainMember is the API's BillChainMember schema. One document of a bill's chain (the bill and its letters).

type BillDetail

type BillDetail = generated.BillDetail

BillDetail is the API's BillDetail schema. One bill with everything read from it.

type BillKind

type BillKind = generated.BillKind

BillKind is the API's BillKind schema. What a document is. Null is an ordinary invoice.

type BillLetter

type BillLetter = generated.BillLetter

BillLetter is the API's BillLetter schema. The newest reminder or collection letter about a bill, which says what is owed now.

type BillLetterKind

type BillLetterKind = generated.BillLetterKind

BillLetterKind is the API's BillLetter.Kind schema.

type BillRecord

type BillRecord = generated.BillRecord

BillRecord is the API's BillRecord schema. The household's own record on a bill.

type BillRelated

type BillRelated = generated.BillRelated

BillRelated is the API's BillRelated schema. The bill a letter or receipt is linked to, and how.

type BillWarning

type BillWarning = generated.BillChainMember_Warnings

BillWarning is the API's BillChainMember.Warnings schema.

type BillsDue

type BillsDue = generated.BillsDue

BillsDue is the API's BillsDue schema.

type BillsService

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

BillsService holds a household's bills (Invoist Personal). Reach it as Client.Bills. Every method needs the bills:read scope, and MarkPaid and MarkUnpaid also bills:write; a business workspace's key gets an *InvoistError with status 403 and code household_feature.

func (*BillsService) Get

func (s *BillsService) Get(ctx context.Context, id string) (*BillDetail, error)

Get fetches one bill with everything read from it, its open warnings, the household's record and its letters (GET /v1/bills/{id}).

func (*BillsService) GetFile

func (s *BillsService) GetFile(ctx context.Context, id string) (*Download, error)

GetFile downloads a bill's original file, byte for byte (GET /v1/bills/{id}/file).

func (*BillsService) List

func (s *BillsService) List(ctx context.Context, params *ListBillsParams) ([]Bill, error)

List lists the household's bills; unpaid bills come soonest-due first (GET /v1/bills). A reminder or collection letter about a bill is folded into that bill (see Bill.Letter). params may be nil.

Example

A household: list the bills still to pay this month.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	client, err := invoist.New(os.Getenv("INVOIST_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	bills, err := client.Bills.List(context.Background(), &invoist.ListBillsParams{
		Paid:  new(false),
		Month: invoist.MonthOf(time.Now()),
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, b := range bills {
		fmt.Println(deref(b.VendorName), deref(b.DueDate), *b.TotalCents, deref(b.Currency))
	}
}

func deref(s *string) string {
	if s == nil {
		return ""
	}
	return *s
}

func (*BillsService) MarkPaid

func (s *BillsService) MarkPaid(ctx context.Context, id string) (*BillRecord, error)

MarkPaid records a bill and its letters as paid by the key's creator, and returns the household's record (POST /v1/bills/{id}/paid, scope bills:write).

Example

Mark a bill paid once it is paid.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	client, err := invoist.New(os.Getenv("INVOIST_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	record, err := client.Bills.MarkPaid(context.Background(), "01a19812-0000-7000-8000-0000000000aa")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("paid at", record.PaidAt)
}

func (*BillsService) MarkUnpaid

func (s *BillsService) MarkUnpaid(ctx context.Context, id string) (*BillRecord, error)

MarkUnpaid records a bill as not paid, and returns the household's record (DELETE /v1/bills/{id}/paid, scope bills:write).

func (*BillsService) Stats

func (s *BillsService) Stats(ctx context.Context, params *BillsStatsParams) (*BillsStats, error)

Stats returns a month at a glance: totals billed and paid per currency, the twelve months up to it, and the biggest senders (GET /v1/bills/stats). params may be nil.

func (*BillsService) Summary

func (s *BillsService) Summary(ctx context.Context, params *BillsSummaryParams) (*BillsSummary, error)

Summary says what there is to pay: how many bills are unpaid and overdue, and what falls due soon, per currency (GET /v1/bills/summary). params may be nil.

type BillsStats

type BillsStats = generated.BillsStats

BillsStats is the API's BillsStats schema.

type BillsStatsMonth

type BillsStatsMonth = generated.BillsStats_Trend

BillsStatsMonth is the API's BillsStats.Trend schema.

type BillsStatsParams

type BillsStatsParams struct {
	// Month is the month to report, "YYYY-MM". Empty is the current month.
	// MonthOf formats a time.Time.
	Month string `query:"month"`
	// Sender narrows the totals and the trend to one sender.
	Sender string `query:"sender"`
}

BillsStatsParams are the options of Bills.Stats.

type BillsStatsSender

type BillsStatsSender = generated.BillsStats_Senders

BillsStatsSender is the API's BillsStats.Senders schema.

type BillsStatsTopSender

type BillsStatsTopSender = generated.BillsStats_TopSenders

BillsStatsTopSender is the API's BillsStats.TopSenders schema.

type BillsStatsTotal

type BillsStatsTotal = generated.BillsStats_Totals

BillsStatsTotal is the API's BillsStats.Totals schema.

type BillsSummary

type BillsSummary = generated.BillsSummary

BillsSummary is the API's BillsSummary schema.

type BillsSummaryParams

type BillsSummaryParams struct {
	// Today is the household's own date, "YYYY-MM-DD", which must be within
	// two days of the server's. Empty uses the server's. DateOf formats a
	// time.Time.
	Today string `query:"today"`
	// Days is how far ahead "due soon" reaches. The API defaults to 30.
	Days int `query:"days"`
}

BillsSummaryParams are the options of Bills.Summary.

type Category

type Category = generated.Category

Category is the API's Category schema.

type Client

type Client struct {
	// Bills holds a household's bills (Invoist Personal). The key needs
	// the bills:read scope, and bills:write to mark bills paid.
	Bills *BillsService
	// HeldEmails holds emails forwarded to a household that wait for a
	// person to approve their sender.
	HeldEmails *HeldEmailsService
	// contains filtered or unexported fields
}

Client calls the Invoist API. Create one with New and reuse it: a *Client is safe for concurrent use by multiple goroutines.

Methods for a business workspace (documents, extraction, the review queue, webhooks) are on Client itself; a household's bills are on Client.Bills and Client.HeldEmails.

func New

func New(apiKey string, opts ...Option) (*Client, error)

New returns a Client that authenticates with apiKey: a workspace or household API key (inv_sk_...) or an OAuth access token (inv_at_...). It returns ErrMissingAPIKey when apiKey is empty, and an error when WithBaseURL was given something that is not an absolute URL.

Example

Point the client elsewhere and tune its retries.

package main

import (
	"errors"
	"fmt"
	"net/http"
	"time"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	client, err := invoist.New("inv_sk_...",
		invoist.WithBaseURL("http://localhost:8080"),
		invoist.WithTimeout(30*time.Second),
		invoist.WithMaxRetries(4),
		invoist.WithHTTPClient(&http.Client{Transport: http.DefaultTransport}),
	)
	fmt.Println(client != nil, err)

	_, err = invoist.New("")
	fmt.Println(errors.Is(err, invoist.ErrMissingAPIKey))
}
Output:
true <nil>
true

func (*Client) CreateWebhookEndpoint

func (c *Client) CreateWebhookEndpoint(ctx context.Context, params CreateWebhookEndpointParams) (*WebhookEndpointWithSecret, error)

CreateWebhookEndpoint registers a URL to receive signed events (POST /v1/webhook-endpoints, scope webhooks:manage). The result's Secret, which VerifyWebhook needs, is returned only this once: store it.

func (*Client) DeleteWebhookEndpoint

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

DeleteWebhookEndpoint removes a webhook endpoint; deliveries to it stop at once (DELETE /v1/webhook-endpoints/{id}, scope webhooks:manage).

func (*Client) Extract

func (c *Client) Extract(ctx context.Context, file File, params *ExtractParams) (*ExtractResult, error)

Extract uploads a PDF, PNG or JPEG (up to 20 MB) for reading (POST /v1/extract, scope documents:write). It returns once the file is stored, usually with the extraction still pending; use WaitForExtraction, ExtractAndWait, or the extraction.completed webhook for the result.

Uploading bytes this workspace already extracted returns the existing document with Duplicate set, and bills nothing, so retrying an upload is safe. params may be nil.

func (*Client) ExtractAndWait

func (c *Client) ExtractAndWait(ctx context.Context, file File, params *ExtractAndWaitParams) (*ExtractResult, error)

ExtractAndWait uploads a file and waits for its extraction: Extract followed by WaitForExtraction. params may be nil.

func (*Client) ExtractBatch

func (c *Client) ExtractBatch(ctx context.Context, files []File) (*BatchResult, error)

ExtractBatch uploads up to 10 files in one request (POST /v1/extract/batch, scope documents:write). Each file goes through the same checks as Extract, and one bad file does not fail the others: look at each entry of Results, which are in the order given.

func (*Client) GetDocument

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

GetDocument fetches a document with its extraction and review items (GET /v1/documents/{id}, scope documents:read).

func (*Client) GetDocumentFile

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

GetDocumentFile downloads a document's original file, byte for byte (GET /v1/documents/{id}/file, scope documents:read).

func (*Client) GetStats

func (c *Client) GetStats(ctx context.Context) (*StatsOverview, error)

GetStats returns the workspace's document counts and plan allowance (GET /v1/stats/overview, scope stats:read).

func (*Client) GetUsage

func (c *Client) GetUsage(ctx context.Context) (*Usage, error)

GetUsage returns the current billing period's usage (GET /v1/usage, scope usage:read).

func (*Client) ListCategories

func (c *Client) ListCategories(ctx context.Context) ([]Category, error)

ListCategories lists the workspace's spend categories (GET /v1/categories, scope workspace:read).

func (*Client) ListDocuments

func (c *Client) ListDocuments(ctx context.Context, params *ListDocumentsParams) ([]DocumentListItem, error)

ListDocuments lists the workspace's documents, newest first (GET /v1/documents, scope documents:read). params may be nil.

func (*Client) ListReviewQueue

func (c *Client) ListReviewQueue(ctx context.Context, params *ListReviewQueueParams) ([]ReviewQueueListItem, error)

ListReviewQueue lists the items flagged for a person to check (GET /v1/review-queue, scope review:read). params may be nil.

func (*Client) ListWebhookEndpoints

func (c *Client) ListWebhookEndpoints(ctx context.Context) (*WebhookEndpointList, error)

ListWebhookEndpoints lists the registered webhook endpoints and the event types the API can send (GET /v1/webhook-endpoints, scope webhooks:manage).

func (*Client) ResolveReviewItem

func (c *Client) ResolveReviewItem(ctx context.Context, id string, status ReviewStatus) (*ReviewQueueItem, error)

ResolveReviewItem closes a review item as ReviewStatusResolved or ReviewStatusDismissed (POST /v1/review-queue/{id}/resolve, scope review:write). An empty status means resolved.

func (*Client) WaitForExtraction

func (c *Client) WaitForExtraction(ctx context.Context, documentID string, params *WaitParams) (*Extraction, error)

WaitForExtraction polls GetDocument until the document's extraction is no longer pending, and returns it. A failed extraction is returned, not raised: it is an answer about the document (see its ErrorMessage). Past the timeout it returns an *InvoistError with status 0 and code extraction_timeout. params may be nil.

type CreateWebhookEndpointParams

type CreateWebhookEndpointParams struct {
	// URL is the HTTP or HTTPS address that receives the events. Required.
	URL string `json:"url"`
	// Description is a note for people reading the endpoint list.
	Description string `json:"description,omitempty"`
	// Events are the event types to send, such as EventExtractionCompleted.
	// Empty, or []EventType{"*"}, subscribes to every event.
	Events []EventType `json:"events,omitempty"`
}

CreateWebhookEndpointParams describes a webhook endpoint to register.

type CustomValue

type CustomValue = generated.CustomValue

CustomValue is the API's CustomValue schema.

type Discovery

type Discovery = generated.Discovery

Discovery is the API's Discovery schema.

type Document

type Document = generated.Document

Document is the API's Document schema.

type DocumentApproval

type DocumentApproval = generated.DocumentApproval

DocumentApproval is the API's DocumentApproval schema. Sign-off state. Separate from `status`, which tracks extraction: this is a person's judgement, that is the machine's progress. Always "draft" unless the workspace has an approval mode switched on.

type DocumentApprovalState

type DocumentApprovalState = generated.DocumentApprovalState

DocumentApprovalState is the API's DocumentApproval.State schema.

type DocumentDetail

DocumentDetail is what GetDocument returns: the document, its extraction (nil until one exists), the job producing it, and its review items.

type DocumentListItem

type DocumentListItem = generated.DocumentListItem

DocumentListItem is the API's DocumentListItem schema. A document plus a flat summary of its latest extraction.

type DocumentSource

type DocumentSource = generated.DocumentSource

DocumentSource is the API's DocumentSource schema. How the document arrived.

type DocumentStatus

type DocumentStatus = generated.DocumentStatus

DocumentStatus is the API's DocumentStatus schema.

type Download

type Download struct {
	// Data is the file's bytes, exactly as uploaded.
	Data []byte
	// ContentType is the stored media type, such as "application/pdf".
	ContentType string
	// Filename is the name from the Content-Disposition header, when the
	// API sent one.
	Filename string
}

Download is a file as the API stored it.

type ErrorDetail

type ErrorDetail = generated.ErrorDetail

ErrorDetail is the API's ErrorDetail schema.

type EventType

type EventType string

EventType is the type of a webhook event.

const (
	// EventDocumentCreated: a document was stored.
	EventDocumentCreated EventType = "document.created"
	// EventExtractionCompleted: a document was read.
	EventExtractionCompleted EventType = "extraction.completed"
	// EventExtractionFailed: a document could not be read.
	EventExtractionFailed EventType = "extraction.failed"
	// EventReviewItemCreated: something was flagged for a person to check.
	EventReviewItemCreated EventType = "review_item.created"
	// EventReviewItemResolved: a review item was resolved or dismissed.
	EventReviewItemResolved EventType = "review_item.resolved"
	// EventDocumentRequestFulfilled: someone sent a document that was asked for.
	EventDocumentRequestFulfilled EventType = "document_request.fulfilled"
	// EventAll subscribes a webhook endpoint to every event type, in
	// CreateWebhookEndpointParams.Events. No event has this type.
	EventAll EventType = "*"
)

The event types the API sends.

type ExtractAndWaitParams

type ExtractAndWaitParams struct {
	// IdempotencyKey is passed to Extract; see ExtractParams.
	IdempotencyKey string
	// Timeout is how long to poll for the result; see WaitParams.
	Timeout time.Duration
	// PollInterval is the pause between polls; see WaitParams.
	PollInterval time.Duration
}

ExtractAndWaitParams are the options of ExtractAndWait.

type ExtractParams

type ExtractParams struct {
	// IdempotencyKey names one logical upload. Sending the same key again
	// replays the first response instead of creating a second document,
	// which covers re-sending byte-different copies of the same file
	// (identical bytes are recognised without a key). Reusing a key with a
	// different file fails with status 422. Keys expire after 24 hours.
	IdempotencyKey string
}

ExtractParams are the options of Extract.

type ExtractResult

type ExtractResult struct {
	// Document is the stored document.
	Document Document `json:"document"`
	// Extraction is the reading of the document. After Extract it is
	// usually still pending (a test-mode key answers "done" at once);
	// after ExtractAndWait it is done or failed. It can be nil on a
	// duplicate whose extraction no longer exists.
	Extraction *Extraction `json:"extraction,omitempty"`
	// Duplicate is true when these exact bytes were already extracted in
	// this workspace: Document is the existing one and nothing was billed.
	Duplicate bool `json:"duplicate"`
}

ExtractResult is what Extract and ExtractAndWait return.

type Extraction

type Extraction = generated.Extraction

Extraction is the API's Extraction schema.

type ExtractionCategorySource

type ExtractionCategorySource = generated.ExtractionCategorySource

ExtractionCategorySource is the API's ExtractionCategorySource schema. Who chose the category.

type ExtractionDocumentKind

type ExtractionDocumentKind = generated.ExtractionDocumentKind

ExtractionDocumentKind is the API's ExtractionDocumentKind schema. What the document is. Null when the reader could not tell, and on documents read before this field existed; treat null as an ordinary invoice.

type ExtractionJob

type ExtractionJob = generated.ExtractionJob

ExtractionJob is the API's ExtractionJob schema. Progress of the background run that produces an extraction. Reading a document is queued work, so this reports how that work is going: whether it is waiting, running, finished, or has given up.

type ExtractionJobStatus

type ExtractionJobStatus = generated.ExtractionJobStatus

ExtractionJobStatus is the API's ExtractionJobStatus schema. `queued` is waiting for a worker, which includes waiting out the backoff between attempts. `failed` means every attempt was used or the failure was one that retrying cannot fix.

type ExtractionStatus

type ExtractionStatus = generated.ExtractionStatus

ExtractionStatus is the API's ExtractionStatus schema.

type File

type File struct {
	// Filename is the name the document is stored under, such as
	// "invoice.pdf". Empty becomes "upload".
	Filename string
	// ContentType is the file's media type, such as "application/pdf".
	// Empty means guess it from the filename's extension. The API checks
	// the bytes themselves either way and accepts PDF, PNG and JPEG.
	ContentType string
	// Data is the file's contents.
	Data []byte
}

File is a document to upload: its bytes, the name it is stored under, and optionally its content type. Build one with a struct literal or with FileFromBytes, FileFromPath or FileFromReader.

func FileFromBytes

func FileFromBytes(filename string, data []byte) File

FileFromBytes returns a File for data, named filename.

func FileFromPath

func FileFromPath(path string) (File, error)

FileFromPath reads the file at path, named after its last element.

func FileFromReader

func FileFromReader(filename string, r io.Reader) (File, error)

FileFromReader reads r to the end and returns it as a File named filename. The bytes are held in memory so a retry can send them again.

type FraudIndicator

type FraudIndicator = generated.FraudIndicator

FraudIndicator is the API's FraudIndicator schema.

type FraudIndicatorSeverity

type FraudIndicatorSeverity = generated.FraudIndicatorSeverity

FraudIndicatorSeverity is the API's FraudIndicator.Severity schema.

type FraudIndicatorSource

type FraudIndicatorSource = generated.FraudIndicatorSource

FraudIndicatorSource is the API's FraudIndicatorSource schema. `model` when read off the page; `engine` when derived from workspace history.

type HeldEmail

type HeldEmail = generated.HeldEmail

HeldEmail is the API's HeldEmail schema. An email forwarded to the household that waits for approval.

type HeldEmailFile

type HeldEmailFile = generated.HeldEmailFile

HeldEmailFile is the API's HeldEmailFile schema.

type HeldEmailHoldReason

type HeldEmailHoldReason = generated.HeldEmailHoldReason

HeldEmailHoldReason is the API's HeldEmailHoldReason schema. Why it waits. The sender reasons wait for a person; the plan reasons clear by themselves.

type HeldEmailSender

type HeldEmailSender = generated.HeldEmailSender

HeldEmailSender is the API's HeldEmailSender schema. What the mail server found about the From address.

type HeldEmailsService

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

HeldEmailsService holds the emails forwarded to a household that wait for a person to approve their sender, or for a plan. Reach it as Client.HeldEmails. It needs the bills:read scope.

func (*HeldEmailsService) List

func (s *HeldEmailsService) List(ctx context.Context) ([]HeldEmail, error)

List lists the waiting emails, oldest first (GET /v1/held-emails). It is read-only: approving a sender is done in the app.

type InvoistError

type InvoistError struct {
	// Status is the HTTP status, or 0 when no response arrived.
	Status int
	// Code is a stable machine-readable code: the one in the API's error
	// envelope, or one of the Code constants in this package.
	Code string
	// Message is human-readable text. Its wording may change.
	Message string
	// RequestID is the X-Request-Id response header, worth quoting to
	// support. Empty when there was no response or no header.
	RequestID string
	// Body is the raw response body, when there was one.
	Body []byte
	// Err is the underlying cause when no response arrived (a dial error,
	// a timeout), and nil otherwise.
	Err error
}

InvoistError is the error every failed call returns, whether the API answered with an error, no answer arrived, or a webhook did not verify. Use errors.As (or errors.AsType) to reach it:

var apiErr *invoist.InvoistError
if errors.As(err, &apiErr) && apiErr.IsNotFound() { ... }

Branch on Code, which is stable, never on Message.

A cancelled or expired context is not an InvoistError: the call returns the context's own error (context.Canceled or context.DeadlineExceeded).

Example

Branch on what went wrong with errors.As.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	client, err := invoist.New(os.Getenv("INVOIST_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	_, err = client.GetDocument(context.Background(), "01a19812-0000-7000-8000-0000000000aa")
	var apiErr *invoist.InvoistError
	switch {
	case err == nil:
		fmt.Println("found it")
	case errors.As(err, &apiErr) && apiErr.IsNotFound():
		fmt.Println("no such document")
	case errors.As(err, &apiErr) && apiErr.IsAuthError():
		fmt.Println("check INVOIST_API_KEY")
	case errors.As(err, &apiErr):
		fmt.Println(apiErr.Code, apiErr.Message, apiErr.RequestID)
	default:
		fmt.Println(err) // the context was cancelled
	}
}

func (*InvoistError) Error

func (e *InvoistError) Error() string

Error returns a one-line description of the failure.

func (*InvoistError) IsAuthError

func (e *InvoistError) IsAuthError() bool

IsAuthError reports whether the key is missing, malformed or revoked (401).

func (*InvoistError) IsNotFound

func (e *InvoistError) IsNotFound() bool

IsNotFound reports whether the resource does not exist (404).

func (*InvoistError) IsPermissionError

func (e *InvoistError) IsPermissionError() bool

IsPermissionError reports whether the key is valid but may not do this (403): a missing scope, or a business key on a household route.

func (*InvoistError) IsRateLimited

func (e *InvoistError) IsRateLimited() bool

IsRateLimited reports whether the request was throttled (429).

func (*InvoistError) IsRetryable

func (e *InvoistError) IsRetryable() bool

IsRetryable reports whether sending the same request again could succeed: no response arrived, the request was throttled, or the server failed (5xx). The client already retries these, up to its retry limit.

func (*InvoistError) Unwrap

func (e *InvoistError) Unwrap() error

Unwrap returns the underlying cause, so errors.Is and errors.As can look through a network failure.

type LineItem

type LineItem = generated.LineItem

LineItem is the API's LineItem schema.

type ListBillsParams

type ListBillsParams struct {
	// Paid, when set, keeps only bills marked paid (true) or still to pay
	// (false). Nil lists both: Paid: new(false) lists what is left to pay.
	Paid *bool `query:"paid"`
	// Month keeps only the bills of one month, "YYYY-MM", by due date (or
	// the bill's own date when it has none). MonthOf formats a time.Time.
	Month string `query:"month"`
	// Sender keeps only one sender's bills, ignoring case and spacing.
	Sender string `query:"sender"`
	// Q matches the filename, sender, bill number or reference, ignoring
	// case, across every month.
	Q string `query:"q"`
	// Limit is the most bills to return. The API defaults to 50 and caps
	// it at 200.
	Limit int `query:"limit"`
	// Offset skips this many bills, for paging.
	Offset int `query:"offset"`
}

ListBillsParams filters Bills.List.

type ListDocumentsParams

type ListDocumentsParams struct {
	// Limit is the most documents to return. The API defaults to 50 and
	// caps it at 200.
	Limit int `query:"limit"`
	// Offset skips this many documents, for paging.
	Offset int `query:"offset"`
	// Status keeps only documents in this state.
	Status DocumentStatus `query:"status"`
	// Flagged keeps only documents with review items still pending. It is
	// sent only when true; false lists every document.
	Flagged bool `query:"flagged"`
	// Q matches the filename, vendor, invoice number or reference,
	// ignoring case.
	Q string `query:"q"`
	// Category is a category id, or "none" for uncategorized documents.
	Category string `query:"category"`
}

ListDocumentsParams filters ListDocuments.

type ListReviewQueueParams

type ListReviewQueueParams struct {
	// Status keeps only items in this state. Empty lists every item.
	Status ReviewStatus `query:"status"`
}

ListReviewQueueParams filters ListReviewQueue.

type Option

type Option func(*Client)

Option configures a Client. Pass any number of them to New.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL points the client at another API origin, such as a staging deployment or a local server. Trailing slashes are ignored.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient makes the client send requests through hc, for a custom transport, a proxy, or a fake in tests. The client's own timeout still applies to each attempt.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a retryable failure (no response, a 429, or a 5xx) is retried (default 2). Zero disables retries.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets how long one attempt of a request may take, from sending it to reading the whole response (default 60s). Zero or less disables the limit; the context you pass still applies.

type Quality

type Quality = generated.Quality

Quality is the API's Quality schema.

type QualityIssues

type QualityIssues = generated.QualityIssues

QualityIssues is the API's Quality.Issues schema.

type RegionBox

type RegionBox = generated.RegionBox

RegionBox is the API's RegionBox schema. A rectangle on the page image, normalized 0 to 1, origin top-left.

type ReviewQueueItem

type ReviewQueueItem = generated.ReviewQueueItem

ReviewQueueItem is the API's ReviewQueueItem schema.

type ReviewQueueListItem

type ReviewQueueListItem = generated.ReviewQueueListItem

ReviewQueueListItem is the API's ReviewQueueListItem schema. A review item plus a summary of the document it belongs to.

type ReviewReason

type ReviewReason = generated.ReviewReason

ReviewReason is the API's ReviewReason schema. Why the item was flagged.

type ReviewStatus

type ReviewStatus = generated.ReviewStatus

ReviewStatus is the API's ReviewStatus schema.

type StatsOverview

type StatsOverview = generated.StatsOverview

StatsOverview is the API's StatsOverview schema.

type StatsOverviewPlan

type StatsOverviewPlan = generated.StatsOverviewPlan

StatsOverviewPlan is the API's StatsOverview.Plan schema.

type Usage

type Usage = generated.Usage

Usage is the API's Usage schema.

type UsageDay

type UsageDay = generated.Usage_ByDay

UsageDay is the API's Usage.ByDay schema.

type WaitParams

type WaitParams struct {
	// Timeout is how long to keep polling before giving up with code
	// extraction_timeout. Zero means DefaultWaitTimeout (120s).
	Timeout time.Duration
	// PollInterval is the pause between polls. Zero means
	// DefaultPollInterval (2s).
	PollInterval time.Duration
}

WaitParams are the options of WaitForExtraction.

type WebhookEndpoint

type WebhookEndpoint = generated.WebhookEndpoint

WebhookEndpoint is the API's WebhookEndpoint schema.

type WebhookEndpointList

WebhookEndpointList is what ListWebhookEndpoints returns: the registered endpoints and every event type the API can send.

type WebhookEndpointWithSecret

type WebhookEndpointWithSecret = generated.WebhookEndpointWithSecret

WebhookEndpointWithSecret is the API's WebhookEndpointWithSecret schema.

type WebhookEvent

type WebhookEvent struct {
	// ID identifies the event.
	ID string `json:"id"`
	// Type is what happened, such as EventExtractionCompleted.
	Type EventType `json:"type"`
	// CreatedAt is when it happened.
	CreatedAt time.Time `json:"created_at"`
	// Data is the event's payload, as sent. Decode it with DecodeData.
	Data json.RawMessage `json:"data"`
}

WebhookEvent is a verified webhook delivery.

func VerifyWebhook

func VerifyWebhook(payload []byte, signatureHeader, secret string, opts ...WebhookOption) (*WebhookEvent, error)

VerifyWebhook checks a delivery's X-Invoist-Signature header against your endpoint's signing secret, and returns the event.

payload must be the raw request body, byte for byte: read it with io.ReadAll(r.Body) before anything parses it, because decoding and re-encoding JSON changes the bytes and breaks the signature.

The signature is HMAC-SHA256 over "<t>.<payload>"; it passes when any v1 in the header matches (there are two while a secret is rotated). On failure it returns an *InvoistError with status 400 and code invalid_signature, or signature_too_old when the timestamp is more than the tolerance away from now. Answer such a request with 400.

Example

Receive webhooks with net/http. Read the raw body before anything parses it.

package main

import (
	"io"
	"log"
	"net/http"
	"os"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	secret := os.Getenv("INVOIST_WEBHOOK_SECRET")
	http.HandleFunc("/webhooks/invoist", func(w http.ResponseWriter, r *http.Request) {
		payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil {
			http.Error(w, "unreadable body", http.StatusBadRequest)
			return
		}
		event, err := invoist.VerifyWebhook(payload, r.Header.Get(invoist.SignatureHeader), secret)
		if err != nil {
			http.Error(w, "bad signature", http.StatusBadRequest)
			return
		}
		switch event.Type {
		case invoist.EventExtractionCompleted:
			var data struct {
				DocumentID string `json:"document_id"`
			}
			if err := event.DecodeData(&data); err == nil {
				log.Println("read", data.DocumentID)
			}
		}
		w.WriteHeader(http.StatusNoContent)
	})
}
Example (Signature)

VerifyWebhook returns the event when the signature matches.

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"strconv"
	"time"

	invoist "github.com/invoisthq/invoist-go"
)

func main() {
	secret := "whsec_0123456789abcdef0123456789abcdef"
	body := []byte(`{"id":"e1","type":"document.created","created_at":"2026-11-01T08:00:00Z","data":{}}`)
	signedAt := time.Date(2026, time.November, 1, 8, 0, 0, 0, time.UTC)

	// What Invoist sends in X-Invoist-Signature.
	ts := strconv.FormatInt(signedAt.Unix(), 10)
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(ts + "."))
	mac.Write(body)
	header := "t=" + ts + ",v1=" + hex.EncodeToString(mac.Sum(nil))

	event, err := invoist.VerifyWebhook(body, header, secret, invoist.WithNow(signedAt.Add(time.Minute)))
	fmt.Println(event.Type, err)

	_, err = invoist.VerifyWebhook([]byte(`{"tampered":true}`), header, secret, invoist.WithNow(signedAt))
	var apiErr *invoist.InvoistError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.Status, apiErr.Code)
	}
}
Output:
document.created <nil>
400 invalid_signature

func (*WebhookEvent) DecodeData

func (e *WebhookEvent) DecodeData(v any) error

DecodeData decodes the event's Data into v, typically a struct with the fields you need or a map[string]any.

type WebhookOption

type WebhookOption func(*webhookOptions)

WebhookOption configures VerifyWebhook.

func WithNow

func WithNow(t time.Time) WebhookOption

WithNow sets the time the timestamp is compared against, instead of time.Now. For tests.

func WithTolerance

func WithTolerance(d time.Duration) WebhookOption

WithTolerance sets how far the signature's timestamp may be from now, in either direction (default DefaultWebhookTolerance). Zero turns the check off, which only makes sense when replaying a captured delivery.

Directories

Path Synopsis
internal
cmd/genexports command
Command genexports writes types_gen.go: an exported alias in package invoist for every API schema type that oapi-codegen generated into internal/generated, and a re-export of every enum value.
Command genexports writes types_gen.go: an exported alias in package invoist for every API schema type that oapi-codegen generated into internal/generated, and a re-export of every enum value.
generated
Package generated provides primitives to interact with the openapi HTTP API.
Package generated provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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