# Cytrongift API client for Python 3.8+ (standard library only, no dependencies). # # CYTRON_API_KEY=ck_... CYTRON_API_SECRET=cs_... python3 client.py [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. import hashlib import hmac import json import os import sys import time import urllib.error import urllib.parse import urllib.request class CytronApi: def __init__(self, base, key, secret): self.base = base.rstrip('/') self.key = key self.secret = secret self.token = '' # One request. The signature covers METHOD, PATH (without /v1), TIMESTAMP and the raw body. def request(self, method, path, body=None, bearer=False): method = method.upper() raw = '' if body is None else json.dumps(body, separators=(',', ':')) headers = {'Accept': 'application/json'} if raw != '': headers['Content-Type'] = 'application/json' if bearer and self.token: headers['Authorization'] = 'Bearer ' + self.token else: ts = str(int(time.time())) clean_path = '/' + urllib.parse.urlsplit(path).path.lstrip('/') message = '\n'.join([method, clean_path, ts, raw]).encode() headers['X-Api-Key'] = self.key headers['X-Timestamp'] = ts headers['X-Signature'] = hmac.new(self.secret.encode(), message, hashlib.sha256).hexdigest() req = urllib.request.Request(self.base + path, data=raw.encode() if raw else None, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=30) as res: text = res.read().decode() except urllib.error.HTTPError as err: # the API answers its envelope on every status, so the body is the answer text = err.read().decode() answer = json.loads(text) if not isinstance(answer, dict): raise RuntimeError('not a JSON envelope') return answer # Exchange the signature for a Bearer token and keep it for later calls. def auth(self, ttl=3600): answer = self.request('POST', '/auth', {'ttl': ttl}) if answer.get('ok'): self.token = answer['data']['access_token'] return answer if __name__ == '__main__': cytron = CytronApi(sys.argv[1] if len(sys.argv) > 1 else 'https://api.cytrongift.com/v1', os.environ.get('CYTRON_API_KEY', ''), os.environ.get('CYTRON_API_SECRET', '')) steps = [ ('health', lambda: cytron.request('GET', '/health')), ('config', lambda: cytron.request('GET', '/config')), ('stats', lambda: cytron.request('GET', '/stats')), ('offers', lambda: cytron.request('GET', '/catalog/offers?limit=5')), ('balance', lambda: cytron.request('GET', '/account/balance')), ('auth', lambda: cytron.auth()), ('balance_jwt', lambda: cytron.request('GET', '/account/balance', None, True)), ] for name, call in steps: answer = call() error = answer.get('error') or {} print(name.ljust(12), 'ok' if answer.get('ok') else 'error %s %s' % (error.get('id'), error.get('desc'))) if not answer.get('ok'): sys.exit(1)