"""Customer API SDK for Python 3.11+ (standard library only). Generated by cmd/sdkgen from api/openapi/customer.v3.yaml. Do not edit by hand; run `task gen`. Every POST gets an Idempotency-Key (generated when you don't pass one), so the client retries network failures, 429 and 5xx safely. Responses are plain dicts shaped like the TypedDicts below. from smm_sdk import SmmClient client = SmmClient(api_key="smm_test_...", base_url="https://example.com") order = client.create_order({"service_id": 1001, "link": "https://instagram.com/x", "quantity": 1000}) """ from __future__ import annotations import hashlib import hmac import json import time import urllib.error import urllib.parse import urllib.request import uuid from typing import Any, Dict, Iterator, List, Literal, NotRequired, Optional, TypedDict __all__ = ["SmmClient", "SmmError", "verify_webhook"] class Accepted(TypedDict): object: Literal["accepted"] status: Literal["queued"] class ApiError(TypedDict): type: str code: str message: str message_fa: str param: Optional[str] request_id: str class Balance(TypedDict): object: Literal["balance"] livemode: bool balance_irr: int credit_limit_irr: int available_irr: int class Batch(TypedDict): object: Literal["batch"] id: int livemode: bool status: str mode: str total_irr: int lines: int orders: List["Order"] created_at: str class BatchCreate(TypedDict): orders: List["OrderCreate"] mode: NotRequired[Literal["all_or_nothing", "valid_only"]] class BatchLineError(TypedDict): index: int error: "LineError" class BatchResult(TypedDict): object: Literal["batch_result"] batch_id: Optional[int] total_irr: int orders: List["Order"] errors: List["BatchLineError"] class Category(TypedDict): object: Literal["category"] id: int platform: str slug: str name_fa: str target_kind: str class CategoryList(TypedDict): object: Literal["list"] data: List["Category"] next_cursor: Optional[str] class Commission(TypedDict): object: Literal["referral_commission"] id: int commission_irr: int status: str release_at: str created_at: str class CouponRedeem(TypedDict): code: str class CouponRedemption(TypedDict): object: Literal["coupon_redemption"] kind: Literal["voucher", "deposit_bonus"] credited_irr: int class Credential(TypedDict): kind: Literal["api_key", "app_token"] id: int label: str livemode: bool scopes: List[str] class ErrorResponse(TypedDict): error: "ApiError" class Event(TypedDict): object: Literal["event"] id: int type: str livemode: bool created_at: str data: Dict[str, Any] class EventList(TypedDict): object: Literal["list"] data: List["Event"] next_cursor: Optional[str] class Favorite(TypedDict): object: Literal["favorite"] service_id: int class FavoriteCreate(TypedDict): service_id: int class FavoriteList(TypedDict): object: Literal["list"] data: List["Favorite"] next_cursor: Optional[str] class LineError(TypedDict): type: str code: str message: str message_fa: str param: Optional[str] class LinkResolution(TypedDict): object: Literal["link_resolution"] platform: str target_kind: str normalized_link: str compatible_service_ids: List[int] recommended_service_id: Optional[int] class LinkResolveRequest(TypedDict): link: str class MarkRead(TypedDict): id: NotRequired[int] class MarkReadResult(TypedDict): object: Literal["notifications_read"] marked: int class Me(TypedDict): object: Literal["user"] id: int phone: str display_name: Optional[str] email: Optional[str] tier: "Tier" ref_code: str credential: "Credential" created_at: str class Meta(TypedDict): object: Literal["meta"] api_version: str server_time: str class Notification(TypedDict): object: Literal["notification"] id: int event: str title_fa: str body_fa: str link: str read: bool created_at: str class NotificationList(TypedDict): object: Literal["list"] data: List["Notification"] next_cursor: Optional[str] unread: int class Order(TypedDict): object: Literal["order"] id: int livemode: bool status: str status_label: str service_id: int link: str quantity: int start_count: Optional[int] remains: Optional[int] charge_irr: int refunded_irr: int params: Dict[str, Any] client_label: Optional[str] batch_id: Optional[int] cancelable: bool refillable: bool created_at: str updated_at: str completed_at: Optional[str] class OrderCreate(TypedDict): service_id: int link: str quantity: int client_label: NotRequired[Optional[str]] params: NotRequired[Dict[str, Any]] class OrderList(TypedDict): object: Literal["list"] data: List["Order"] next_cursor: Optional[str] class OtpChallenge(TypedDict): object: Literal["otp_challenge"] challenge_id: str expires_in: int class OtpRequest(TypedDict): phone: str class OtpVerify(TypedDict): challenge_id: str code: str device_name: NotRequired[str] class Payment(TypedDict): object: Literal["payment"] id: int status: str gateway: str amount_irr: int redirect_url: Optional[str] return_url: Optional[str] created_at: str updated_at: str verified_at: Optional[str] class PaymentCreate(TypedDict): amount_irr: int gateway: NotRequired[str] return_url: NotRequired[Optional[str]] class Platform(TypedDict): object: Literal["platform"] slug: str name_fa: str name_en: str is_domestic: bool ordering_paused: bool class PlatformList(TypedDict): object: Literal["list"] data: List["Platform"] next_cursor: Optional[str] class Quote(TypedDict): object: Literal["quote"] service_id: int quantity: int rate_irr_per_1000: int charge_irr: int valid_until: str duplicate_order_ids: List[int] class QuoteRequest(TypedDict): service_id: int quantity: int link: NotRequired[str] class Referrals(TypedDict): object: Literal["referrals"] link: str ref_code: str commission_bps: int hold_days: int held_irr: int released_irr: int commissions: List["Commission"] class Refill(TypedDict): object: Literal["refill"] id: int order_id: int status: str error: str created_at: str updated_at: str class RefillList(TypedDict): object: Literal["list"] data: List["Refill"] next_cursor: Optional[str] class RefreshRequest(TypedDict): refresh_token: str class RequestLog(TypedDict): object: Literal["request_log"] id: int method: str path: str status: int duration_ms: int request_id: str error_code: Optional[str] credential: str livemode: bool created_at: str class RequestLogList(TypedDict): object: Literal["list"] data: List["RequestLog"] next_cursor: Optional[str] class Service(TypedDict): object: Literal["service"] id: int platform: str category: str target_kind: str type: str name_fa: str description_fa: str rate_irr_per_1000: int min: int max: int step: int refill_days: int cancelable: bool dripfeed: bool p50_start_seconds: Optional[int] p50_complete_seconds: Optional[int] status: str class ServiceList(TypedDict): object: Literal["list"] data: List["Service"] next_cursor: Optional[str] class Target(TypedDict): object: Literal["target"] id: int link: str platform: str target_kind: str label: str tags: List[str] created_at: str class TargetCreate(TypedDict): link: str label: NotRequired[str] tags: NotRequired[List[str]] class TargetList(TypedDict): object: Literal["list"] data: List["Target"] next_cursor: Optional[str] class Template(TypedDict): object: Literal["template"] id: int name: str lines: str created_at: str updated_at: str class TemplateCreate(TypedDict): name: str lines: str class TemplateList(TypedDict): object: Literal["list"] data: List["Template"] next_cursor: Optional[str] class TestBalanceRequest(TypedDict): amount_irr: int class Ticket(TypedDict): object: Literal["ticket"] id: int subject: str category: str status: str order_id: Optional[int] rating: Optional[int] last_message_at: str created_at: str closed_at: Optional[str] class TicketCreate(TypedDict): subject: str body: str category: NotRequired[Literal["general", "order", "payment", "api", "account", "other"]] order_id: NotRequired[int] class TicketDetail(TypedDict): object: Literal["ticket_detail"] ticket: "Ticket" messages: List["TicketMessage"] class TicketList(TypedDict): object: Literal["list"] data: List["Ticket"] next_cursor: Optional[str] class TicketMessage(TypedDict): object: Literal["ticket_message"] id: int author: Literal["user", "staff", "system"] body: str created_at: str class TicketReply(TypedDict): body: str class Tier(TypedDict): id: int name_fa: str discount_bps: int class TokenPair(TypedDict): object: Literal["token"] token_type: Literal["Bearer"] access_token: str expires_in: int refresh_token: str refresh_expires_in: int user_id: int class TrackingLink(TypedDict): object: Literal["tracking_link"] order_id: int url: str class TrackingLinkRequest(TypedDict): order_id: int class Transaction(TypedDict): object: Literal["transaction"] id: int kind: str amount_irr: int balance_after_irr: int ref_type: str ref_id: str memo: str created_at: str class TransactionList(TypedDict): object: Literal["list"] data: List["Transaction"] next_cursor: Optional[str] class WebhookDelivery(TypedDict): object: Literal["webhook_delivery"] id: int endpoint_id: int event_id: int attempt: int status: str response_code: Optional[int] duration_ms: Optional[int] error: str next_attempt_at: Optional[str] created_at: str updated_at: str class WebhookDeliveryList(TypedDict): object: Literal["list"] data: List["WebhookDelivery"] next_cursor: Optional[str] class WebhookEndpoint(TypedDict): object: Literal["webhook_endpoint"] id: int url: str events: List[str] livemode: bool active: bool failing_since: Optional[str] created_at: str updated_at: str class WebhookEndpointCreate(TypedDict): url: str events: NotRequired[List[str]] class WebhookEndpointCreated(TypedDict): object: Literal["webhook_endpoint"] id: int url: str events: List[str] livemode: bool active: bool failing_since: Optional[str] created_at: str updated_at: str secret: str class WebhookEndpointList(TypedDict): object: Literal["list"] data: List["WebhookEndpoint"] next_cursor: Optional[str] class WebhookEndpointUpdate(TypedDict): active: NotRequired[bool] events: NotRequired[List[str]] url: NotRequired[str] class SmmError(Exception): """The standard error object, raised for every non-2xx response.""" def __init__(self, status: int, error: Dict[str, Any]): super().__init__(error.get("message") or f"request failed with status {status}") self.status = status self.type = error.get("type", "api_error") self.code = error.get("code", "unknown") self.message_fa = error.get("message_fa", "") self.param = error.get("param") self.request_id = error.get("request_id", "") class SmmClient: """A Customer API client. api_key is an API key (smm_live_/smm_test_) or an app access token.""" def __init__(self, api_key: str, base_url: str, *, max_retries: int = 2, timeout: float = 30.0): if not api_key: raise ValueError("api_key is required") self.api_key = api_key self.base_url = base_url.rstrip("/") + "/api/v3" self.max_retries = max_retries self.timeout = timeout self.rate_limit: Optional[Dict[str, int]] = None def request(self, method: str, path: str, *, body: Any = None, query: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None) -> Any: """Sends a request; most code calls the typed methods below instead.""" url = self.base_url + path if query: q = {k: v for k, v in query.items() if v is not None} if q: url += "?" + urllib.parse.urlencode(q) headers = {"Authorization": "Bearer " + self.api_key, "Accept": "application/json", "User-Agent": "smm-sdk-python/3"} data = None if body is not None: data = json.dumps(body, ensure_ascii=False).encode() headers["Content-Type"] = "application/json" if method == "POST": headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4()) attempt = 0 while True: req = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=self.timeout) as res: self._limits(res.headers) raw = res.read() return json.loads(raw) if raw else None except urllib.error.HTTPError as e: self._limits(e.headers) raw = e.read() if (e.code == 429 or e.code >= 500) and attempt < self.max_retries: after = float(e.headers.get("Retry-After") or 0) time.sleep(after if after > 0 else 0.5 * 2 ** attempt) attempt += 1 continue try: err = json.loads(raw).get("error", {}) except ValueError: err = {} raise SmmError(e.code, err) from None except urllib.error.URLError: if attempt < self.max_retries: time.sleep(0.5 * 2 ** attempt) attempt += 1 continue raise def _limits(self, headers: Any) -> None: if headers and headers.get("RateLimit-Limit"): self.rate_limit = { "limit": int(headers.get("RateLimit-Limit")), "remaining": int(headers.get("RateLimit-Remaining") or 0), "reset": int(headers.get("RateLimit-Reset") or 1), } def paginate(self, list_fn: Any, **params: Any) -> Iterator[Any]: """Iterates every item of a list method, following next_cursor.""" cursor = None while True: page = list_fn(cursor=cursor, **params) yield from page["data"] cursor = page.get("next_cursor") if not cursor: return # ---- operations ---------------------------------------------------- def logout(self, *, idempotency_key: Optional[str] = None) -> None: "Sign the app out (revokes the current app session)" return self.request("POST", "/auth/logout", body=None, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def request_otp(self, body: OtpRequest, *, idempotency_key: Optional[str] = None) -> "OtpChallenge": "Send a login code to a phone number" return self.request("POST", "/auth/otp", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def verify_otp(self, body: OtpVerify, *, idempotency_key: Optional[str] = None) -> "TokenPair": "Verify the code and receive app tokens" return self.request("POST", "/auth/otp/verify", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def refresh_token(self, body: RefreshRequest, *, idempotency_key: Optional[str] = None) -> "TokenPair": "Rotate the refresh token and get a new access token" return self.request("POST", "/auth/refresh", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def get_balance(self) -> "Balance": "Wallet balance (the test wallet for test keys) (scope: read)" return self.request("GET", "/balance", body=None, query=None) # type: ignore[return-value] def get_batch(self, id: int) -> "Batch": "A batch and its orders (scope: read)" return self.request("GET", f"/batches/{id}", body=None, query=None) # type: ignore[return-value] def list_categories(self, *, platform: Optional[str] = None) -> "CategoryList": "Categories (scope: read)" return self.request("GET", "/categories", body=None, query={"platform": platform}) # type: ignore[return-value] def redeem_coupon(self, body: CouponRedeem, *, idempotency_key: Optional[str] = None) -> "CouponRedemption": "Redeem a voucher (credited now) or a deposit coupon (applied to the next deposit) (scope: payments)" return self.request("POST", "/coupons/redeem", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def list_events(self, *, type: Optional[str] = None, created_after: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None) -> "EventList": "Your events from the last 30 days, newest first (scope: read)" return self.request("GET", "/events", body=None, query={"type": type, "created_after": created_after, "limit": limit, "cursor": cursor}) # type: ignore[return-value] def get_event(self, id: int) -> "Event": "An event (scope: read)" return self.request("GET", f"/events/{id}", body=None, query=None) # type: ignore[return-value] def list_favorites(self) -> "FavoriteList": "Favorite services (scope: read)" return self.request("GET", "/favorites", body=None, query=None) # type: ignore[return-value] def add_favorite(self, body: FavoriteCreate, *, idempotency_key: Optional[str] = None) -> "Favorite": "Add a favorite service (scope: orders)" return self.request("POST", "/favorites", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def delete_favorite(self, id: int) -> None: "Remove a favorite (the id is the service id) (scope: orders)" return self.request("DELETE", f"/favorites/{id}", body=None, query=None) # type: ignore[return-value] def resolve_link(self, body: LinkResolveRequest, *, idempotency_key: Optional[str] = None) -> "LinkResolution": "Detect the platform and target of a link, and the services that accept it (scope: read)" return self.request("POST", "/links/resolve", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def get_me(self) -> "Me": "The signed-in user and the current credential (scope: read)" return self.request("GET", "/me", body=None, query=None) # type: ignore[return-value] def get_meta(self) -> "Meta": "API metadata and server time" return self.request("GET", "/meta", body=None, query=None) # type: ignore[return-value] def list_notifications(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> "NotificationList": "In-app notifications, newest first (scope: read)" return self.request("GET", "/notifications", body=None, query={"limit": limit, "cursor": cursor}) # type: ignore[return-value] def mark_notifications_read(self, body: MarkRead, *, idempotency_key: Optional[str] = None) -> "MarkReadResult": "Mark one notification (id) or all of them read (scope: read)" return self.request("POST", "/notifications/read", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def list_orders(self, *, status: Optional[str] = None, service_id: Optional[int] = None, client_label: Optional[str] = None, link: Optional[str] = None, batch_id: Optional[int] = None, created_after: Optional[str] = None, created_before: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None) -> "OrderList": "Your orders, newest first (scope: read)" return self.request("GET", "/orders", body=None, query={"status": status, "service_id": service_id, "client_label": client_label, "link": link, "batch_id": batch_id, "created_after": created_after, "created_before": created_before, "limit": limit, "cursor": cursor}) # type: ignore[return-value] def create_order(self, body: OrderCreate, *, idempotency_key: Optional[str] = None) -> "Order": "Place an order (always send an Idempotency-Key) (scope: orders)" return self.request("POST", "/orders", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def create_order_batch(self, body: BatchCreate, *, idempotency_key: Optional[str] = None) -> "BatchResult": "Place up to 100 orders in one charge (scope: orders)" return self.request("POST", "/orders/batch", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def quote_order(self, body: QuoteRequest, *, idempotency_key: Optional[str] = None) -> "Quote": "Price an order without placing it (scope: read)" return self.request("POST", "/orders/quote", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def get_order(self, id: int) -> "Order": "An order (scope: read)" return self.request("GET", f"/orders/{id}", body=None, query=None) # type: ignore[return-value] def cancel_order(self, id: int, *, idempotency_key: Optional[str] = None) -> "Order": "Ask to cancel an order (the refund follows when it is canceled) (scope: orders)" return self.request("POST", f"/orders/{id}/cancel", body=None, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def refill_order(self, id: int, *, idempotency_key: Optional[str] = None) -> "Refill": "Request a refill within the service's refill window (scope: orders)" return self.request("POST", f"/orders/{id}/refill", body=None, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def create_payment(self, body: PaymentCreate, *, idempotency_key: Optional[str] = None) -> "Payment": "Start a wallet top-up through the gateway (scope: payments)" return self.request("POST", "/payments", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def get_payment(self, id: int) -> "Payment": "A payment (scope: read)" return self.request("GET", f"/payments/{id}", body=None, query=None) # type: ignore[return-value] def list_platforms(self) -> "PlatformList": "Platforms (scope: read)" return self.request("GET", "/platforms", body=None, query=None) # type: ignore[return-value] def get_referrals(self) -> "Referrals": "Your referral link, totals and recent commissions (scope: read)" return self.request("GET", "/referrals", body=None, query=None) # type: ignore[return-value] def list_refills(self, *, order_id: Optional[int] = None, limit: Optional[int] = None) -> "RefillList": "Your refills, newest first (scope: read)" return self.request("GET", "/refills", body=None, query={"order_id": order_id, "limit": limit}) # type: ignore[return-value] def get_refill(self, id: int) -> "Refill": "A refill (scope: read)" return self.request("GET", f"/refills/{id}", body=None, query=None) # type: ignore[return-value] def list_request_logs(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> "RequestLogList": "Your API request log (writes and errors, 14 days) (scope: read)" return self.request("GET", "/request-logs", body=None, query={"limit": limit, "cursor": cursor}) # type: ignore[return-value] def list_services(self, *, platform: Optional[str] = None, category: Optional[str] = None, target_kind: Optional[str] = None, q: Optional[str] = None) -> "ServiceList": "Active services with your prices (scope: read)" return self.request("GET", "/services", body=None, query={"platform": platform, "category": category, "target_kind": target_kind, "q": q}) # type: ignore[return-value] def get_service(self, id: int) -> "Service": "A service (scope: read)" return self.request("GET", f"/services/{id}", body=None, query=None) # type: ignore[return-value] def list_targets(self, *, tag: Optional[str] = None) -> "TargetList": "Saved targets (links and usernames) (scope: read)" return self.request("GET", "/targets", body=None, query={"tag": tag}) # type: ignore[return-value] def create_target(self, body: TargetCreate, *, idempotency_key: Optional[str] = None) -> "Target": "Save a target (scope: orders)" return self.request("POST", "/targets", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def delete_target(self, id: int) -> None: "Delete a saved target (scope: orders)" return self.request("DELETE", f"/targets/{id}", body=None, query=None) # type: ignore[return-value] def list_templates(self) -> "TemplateList": "Order templates (bulk lines) (scope: read)" return self.request("GET", "/templates", body=None, query=None) # type: ignore[return-value] def create_template(self, body: TemplateCreate, *, idempotency_key: Optional[str] = None) -> "Template": "Save a template (same name replaces it) (scope: orders)" return self.request("POST", "/templates", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def delete_template(self, id: int) -> None: "Delete a template (scope: orders)" return self.request("DELETE", f"/templates/{id}", body=None, query=None) # type: ignore[return-value] def test_top_up(self, body: TestBalanceRequest, *, idempotency_key: Optional[str] = None) -> "Balance": "Add funds to the test wallet (test keys only) (scope: read) Test mode only." return self.request("POST", "/test/balance", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def list_tickets(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> "TicketList": "Your support tickets, latest activity first (scope: support)" return self.request("GET", "/tickets", body=None, query={"limit": limit, "cursor": cursor}) # type: ignore[return-value] def create_ticket(self, body: TicketCreate, *, idempotency_key: Optional[str] = None) -> "TicketDetail": "Open a ticket (scope: support)" return self.request("POST", "/tickets", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def get_ticket(self, id: int) -> "TicketDetail": "A ticket with its messages (scope: support)" return self.request("GET", f"/tickets/{id}", body=None, query=None) # type: ignore[return-value] def reply_ticket(self, id: int, body: TicketReply, *, idempotency_key: Optional[str] = None) -> "TicketMessage": "Reply to a ticket (reopens it) (scope: support)" return self.request("POST", f"/tickets/{id}/messages", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def create_tracking_link(self, body: TrackingLinkRequest, *, idempotency_key: Optional[str] = None) -> "TrackingLink": "A public tracking link for an order (no login needed to open it) (scope: read)" return self.request("POST", "/tracking-links", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def list_transactions(self, *, kind: Optional[str] = None, created_after: Optional[str] = None, created_before: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None) -> "TransactionList": "Wallet ledger lines, newest first (scope: read)" return self.request("GET", "/transactions", body=None, query={"kind": kind, "created_after": created_after, "created_before": created_before, "limit": limit, "cursor": cursor}) # type: ignore[return-value] def redeliver_webhook(self, id: int, *, idempotency_key: Optional[str] = None) -> "Accepted": "Send a delivery again (scope: webhooks)" return self.request("POST", f"/webhook-deliveries/{id}/redeliver", body=None, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def list_webhook_endpoints(self) -> "WebhookEndpointList": "Your webhook endpoints (for this mode) (scope: webhooks)" return self.request("GET", "/webhook-endpoints", body=None, query=None) # type: ignore[return-value] def create_webhook_endpoint(self, body: WebhookEndpointCreate, *, idempotency_key: Optional[str] = None) -> "WebhookEndpointCreated": "Create an endpoint; the signing secret is shown once (scope: webhooks)" return self.request("POST", "/webhook-endpoints", body=body, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def get_webhook_endpoint(self, id: int) -> "WebhookEndpoint": "An endpoint (scope: webhooks)" return self.request("GET", f"/webhook-endpoints/{id}", body=None, query=None) # type: ignore[return-value] def update_webhook_endpoint(self, id: int, body: WebhookEndpointUpdate) -> "WebhookEndpoint": "Change the URL, the events or turn it on or off (scope: webhooks)" return self.request("PATCH", f"/webhook-endpoints/{id}", body=body, query=None) # type: ignore[return-value] def delete_webhook_endpoint(self, id: int) -> None: "Delete an endpoint (scope: webhooks)" return self.request("DELETE", f"/webhook-endpoints/{id}", body=None, query=None) # type: ignore[return-value] def list_webhook_deliveries(self, id: int, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> "WebhookDeliveryList": "The endpoint's delivery log (scope: webhooks)" return self.request("GET", f"/webhook-endpoints/{id}/deliveries", body=None, query={"limit": limit, "cursor": cursor}) # type: ignore[return-value] def test_webhook_endpoint(self, id: int, *, idempotency_key: Optional[str] = None) -> "Accepted": "Send a test event to the endpoint (scope: webhooks)" return self.request("POST", f"/webhook-endpoints/{id}/test", body=None, query=None, idempotency_key=idempotency_key) # type: ignore[return-value] def verify_webhook(secret: str, header: str, raw_body: bytes, tolerance: int = 300, now: Optional[float] = None) -> bool: """Verifies the Smm-Signature header: t=,v1=. Pass the raw request body exactly as received. Rejects timestamps older than tolerance seconds. Several v1= values may be present while a secret rotates. """ t, sigs = 0, [] for part in header.split(","): k, _, v = part.strip().partition("=") if k == "t" and v.isdigit(): t = int(v) elif k == "v1": sigs.append(v) if not t or not sigs or abs((now if now is not None else time.time()) - t) > tolerance: return False expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return any(hmac.compare_digest(expected, s) for s in sigs)