// Cytrongift API client in Go (standard library only). // // CYTRON_API_KEY=ck_... CYTRON_API_SECRET=cs_... go run . [base_url] // // Signs every request with the application key, exchanges the signature for a Bearer token // and reads the balance twice: once over the signature, once over the token. package main import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strconv" "strings" "time" ) // Envelope is the answer of every endpoint. type Envelope struct { OK int `json:"ok"` Data json.RawMessage `json:"data"` Error *struct { ID string `json:"id"` Code int `json:"code"` Desc string `json:"desc"` } `json:"error"` } // CytronApi signs requests with an application key. type CytronApi struct { Base string Key string Secret string token string http *http.Client } // NewCytronApi returns a client for the base address, for example https://api.cytrongift.com/v1. func NewCytronApi(base, key, secret string) *CytronApi { return &CytronApi{Base: strings.TrimRight(base, "/"), Key: key, Secret: secret, http: &http.Client{Timeout: 30 * time.Second}} } // Request sends one call. The signature covers METHOD, PATH (without /v1), TIMESTAMP and the raw body. func (c *CytronApi) Request(method, path string, body any, bearer bool) (*Envelope, error) { method = strings.ToUpper(method) raw := []byte{} if body != nil { var err error if raw, err = json.Marshal(body); err != nil { return nil, err } } req, err := http.NewRequest(method, c.Base+path, bytes.NewReader(raw)) if err != nil { return nil, err } req.Header.Set("Accept", "application/json") if len(raw) > 0 { req.Header.Set("Content-Type", "application/json") } if bearer && c.token != "" { req.Header.Set("Authorization", "Bearer "+c.token) } else { u, _ := url.Parse(path) ts := strconv.FormatInt(time.Now().Unix(), 10) mac := hmac.New(sha256.New, []byte(c.Secret)) mac.Write([]byte(method + "\n/" + strings.TrimLeft(u.Path, "/") + "\n" + ts + "\n" + string(raw))) req.Header.Set("X-Api-Key", c.Key) req.Header.Set("X-Timestamp", ts) req.Header.Set("X-Signature", hex.EncodeToString(mac.Sum(nil))) } res, err := c.http.Do(req) if err != nil { return nil, err } defer res.Body.Close() answer, err := io.ReadAll(res.Body) if err != nil { return nil, err } var env Envelope if err := json.Unmarshal(answer, &env); err != nil { return nil, fmt.Errorf("HTTP %d: not a JSON envelope", res.StatusCode) } return &env, nil } // Auth exchanges the signature for a Bearer token and keeps it for later calls. func (c *CytronApi) Auth(ttl int) (*Envelope, error) { env, err := c.Request("POST", "/auth", map[string]int{"ttl": ttl}, false) if err == nil && env.OK == 1 { var data struct { AccessToken string `json:"access_token"` } if err := json.Unmarshal(env.Data, &data); err == nil { c.token = data.AccessToken } } return env, err } func main() { base := "https://api.cytrongift.com/v1" if len(os.Args) > 1 { base = os.Args[1] } cytron := NewCytronApi(base, os.Getenv("CYTRON_API_KEY"), os.Getenv("CYTRON_API_SECRET")) steps := []struct { name string call func() (*Envelope, error) }{ {"health", func() (*Envelope, error) { return cytron.Request("GET", "/health", nil, false) }}, {"config", func() (*Envelope, error) { return cytron.Request("GET", "/config", nil, false) }}, {"stats", func() (*Envelope, error) { return cytron.Request("GET", "/stats", nil, false) }}, {"offers", func() (*Envelope, error) { return cytron.Request("GET", "/catalog/offers?limit=5", nil, false) }}, {"balance", func() (*Envelope, error) { return cytron.Request("GET", "/account/balance", nil, false) }}, {"auth", func() (*Envelope, error) { return cytron.Auth(3600) }}, {"balance_jwt", func() (*Envelope, error) { return cytron.Request("GET", "/account/balance", nil, true) }}, } for _, step := range steps { env, err := step.call() if err != nil { fmt.Printf("%-12s %v\n", step.name, err) os.Exit(1) } if env.OK != 1 { fmt.Printf("%-12s error %s %s\n", step.name, env.Error.ID, env.Error.Desc) os.Exit(1) } fmt.Printf("%-12s ok\n", step.name) } }