invoice API for Go

Invoice API for Go

Create an invoice from Go with net/http. Set a timeout so a slow response cannot hold a worker open.

Base URL https://invoicetxt.com Auth Authorization: Bearer itxt_live_…

POST/v1/invoices

Create with a timeout

Use a context with a timeout. Read the whole error body when the status is not 201 so logs show the validation message instead of an empty failure. Check the error from NewRequest and Do before you close the body.

Go
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
body := []byte(`{"client":"Lena Park","due":"net 7","items":[{"description":"Portrait session","quantity":1,"rate":250}]}`)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://invoicetxt.com/v1/invoices", bytes.NewReader(body))
if err != nil {
  log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("INVOICETXT_API_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
  log.Fatal(err)
}
defer res.Body.Close()
payload, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusCreated {
  log.Fatalf("invoice API %s: %s", res.Status, payload)
}

PDF bytes

A second request to /v1/invoices/{id}/pdf returns the file. Copy the body to an os.File only after you have checked the status code. A JSON error body is not a PDF.