|
|
import os, time, hashlib, hmac, requests |
|
|
|
|
|
API_URL = os.environ["CHAPTLY_API_URL"] |
|
|
API_SECRET = os.environ["CHAPTLY_API_SECRET"] |
|
|
API_KEY = os.environ["API_KEYS"] |
|
|
|
|
|
def signed_request(method: str, path: str, json_payload: dict | None = None): |
|
|
body_bytes = (json.dumps(json_payload or {}) ).encode("utf-8") |
|
|
body_hash = hashlib.sha256(body_bytes).hexdigest() |
|
|
timestamp = str(int(time.time())) |
|
|
canonical = "\n".join([method.upper(), path, body_hash, timestamp]) |
|
|
signature = hmac.new(API_SECRET.encode(), canonical.encode(), hashlib.sha256).hexdigest() |
|
|
|
|
|
headers = { |
|
|
"X-Timestamp": timestamp, |
|
|
"X-Signature": signature, |
|
|
} |
|
|
if API_KEY: |
|
|
headers["X-API-Key"] = API_KEY |
|
|
|
|
|
url = f"{API_URL}{path}" |
|
|
resp = requests.request(method, url, json=json_payload, headers=headers) |
|
|
resp.raise_for_status() |
|
|
return resp.json() |