PK!ÌÛœç66'finity_partner-1.0.0.dist-info/METADATAMetadata-Version: 2.1 Name: finity-partner Version: 1.0.0 Requires-Python: >=3.11 Summary: Finity partner backend SDK Description-Content-Type: text/markdown # Finity Python client Install the wheel with pip on Python 3.11+. Run the client on your backend. import os from finity_partner import FinityClient client = FinityClient(os.environ["FINITY_ORIGIN"], "network", os.environ["FINITY_SECRET"]) orders = client.list_purchases() intent = client.create_financing_intent({ "entry": "discovery", "shop_ref": "demo-shop", "idempotency_key": "demo-intent-1" }) Read cash and purchase feeds with application_events(case_id, after) and purchase_events(intent_ref, after). Use response next_cursor on the next poll. Reuse operation keys on manual retries. Only GET requests retry automatically after a 401. Processor clients can submit_evidence(issuer, callback_secret, event). To authenticate delivery, use verify_webhook(secret, timestamp, signature, raw_bytes, path) before JSON decoding and deduplicate accepted event IDs. Call capabilities() to read assigned programs. For an order intent you can supply program_ref. Call purchase_deliveries(intent_ref, after) to inspect acknowledgements. Use redeliver_purchase(intent_ref, delivery_id, {"idempotency_key": stable_key}) for an acknowledged event. PK!½Î×ÙÙ%finity_partner-1.0.0.dist-info/RECORDfinity_partner-1.0.0.dist-info/METADATA,sha256=aZgmKKfkGp6njZH6VQc6k81dMA3IgyDH5dgBABVi1kc,1334 finity_partner-1.0.0.dist-info/WHEEL,sha256=ZUUyL0b277hTBo17iiR1UlirzjKxt4tQ6AsD1PUenvA,82 finity_partner/__init__.py,sha256=LaIYeKnaH-IGxhUR4UkS28yi7YuojyVTFeNzdY_gPek,8136 finity_partner/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 finity_partner/types.py,sha256=J3xUBNFBTGZ8sUB-VBOdYg4BREIyfOjdP7MeFrr-pQI,7559 finity_partner-1.0.0.dist-info/RECORD,, PK!yEüöRR$finity_partner-1.0.0.dist-info/WHEELWheel-Version: 1.0 Generator: finity-pack Root-Is-Purelib: true Tag: py3-none-any PK!D‹o|ÈÈfinity_partner/__init__.py"""Standard-library client for partner backends.""" import base64 import hashlib import hmac import http.client import json import re import threading import time from urllib.parse import urlsplit from .types import * def _segment(value): if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", value): raise ValueError("Invalid path segment") return value def _cursor(after): if type(after) is not int or after < 0: raise ValueError("Invalid event cursor") return "?after=" + str(after) def _mac(secret, path, timestamp, raw): prefix = f"POST {path}\n{timestamp}\n".encode() return hmac.new(secret.encode(), prefix + raw, hashlib.sha256).hexdigest() def verify_webhook(secret: str, timestamp: str, signature: str, raw: bytes, path="/notifications") -> bool: return bool(re.fullmatch(r"[0-9]{13}", timestamp) and re.fullmatch(r"[a-f0-9]{64}", signature) and abs(time.time()*1000-int(timestamp)) <= 300000 and hmac.compare_digest(signature, _mac(secret, path, timestamp, raw))) def sign_evidence(secret: str, issuer: str, raw: bytes, timestamp=None): if issuer not in ("bank", "payout", "collections"): raise ValueError("Invalid issuer") stamp = str(time.time_ns() // 1000000) if timestamp is None else timestamp return {"x-finity-timestamp": stamp, "x-finity-signature": _mac(secret, "/integration/v1/callbacks/"+issuer, stamp, raw)} class FinityError(Exception): def __init__(self, status): super().__init__(f"Finity HTTP {status}") self.status = status class FinityClient: def __init__(self, hub_origin: str, client_id: str, client_secret: str): if not re.fullmatch(r"https?://(?:\[[0-9a-fA-F:]+\]|[a-zA-Z0-9.-]+)(?::[0-9]+)?/?", hub_origin): raise ValueError("Expected a secure hub origin") host = urlsplit(hub_origin) if host.scheme == "http" and host.hostname not in ("localhost", "127.0.0.1", "::1"): raise ValueError("HTTPS required") self._host, self._port = host.hostname, host.port self._conn = http.client.HTTPSConnection if host.scheme == "https" else http.client.HTTPConnection self._basic = "Basic " + base64.b64encode(f"{client_id}:{client_secret}".encode()).decode() self._lock = threading.Lock() self._token, self._until = None, 0 def _send(self, method, path, headers, raw=None): conn = self._conn(self._host, self._port, timeout=30) try: conn.request(method, "/integration/v1"+path, raw, {"Content-Type":"application/json", **headers}) response = conn.getresponse() if not 200 <= response.status < 300: raise FinityError(response.status) return json.loads(response.read()) finally: conn.close() def token(self) -> str: with self._lock: if time.monotonic() >= self._until: data = self._send("POST", "/token", {"Authorization": self._basic}) self._token = data["access_token"] self._until = time.monotonic() + data["expires_in"] - 30 return self._token def _call(self, method, path, data=None): key = self.token() raw = None if data is None else json.dumps(data).encode() try: return self._send(method, path, {"Authorization":"Bearer "+key}, raw) except FinityError as error: if error.status != 401: raise with self._lock: if self._token == key: self._until = 0 if method != "GET": raise return self._send(method, path, {"Authorization":"Bearer "+self.token()}) def submit_evidence(self, issuer: Literal["bank", "payout", "collections"], secret: str, data: Callback) -> EvidenceReceipt: raw = json.dumps(data).encode() return self._send("POST", "/callbacks/"+_segment(issuer), sign_evidence(secret, issuer, raw), raw) def list_applications(self) -> ListApplicationsResponse: return self._call("GET", '/applications') def get_application(self, case_id: str) -> Application: return self._call("GET", f'/applications/{_segment(case_id)}') def get_state(self, case_id: str) -> State: return self._call("GET", f'/applications/{_segment(case_id)}/state') def command(self, case_id: str, action: Literal['attest', 'notify', 'forward', 'offer', 'approve', 'decline', 'funding', 'payout', 'funded', 'post', 'return', 'correct'], data: Command) -> CommandReceipt: return self._call("POST", f'/applications/{_segment(case_id)}/commands/{_segment(action)}', data) def application_events(self, case_id: str, after: int = 0) -> ApplicationEventsResponse: return self._call("GET", f'/applications/{_segment(case_id)}/events' + _cursor(after)) def list_transfers(self) -> ListTransfersResponse: return self._call("GET", '/transfers') def get_transfer(self, case_id: str) -> GetTransferResponse: return self._call("GET", f'/transfers/{_segment(case_id)}') def create_merchant_launch(self, data: CreateMerchantLaunchInput) -> CreateMerchantLaunchResponse: return self._call("POST", '/merchant-launches', data) def create_financing_intent(self, data: FinancingIntent) -> PurchaseOrder | CreateFinancingIntentResponse2: return self._call("POST", '/financing-intents', data) def list_purchases(self) -> ListPurchasesResponse: return self._call("GET", '/purchases') def get_purchase(self, intent_ref: str) -> PurchaseOrder: return self._call("GET", f'/purchases/{_segment(intent_ref)}') def request_purchase(self, intent_ref: str, data: RequestPurchaseInput) -> PurchaseOrder: return self._call("POST", f'/purchases/{_segment(intent_ref)}/request', data) def approve_purchase(self, intent_ref: str, data: ApprovePurchaseInput) -> PurchaseOrder: return self._call("POST", f'/purchases/{_segment(intent_ref)}/approve', data) def fulfil_purchase(self, intent_ref: str, data: FulfilPurchaseInput) -> PurchaseOrder: return self._call("POST", f'/purchases/{_segment(intent_ref)}/fulfil', data) def return_purchase(self, intent_ref: str, data: ReturnPurchaseInput) -> PurchaseOrder: return self._call("POST", f'/purchases/{_segment(intent_ref)}/return', data) def cancel_purchase(self, intent_ref: str, data: CancelPurchaseInput) -> PurchaseOrder: return self._call("POST", f'/purchases/{_segment(intent_ref)}/cancel', data) def revise_purchase(self, intent_ref: str, data: RevisePurchaseInput) -> PurchaseOrder: return self._call("POST", f'/purchases/{_segment(intent_ref)}/revise', data) def purchase_evidence(self, intent_ref: str, data: PurchaseEvidenceInput) -> dict[str, Any]: return self._call("POST", f'/purchases/{_segment(intent_ref)}/evidence', data) def purchase_events(self, intent_ref: str, after: int = 0) -> PurchaseEventsResponse: return self._call("GET", f'/purchases/{_segment(intent_ref)}/events' + _cursor(after)) def list_questions(self, case_id: str) -> ListQuestionsResponse: return self._call("GET", f'/applications/{_segment(case_id)}/questions') def question_action(self, case_id: str, action: Literal['request', 'accept_answer', 'waive', 'evidence'], data: QuestionActionInput) -> dict[str, Any]: return self._call("POST", f'/applications/{_segment(case_id)}/questions/{_segment(action)}', data) def capabilities(self) -> Capabilities: return self._call("GET", "/capabilities") def purchase_deliveries(self, intent_ref: str, after: int = 0) -> PurchaseDeliveries: return self._call("GET", f'/purchases/{_segment(intent_ref)}/deliveries' + _cursor(after)) def redeliver_purchase(self, intent_ref: str, delivery_id: str, data: RedeliveryRequest) -> RedeliveryReceipt: path = f'/purchases/{_segment(intent_ref)}/deliveries/{_segment(delivery_id)}/redeliver' return self._call("POST", path, data) PK!finity_partner/py.typedPK!¿­‡‡finity_partner/types.pyfrom typing import Any, Literal, NotRequired, TypedDict class Application(TypedDict): id: str stage: str channel: str name: str treatment: str reference: NotRequired[str] purpose: NotRequired[str] requested_minor: NotRequired[int] approved_minor: NotRequired[int] outstanding: NotRequired[int] class StateActionsItem(TypedDict): action: str label: str review: NotRequired[dict[str, Any]] confirmation: NotRequired[str] class State(TypedDict): id: str stage: str actions: list[StateActionsItem] events: list[dict[str, Any]] CommandDetails = TypedDict("CommandDetails", { "reference": NotRequired[str], "from": NotRequired[str], "to": NotRequired[str], "sales": NotRequired[int], "amount": NotRequired[int], "route": NotRequired[Literal['manual', 'simulated']], "ledger_reference": NotRequired[str], "reason": NotRequired[str], }) class Command(TypedDict): key: str confirmation: NotRequired[str] details: NotRequired[CommandDetails] class CommandReceipt(TypedDict): id: str status: str class Notice(TypedDict): id: str type: Literal['application.ready', 'receipt.changed', 'transfer.ready'] environment: Literal['sandbox'] case_ref: str receipt_ref: NotRequired[str] version: int occurred_at: str class TransferSourceAccount(TypedDict): owner: Literal['merchant', 'lender'] reference: str network: NotRequired[str] lender: NotRequired[str] class TransferDestinationAccount(TypedDict): owner: Literal['merchant', 'lender'] reference: str network: NotRequired[str] lender: NotRequired[str] class Transfer(TypedDict): case_ref: str instruction: str direction: Literal['payout', 'pay', 'return'] currency: Literal['PKR'] amount_minor: int merchant_ref: str status: str source_version: int source_receipt: NotRequired[str] source_account: TransferSourceAccount destination_account: TransferDestinationAccount instruction_status: str responsibility: Literal['execute_once_and_report', 'report_bank_entry'] original_collection: NotRequired[str] original_receipt: NotRequired[str] class Evidence(TypedDict): merchant_ref: str statement_ref: str transfer_ref: str amount: str value_date: str class Callback(TypedDict): id: str type: Literal['transfer.evidence'] case_ref: str instruction: str expected_version: int evidence: Evidence class EvidenceReceipt(TypedDict): event_id: str version: int status: Literal['awaiting_evidence', 'mismatch', 'matched'] class FinancingIntent1FinanceAmount(TypedDict): mode: Literal['open', 'fixed', 'suggested', 'maximum'] minor: NotRequired[int] class FinancingIntent1(TypedDict): shop_ref: str idempotency_key: str entry: Literal['discovery', 'working_capital', 'offer', 'resume'] case_ref: NotRequired[str] currency: NotRequired[Literal['PKR']] product_ref: NotRequired[Literal['working-capital-v1']] finance_amount: NotRequired[FinancingIntent1FinanceAmount] PurchaseProgramRef = Literal["panel-stock-v1", "trazmo-stock-v1"] class FinancingIntent2(TypedDict): program_ref: NotRequired[PurchaseProgramRef] shop_ref: str idempotency_key: str entry: Literal['order_checkout', 'facility_draw', 'invoice', 'assisted'] order_ref: str sku: NotRequired[Literal['stock', 'equipment']] quantity: NotRequired[int] manual_review: NotRequired[bool] invoice_ref: NotRequired[str] revision: NotRequired[int] FinancingIntent = FinancingIntent1 | FinancingIntent2 class PurchaseOrder(TypedDict): program_ref: NotRequired[Literal["panel-stock-v1", "trazmo-stock-v1"]] lender: NotRequired[str] decision_party: NotRequired[Literal["lender", "trazmo"]] relay: NotRequired[str | None] intent_ref: str order_ref: str status: Literal['quoted', 'needs_information', 'in_review', 'approved', 'confirmed', 'settlement_pending', 'partially_fulfilled', 'fulfilled', 'return_pending', 'refunded', 'paid', 'paid_now', 'cancelled'] terms_ref: NotRequired[str] currency: NotRequired[Literal['PKR']] revision: NotRequired[int] total_minor: int deposit_minor: NotRequired[int] finance_minor: NotRequired[int] settled_minor: NotRequired[int] balance_minor: int available_limit_minor: NotRequired[int] followups: NotRequired[list[dict[str, Any]]] receipts: NotRequired[list[dict[str, Any]]] class PurchaseNotice(TypedDict): id: str type: Literal['purchase.changed'] environment: Literal['sandbox'] intent_ref: str version: int occurred_at: str class ListApplicationsResponse(TypedDict): applications: list[Application] class ApplicationEventsResponse(TypedDict): events: list[Notice] next_cursor: int class ListTransfersResponse(TypedDict): transfers: list[Transfer] class GetTransferResponse(TypedDict): transfers: list[Transfer] class CreateMerchantLaunchResponse(TypedDict): code: str expires_in: Literal[90] class CreateMerchantLaunchInput(TypedDict): subject: str reference: str business: str signer: str capacity: Literal['proprietor', 'company'] intent_ref: NotRequired[str] class CreateFinancingIntentResponse2(TypedDict): intent_ref: str entry: str expires_at: str class ListPurchasesResponse(TypedDict): orders: list[PurchaseOrder] class RequestPurchaseInput(TypedDict): idempotency_key: str question: Literal['Please confirm the delivery location for this order.', 'When can the shop take delivery?', 'What date is on the supplier quote?', 'What is the supplier bill number?'] class ApprovePurchaseInput(TypedDict): idempotency_key: str question_ref: str answer_ref: str application_ref: str class FulfilPurchaseInput(TypedDict): idempotency_key: str amount_minor: int class ReturnPurchaseInput(TypedDict): idempotency_key: str amount_minor: int class CancelPurchaseInput(TypedDict): idempotency_key: str class RevisePurchaseInput(TypedDict): idempotency_key: str revision: int quantity: NotRequired[int] sku: NotRequired[Literal['stock', 'equipment']] class PurchaseEvidenceInput(TypedDict): question_ref: str class PurchaseEventsResponse(TypedDict): events: list[PurchaseNotice] next_cursor: int class ListQuestionsResponse(TypedDict): questions: list[dict[str, Any]] class QuestionActionInput(TypedDict): key: str revision: int kind: NotRequired[Literal['supplier_bill', 'bill_date', 'delivery_days']] reason: NotRequired[Literal['verify_stock', 'unclear_date', 'delivery_timing']] class PurchaseProgram(TypedDict): program_ref: PurchaseProgramRef lender: str decision_party: Literal["trazmo", "lender"] relay: Literal["trazmo"] | None class Capabilities(TypedDict): client: str environment: Literal["sandbox"] contract: str entries: list[str] purchase_programs: list[PurchaseProgram] transfer_source: Literal["payout", "bank", "collections"] | None class PurchaseDelivery(TypedDict): id: str version: int generation: int attempts: int delivered: bool acknowledged_at: str | None class PurchaseDeliveries(TypedDict): deliveries: list[PurchaseDelivery] next_cursor: int class RedeliveryRequest(TypedDict): idempotency_key: str class RedeliveryReceipt(TypedDict): id: str generation: int PK!ÌÛœç66'¤�finity_partner-1.0.0.dist-info/METADATAPK!½Î×ÙÙ%¤�{finity_partner-1.0.0.dist-info/RECORDPK!yEüöRR$¤�—finity_partner-1.0.0.dist-info/WHEELPK!D‹o|ÈȤ�+finity_partner/__init__.pyPK!¤�+(finity_partner/py.typedPK!¿­‡‡¤�`(finity_partner/types.pyPKÌF