"""Minimal Tagali Partner API client for Python 3.8+ (standard library only). Copy into your integration. tagali = TagaliClient("https://api.tagali.example/partner/v1", "pk_test_...", "sk_test_...") r = tagali.lookup("test.moussa", "Moussa Traore") # show r["displayName"] to your sender q = tagali.quote(r["lookupId"], 65000) # XOF the recipient receives p = tagali.payout({"quoteId": q["quoteId"], "partnerReference": "TRX-1", "sender": {"fullName": "Aminata Diallo", "country": "FR"}, "purpose": "family_support"}) """ import hashlib, hmac, json, secrets, time, uuid from urllib import request as _rq, parse as _parse, error as _err class TagaliError(Exception): def __init__(self, status, code, message, data=None): super().__init__(f"{status} {code}: {message}") self.status, self.code, self.data = status, code, data or {} class TagaliClient: def __init__(self, base_url, key_id, secret, timeout=30): self.base = base_url.rstrip("/") self.path_prefix = _parse.urlsplit(self.base).path self.key_id, self.secret, self.timeout = key_id, secret.encode(), timeout def request(self, method, path, body=None, headers=None): raw = b"" if body is None else json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode() ts = str(int(time.time())) nonce = secrets.token_hex(16) to_sign = f"{ts}.{nonce}.{method}.{self.path_prefix}{path}.{hashlib.sha256(raw).hexdigest()}" sig = hmac.new(self.secret, to_sign.encode(), hashlib.sha256).hexdigest() h = {"Content-Type": "application/json", "X-Tagali-Key": self.key_id, "X-Tagali-Timestamp": ts, "X-Tagali-Nonce": nonce, "X-Tagali-Signature": f"v1={sig}", **(headers or {})} req = _rq.Request(self.base + path, data=raw or None, method=method, headers=h) try: with _rq.urlopen(req, timeout=self.timeout) as res: return json.loads(res.read() or b"{}") except _err.HTTPError as e: data = json.loads(e.read() or b"{}").get("error", {}) raise TagaliError(e.code, data.get("code"), data.get("message"), data) from None def ping(self): return self.request("GET", "/ping") def lookup(self, tag, sender_given_name=None): q = f"?name={_parse.quote(sender_given_name)}" if sender_given_name else "" return self.request("GET", f"/recipients/{_parse.quote(tag.lstrip('@'))}{q}") def quote(self, lookup_id, amount): return self.request("POST", "/quotes", {"lookupId": lookup_id, "amount": amount, "currency": "XOF"}) def payout(self, body, idempotency_key=None): """Pass the same idempotency_key when you retry after a timeout.""" return self.request("POST", "/payouts", body, {"Idempotency-Key": idempotency_key or str(uuid.uuid4())}) def get_payout(self, id_or_reference): return self.request("GET", f"/payouts/{_parse.quote(id_or_reference)}") def cancel(self, payout_id): return self.request("POST", f"/payouts/{_parse.quote(payout_id)}/cancel", {}) def balance(self): return self.request("GET", "/balance") def verify_tagali_webhook(raw_body: bytes, timestamp: str, signature: str, webhook_secret: str, tolerance_sec=300) -> bool: """Verify a webhook from Tagali. Use the raw request body exactly as received.""" try: if abs(time.time() - int(timestamp)) > tolerance_sec: return False except (TypeError, ValueError): return False expected = hmac.new(webhook_secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(f"v1={expected}", signature or "")