// Package exno is the EXNO REST SDK 1.0.0 for Go 1.21+ (server-side, standard library only). One file: copy it into // your module (for example internal/exno/exno.go). Same behaviour as the JavaScript and Python SDKs, plus VerifyWebhook. package exno import ( "bytes" "context" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "math" "net/http" "net/url" "regexp" "strconv" "strings" "time" ) var hosts = map[string]string{"production": "https://exno.app/api/v1/", "staging": "https://staging.exno.app/api/v1/"} var resourceRe = regexp.MustCompile(`^[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*$`) var localRe = regexp.MustCompile(`^http://(127\.0\.0\.1|localhost):\d{2,5}/?$`) // Error is an answer from EXNO that isn't a success. type Error struct { Status int Code string Param string Message string RequestID string RetryAfter string } func (e *Error) Error() string { return e.Message } // ErrInvalidSignature is returned by VerifyWebhook for a request that EXNO didn't sign (or signed too long ago). var ErrInvalidSignature = errors.New("exno: invalid webhook signature") // Client calls the EXNO REST API with one API key. type Client struct { key string base string http *http.Client } // Option configures a Client. type Option func(*Client) error // WithEnvironment chooses "production" (the default) or "staging". func WithEnvironment(env string) Option { return func(c *Client) error { b, ok := hosts[env] if !ok { return errors.New("exno: unknown environment") } c.base = b return nil } } // WithBaseURL is for local development only: http://127.0.0.1: or http://localhost:. func WithBaseURL(u string) Option { return func(c *Client) error { if !localRe.MatchString(u) { return errors.New("exno: the base URL is only for local development (http://127.0.0.1:)") } c.base = strings.TrimRight(u, "/") + "/api/v1/" return nil } } // WithHTTPClient uses your own http.Client (redirects are never followed). func WithHTTPClient(h *http.Client) Option { return func(c *Client) error { cp := *h cp.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } c.http = &cp return nil } } // New makes a client. Keep the key on your server: set EXNO_API_KEY in its environment. func New(apiKey string, opts ...Option) (*Client, error) { if strings.TrimSpace(apiKey) == "" { return nil, errors.New("exno: an API key is required") } c := &Client{key: apiKey, base: hosts["production"], http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} for _, o := range opts { if err := o(c); err != nil { return nil, err } } return c, nil } // RequestOptions are a call's URL parameters, JSON body and idempotency key (a new one is made for every write // without one; keep your own to retry a write safely). type RequestOptions struct { Query map[string]string Body any IdempotencyKey string } // Request makes one API call. resource is relative to /api/v1, for example "products" or "sales/ORDER_ID". The // answer is the complete API response; numbers are json.Number (money is in integer minor units). func (c *Client) Request(ctx context.Context, method, resource string, o *RequestOptions) (map[string]any, error) { if o == nil { o = &RequestOptions{} } switch method { case http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodDelete: default: return nil, errors.New("exno: unsupported HTTP method") } if !resourceRe.MatchString(resource) { return nil, errors.New("exno: use an API resource such as products or sales/ID") } if method == http.MethodGet && o.Body != nil { return nil, errors.New("exno: GET does not take a body") } u, err := url.Parse(c.base + resource) if err != nil { return nil, err } if len(o.Query) > 0 { q := u.Query() for k, v := range o.Query { q.Set(k, v) } u.RawQuery = q.Encode() } var body io.Reader if o.Body != nil { b, err := json.Marshal(o.Body) if err != nil { return nil, err } body = bytes.NewReader(b) } req, err := http.NewRequestWithContext(ctx, method, u.String(), body) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+c.key) req.Header.Set("Accept", "application/json") if o.Body != nil { req.Header.Set("Content-Type", "application/json") } if method != http.MethodGet { key := o.IdempotencyKey if key == "" { key = newUUID() } req.Header.Set("Idempotency-Key", key) } res, err := c.http.Do(req) if err != nil { return nil, err } defer res.Body.Close() raw, err := io.ReadAll(io.LimitReader(res.Body, 32<<20)) if err != nil { return nil, err } var data map[string]any if len(raw) > 0 { d := json.NewDecoder(bytes.NewReader(raw)) d.UseNumber() if err := d.Decode(&data); err != nil && res.StatusCode >= 200 && res.StatusCode < 300 { return nil, errors.New("exno: invalid JSON from EXNO") } } if res.StatusCode < 200 || res.StatusCode >= 300 { e := &Error{Status: res.StatusCode, Message: fmt.Sprintf("EXNO returned HTTP %d", res.StatusCode), RequestID: res.Header.Get("X-Request-Id"), RetryAfter: res.Header.Get("Retry-After")} if detail, ok := data["error"].(map[string]any); ok { if s, ok := detail["message"].(string); ok && s != "" { e.Message = s } e.Code, _ = detail["code"].(string) e.Param, _ = detail["param"].(string) if e.RequestID == "" { e.RequestID, _ = detail["request_id"].(string) } } return nil, e } return data, nil } // Me is GET /me. func (c *Client) Me(ctx context.Context) (map[string]any, error) { return c.Request(ctx, http.MethodGet, "me", nil) } // Products is GET /products. func (c *Client) Products(ctx context.Context, query map[string]string) (map[string]any, error) { return c.Request(ctx, http.MethodGet, "products", &RequestOptions{Query: query}) } // Sales is GET /sales. func (c *Client) Sales(ctx context.Context, query map[string]string) (map[string]any, error) { return c.Request(ctx, http.MethodGet, "sales", &RequestOptions{Query: query}) } // Pages calls fn with every page of a list, following next_cursor. Return an error from fn to stop. func (c *Client) Pages(ctx context.Context, resource string, query map[string]string, fn func(page map[string]any) error) error { q := map[string]string{} for k, v := range query { q[k] = v } seen := map[string]bool{} if q["cursor"] != "" { seen[q["cursor"]] = true } for { page, err := c.Request(ctx, http.MethodGet, resource, &RequestOptions{Query: q}) if err != nil { return err } if err := fn(page); err != nil { return err } if more, _ := page["has_more"].(bool); !more { return nil } next, _ := page["next_cursor"].(string) if next == "" || seen[next] { return errors.New("exno: invalid pagination cursor") } q["cursor"] = next seen[next] = true } } // VerifyWebhook checks a webhook request from EXNO and returns the event. body is the raw request body, signature // the Exno-Signature header, secret the endpoint's or app's signing secret (whsec_…). Requests older than tolerance // are refused (0 = don't check the time). func VerifyWebhook(body []byte, signature, secret string, tolerance time.Duration) (map[string]any, error) { var t string var v1 []string for _, part := range strings.Split(signature, ",") { k, v, ok := strings.Cut(strings.TrimSpace(part), "=") if !ok { continue } switch k { case "t": t = v case "v1": v1 = append(v1, v) } } ts, err := strconv.ParseInt(t, 10, 64) if err != nil || len(v1) == 0 { return nil, ErrInvalidSignature } if tolerance > 0 && math.Abs(float64(time.Now().Unix()-ts)) > tolerance.Seconds() { return nil, ErrInvalidSignature } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(t + ".")) mac.Write(body) expected := hex.EncodeToString(mac.Sum(nil)) for _, candidate := range v1 { if hmac.Equal([]byte(expected), []byte(candidate)) { var event map[string]any d := json.NewDecoder(bytes.NewReader(body)) d.UseNumber() if err := d.Decode(&event); err != nil { return nil, err } return event, nil } } return nil, ErrInvalidSignature } func newUUID() string { var b [16]byte if _, err := rand.Read(b[:]); err != nil { panic(err) } b[6] = (b[6] & 0x0f) | 0x40 b[8] = (b[8] & 0x3f) | 0x80 h := hex.EncodeToString(b[:]) return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:] }