Skip to content

Self-improving AI Employees for everyone

feat(nodes): add the Dodo Payments action node

trohitgda32e21cdf20
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index 2ffecf5e..26ab41c7 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -1078,6 +1078,39 @@
},
"instructions": "Click 'Login with Stripe' to open the Stripe Dashboard. After you authorise, the CLI stores credentials at ~/.config/stripe/config.toml and the listen daemon starts automatically. The Stripe CLI is downloaded automatically on first use unless one is already on PATH (manual install: https://stripe.com/docs/stripe-cli#install)."
},
+ "dodo_payments": {
+ "name": "Dodo Payments",
+ "publisher": "Dodo Payments",
+ "verified": true,
+ "consumer_category": "business",
+ "description": "Take payments, refund orders and manage subscriptions.",
+ "category": "payments",
+ "category_label": "Payments",
+ "color": "dracula.green",
+ "kind": "apiKey",
+ "icon_ref": "/api/schemas/credentials/dodo_payments/icon",
+ "fields": [
+ {
+ "key": "apiKey",
+ "label": "API Key",
+ "type": "password",
+ "secret": true,
+ "placeholder": "Developer -> API Keys in the Dodo Payments dashboard",
+ "required": true,
+ "help": "A test-mode or a live-mode key. Validation finds which, and the nodes then work in that mode."
+ },
+ {
+ "key": "dodo_payments_webhook_key",
+ "label": "Webhook Secret (for the trigger)",
+ "type": "password",
+ "secret": true,
+ "placeholder": "whsec_...",
+ "required": false,
+ "help": "The signing secret of the Dodo webhook endpoint that posts to /webhook/dodo-payments. Only needed to receive events."
+ }
+ ],
+ "instructions": "Create an API key in the Dodo Payments dashboard (Developer -> API Keys); a read-only key can look things up but cannot refund or cancel. Paste it and validate: validation finds whether it is a test-mode or a live-mode key, and every call then goes to that mode. To receive events, add a webhook endpoint (Developer -> Webhooks) that posts to https://<your OpenCompany address>/webhook/dodo-payments, then save its signing secret (whsec_...) below."
+ },
"vercel": {
"name": "Vercel",
"publisher": "Vercel",
diff --git a/server/nodes/dodo_payments/__init__.py b/server/nodes/dodo_payments/__init__.py
new file mode 100644
index 00000000..3248aca8
--- /dev/null
+++ b/server/nodes/dodo_payments/__init__.py
@@ -0,0 +1,27 @@
+"""Plugins for the 'payments' palette group — Dodo Payments via the official
+dodopayments SDK.
+
+``dodoPaymentsAction`` (AI tool ``dodo_payments_action``): typed payment,
+subscription, customer, checkout and refund operations, ``call`` for any SDK
+endpoint, and ``list_operations`` to discover them. Auth is the API key saved
+in Credentials -> Dodo Payments, whose mode (test or live) validation finds.
+The SDK is imported lazily (``_sdk.py``), so the plugin registers and the
+credentials modal answers even without it.
+"""
+
+from __future__ import annotations
+
+from services.node_output_schemas import register_output_schema
+from services.ws_handler_registry import register_option_loader
+
+from ._credentials import DodoPaymentsCredential
+from ._sdk import load_dodo_payments_endpoints
+from .dodo_payments_action import DodoPaymentsActionNode, DodoPaymentsActionOutput
+
+register_output_schema("dodoPaymentsAction", DodoPaymentsActionOutput)
+register_option_loader("dodoPaymentsEndpoints", load_dodo_payments_endpoints)
+
+__all__ = [
+ "DodoPaymentsActionNode",
+ "DodoPaymentsCredential",
+]
diff --git a/server/nodes/dodo_payments/_credentials.py b/server/nodes/dodo_payments/_credentials.py
new file mode 100644
index 00000000..d71f2f2a
--- /dev/null
+++ b/server/nodes/dodo_payments/_credentials.py
@@ -0,0 +1,91 @@
+"""Dodo Payments credential — an API key kept in OpenCompany's encrypted
+credential store (``ApiKeyCredential`` shape), plus two companion rows.
+
+Three rows under one provider:
+
+* ``apiKey`` (stored under the provider id ``dodo_payments``) — the API key,
+ the field the credentials modal validates;
+* ``dodo_payments_mode`` — ``test_mode`` or ``live_mode``, written by
+ validation, never typed by the owner;
+* ``dodo_payments_webhook_key`` — the ``whsec_`` signing secret of the Dodo
+ webhook endpoint that posts to OpenCompany, read by Dodo Payments Receive.
+
+A Dodo key works only in the mode it was created in and says nothing about
+which (https://docs.dodopayments.com/miscellaneous/test-mode-vs-live-mode).
+Validation asks each mode in turn, test first, and saves the one that
+accepted the key; every call then goes to that mode's base URL, so a node
+never reaches live payments with a key the owner made for testing. The key
+is always passed to the SDK explicitly, so a ``DODO_PAYMENTS_API_KEY`` in the
+server environment never authenticates a node.
+
+This module stays free of the SDK: the plugin registers and the modal
+answers even when ``dodopayments`` is missing.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, Mapping
+
+from services.plugin.credential import ApiKeyCredential, ProbeResult
+
+MODE_FIELD = "dodo_payments_mode"
+WEBHOOK_KEY_FIELD = "dodo_payments_webhook_key"
+# The SDK's environment names, in the order validation asks them.
+MODES = ("test_mode", "live_mode")
+
+
+class DodoPaymentsCredential(ApiKeyCredential):
+ id = "dodo_payments"
+ display_name = "Dodo Payments"
+ category = "Payments"
+ docs_url = "https://docs.dodopayments.com/api-reference/introduction"
+ key_location = "bearer"
+ extra_fields = (MODE_FIELD, WEBHOOK_KEY_FIELD)
+
+ @classmethod
+ async def validate(cls, data: Dict[str, Any]) -> Dict[str, Any]:
+ """The base scaffold, then the mode the probe found, saved beside the
+ key it belongs to."""
+ response = await super().validate(data)
+ if response.get("valid"):
+ from services.plugin.deps import get_auth_service
+
+ await get_auth_service().store_api_key(
+ MODE_FIELD, response["mode"], models=[], session_id=data.get("session_id", "default")
+ )
+ return response
+
+ @classmethod
+ async def _probe(cls, api_key: str) -> ProbeResult:
+ """Find the mode the key belongs to (``_sdk.key_mode``). Stores
+ nothing; :meth:`validate` saves the key and its mode."""
+ from services.plugin import NodeUserError
+
+ from ._sdk import key_mode
+
+ try:
+ mode = await key_mode(api_key, timeout=cls.probe_timeout_seconds)
+ except NodeUserError as exc:
+ return ProbeResult(valid=False, message=str(exc))
+ return ProbeResult(
+ valid=True,
+ message=f"Dodo Payments API key is valid ({mode.replace('_', ' ')})",
+ extra={"mode": mode},
+ )
+
+
+def stored_mode(secrets: Mapping[str, Any]) -> str:
+ """The mode saved when the key was validated. Missing, it raises the same
+ annotated ``PermissionError`` as a missing key, so the node answers with
+ the ``PermissionDeniedError`` envelope that points at the modal."""
+ mode = secrets.get(MODE_FIELD)
+ if mode not in MODES:
+ err = PermissionError(
+ "Validate the Dodo Payments API key in Credentials -> Dodo Payments: "
+ "validation finds whether it is a test or a live key."
+ )
+ err.provider = DodoPaymentsCredential.id
+ err.reason = "missing"
+ err.auth = DodoPaymentsCredential.auth
+ raise err
+ return mode
diff --git a/server/nodes/dodo_payments/_sdk.py b/server/nodes/dodo_payments/_sdk.py
new file mode 100644
index 00000000..abdf6998
--- /dev/null
+++ b/server/nodes/dodo_payments/_sdk.py
@@ -0,0 +1,372 @@
+"""Everything that touches the ``dodopayments`` SDK, imported lazily.
+
+The node never imports the SDK at module level: the plugin must register (and
+the credentials modal must answer) even when it is missing. Every function
+here that needs the SDK imports it inside its body.
+
+Three jobs:
+
+* **Clients**: :func:`open_client` builds an ``AsyncDodoPayments`` for one
+ operation with the key and its mode's base URL passed explicitly, so no
+ ``DODO_PAYMENTS_*`` variable in the server environment authenticates a node
+ or points it elsewhere. A call that writes runs with the SDK's retries off:
+ the SDK retries POSTs too, and Dodo's API takes no idempotency key, so a
+ retried refund could be refunded twice.
+* **Introspection** (no credentials, no network): :func:`endpoint_index`
+ reflects every API call the installed SDK makes, with its HTTP route and
+ parameters, for ``list_operations``, the endpoint dropdown, ``call`` and
+ the approval rule. Nothing is vendored: an SDK upgrade is all it takes to
+ pick up new endpoints.
+* **Calls and shaping**: :func:`invoke` runs one SDK method, :func:`to_plain`
+ returns the API's own JSON, and :func:`raise_user_error` maps the SDK's
+ errors onto ``NodeUserError``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import difflib
+import functools
+import inspect
+import json
+import re
+from dataclasses import asdict, dataclass
+from typing import Any, AsyncIterator, Dict, List, Mapping, NoReturn, Tuple
+
+from core.logging import get_logger
+from services.plugin import NodeUserError
+
+from ._credentials import MODES
+
+logger = get_logger(__name__)
+
+# The SDK's own default for calls that only read; calls that write get none.
+READ_RETRIES = 2
+# Per-request timeout for node calls (the SDK's default, made explicit).
+CALL_TIMEOUT_SECONDS = 60.0
+_BODY_PREVIEW_CHARS = 500
+_MAX_SUGGESTIONS = 5
+# Keyword arguments every SDK method takes besides the API's own parameters.
+# extra_headers could replace the Authorization header, so neither the index
+# nor `call` lets them through.
+_SDK_KWARGS = frozenset({"extra_headers", "extra_query", "extra_body", "timeout"})
+# Webhook endpoints and their signing secrets configure this integration
+# itself, and a secret has no use in an agent's hands: they stay in the Dodo
+# dashboard, out of the index and so out of `call`.
+_EXCLUDED_RESOURCES = frozenset({"webhooks"})
+# How a generated method makes its request: ``self._get(path_template("/x/{id}", ...``.
+_ROUTE_RE = re.compile(r"self\._(get_api_list|get|post|patch|put|delete)\(\s*(?:path_template\(\s*)?[\"'](/[^\"']*)[\"']")
+
+
+# ---------------------------------------------------------------------------
+# Clients
+# ---------------------------------------------------------------------------
+
+
+async def open_client(api_key: str, mode: str, *, max_retries: int, timeout: float) -> AsyncIterator[Any]:
+ """An ``AsyncDodoPayments`` for one operation, closed afterwards."""
+ try:
+ from dodopayments import ENVIRONMENTS, AsyncDodoPayments
+ except ImportError as exc:
+ raise NodeUserError("The 'dodopayments' package is not installed. Run `uv sync` in server/.") from exc
+ async with AsyncDodoPayments(
+ bearer_token=api_key,
+ base_url=ENVIRONMENTS[mode],
+ max_retries=max_retries,
+ timeout=timeout,
+ ) as client:
+ yield client
+
+
+async def key_mode(api_key: str, *, timeout: float) -> str:
+ """The mode a key belongs to. Each mode is asked to list the brands (every
+ business has one), test first; a 401 means the key is not that mode's."""
+ from dodopayments import APIError, AuthenticationError
+
+ for mode in MODES:
+ async with open_client(api_key, mode, max_retries=0, timeout=timeout) as client:
+ try:
+ await client.brands.list()
+ except AuthenticationError:
+ continue
+ except APIError as exc:
+ raise_user_error(exc, "brands.list", writes=False)
+ return mode
+ raise NodeUserError(
+ "Dodo Payments rejected this API key in both test and live mode. "
+ "Copy it again from Developer -> API Keys in the Dodo Payments dashboard."
+ )
+
+
+# ---------------------------------------------------------------------------
+# Introspection
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class ParamInfo:
+ name: str
+ type: str
+ required: bool
+
+
+@dataclass(frozen=True)
+class EndpointInfo:
+ endpoint: str # the SDK's dotted method, "customers.wallets.list"
+ http_method: str # "GET" / "POST" / "PATCH" / "PUT" / "DELETE"
+ path: str # "/customers/{customer_id}/wallets"
+ params: Tuple[ParamInfo, ...]
+ deprecated: bool
+
+ @property
+ def reads(self) -> bool:
+ return self.http_method == "GET"
+
+ def as_dict(self) -> Dict[str, Any]:
+ return asdict(self) | {"params": [asdict(p) for p in self.params], "reads": self.reads}
+
+
+def _resources(owner: Any, resource_type: type) -> List[Tuple[str, Any]]:
+ """The public resources hanging off a client or a resource: its cached
+ properties that build an API resource (``with_raw_response`` and
+ ``with_streaming_response`` are wrappers, not resources)."""
+ found = []
+ for name, member in inspect.getmembers(type(owner)):
+ if name.startswith(("_", "with_")) or not isinstance(member, functools.cached_property):
+ continue
+ child = getattr(owner, name)
+ if isinstance(child, resource_type):
+ found.append((name, child))
+ return found
+
+
+def _describe(endpoint: str, fn: Any) -> EndpointInfo | None:
+ """One method's route and parameters, or None for a local helper that
+ makes no request (``webhooks.unwrap``)."""
+ match = _ROUTE_RE.search(inspect.getsource(fn))
+ if match is None:
+ return None
+ verb, path = match.groups()
+ params = tuple(
+ ParamInfo(
+ name=p.name,
+ type=p.annotation if isinstance(p.annotation, str) else getattr(p.annotation, "__name__", repr(p.annotation)),
+ required=p.default is inspect.Parameter.empty,
+ )
+ for p in inspect.signature(fn).parameters.values()
+ if p.name != "self" and p.name not in _SDK_KWARGS
+ )
+ return EndpointInfo(
+ endpoint=endpoint,
+ http_method="GET" if verb == "get_api_list" else verb.upper(),
+ path=path,
+ params=params,
+ deprecated=getattr(fn, "__deprecated__", None) is not None,
+ )
+
+
+def _collect(path: str, resource: Any, resource_type: type, out: List[EndpointInfo]) -> None:
+ for name, fn in inspect.getmembers(type(resource), inspect.isfunction):
+ if name.startswith("_"):
+ continue
+ info = _describe(f"{path}.{name}", fn)
+ if info is not None:
+ out.append(info)
+ for name, child in _resources(resource, resource_type):
+ _collect(f"{path}.{name}", child, resource_type, out)
+
+
[email protected]_cache(maxsize=1)
+def endpoint_index() -> Tuple[EndpointInfo, ...]:
+ """Every API call the installed SDK makes, by reflecting a throwaway
+ client (the sync one, whose methods mirror the async client's). No
+ network. Built once per process; async callers run it in a thread."""
+ try:
+ from dodopayments import DodoPayments
+ from dodopayments._resource import SyncAPIResource
+ except ImportError as exc:
+ raise NodeUserError("The 'dodopayments' package is not installed. Run `uv sync` in server/.") from exc
+ entries: List[EndpointInfo] = []
+ with DodoPayments(bearer_token="introspection", base_url="http://introspection.invalid", max_retries=0) as client:
+ for name, resource in _resources(client, SyncAPIResource):
+ if name not in _EXCLUDED_RESOURCES:
+ _collect(name, resource, SyncAPIResource, entries)
+ entries.sort(key=lambda entry: entry.endpoint)
+ logger.info("dodo payments endpoint index built", endpoints=len(entries))
+ return tuple(entries)
+
+
[email protected]_cache(maxsize=1)
+def _by_endpoint() -> Dict[str, EndpointInfo]:
+ return {entry.endpoint: entry for entry in endpoint_index()}
+
+
+def resolve_endpoint(raw: str) -> EndpointInfo:
+ """The index entry for a dotted endpoint name, with the closest names on
+ a miss."""
+ name = (raw or "").strip()
+ if not name:
+ raise NodeUserError(
+ "endpoint is required (e.g. payouts.list). Use operation=list_operations to discover endpoints."
+ )
+ index = _by_endpoint()
+ if name in index:
+ return index[name]
+ suggestions = difflib.get_close_matches(name, list(index), n=_MAX_SUGGESTIONS, cutoff=0.5)
+ hint = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
+ raise NodeUserError(
+ f"Unknown Dodo Payments endpoint '{name}'.{hint} Use operation=list_operations to discover endpoints."
+ )
+
+
+def endpoint_writes(raw: str) -> bool:
+ """Whether calling this endpoint changes anything: every method but GET.
+ An unknown name counts as writing."""
+ info = _by_endpoint().get((raw or "").strip())
+ return info is None or not info.reads
+
+
+def check_request(info: EndpointInfo, request: Mapping[str, Any]) -> Dict[str, Any]:
+ """The request's keyword arguments, checked against the method's
+ parameters before any network use."""
+ problems = []
+ unknown = sorted(set(request) - {p.name for p in info.params})
+ if unknown:
+ problems.append(f"unknown: {', '.join(unknown)}")
+ missing = sorted(p.name for p in info.params if p.required and p.name not in request)
+ if missing:
+ problems.append(f"missing: {', '.join(missing)}")
+ if problems:
+ accepted = ", ".join(f"{p.name}{' (required)' if p.required else ''}" for p in info.params) or "none"
+ raise NodeUserError(f"{info.endpoint} rejected the request ({'; '.join(problems)}). Accepted: {accepted}.")
+ return dict(request)
+
+
+# ---------------------------------------------------------------------------
+# Calls + shaping
+# ---------------------------------------------------------------------------
+
+
+def _method(client: Any, endpoint: str) -> Any:
+ target = client
+ for part in endpoint.split("."):
+ target = getattr(target, part)
+ return target
+
+
+async def invoke(client: Any, endpoint: str, request: Mapping[str, Any], *, writes: bool) -> Any:
+ """``client.<endpoint>(**request)`` as plain data. A list method answers
+ with its first page (the request's ``page_number`` / ``page_size`` pick
+ which): the SDK's own auto-pagination asks for page 2 after page 0."""
+ from dodopayments import APIError
+
+ try:
+ return to_plain(await _method(client, endpoint)(**request))
+ except APIError as exc:
+ raise_user_error(exc, endpoint, writes=writes)
+ except ValueError as exc: # the SDK's own argument checks, e.g. an empty id
+ raise NodeUserError(f"Dodo Payments {endpoint} rejected the request: {exc}") from exc
+
+
+def to_plain(value: Any) -> Any:
+ """The API's own JSON: a model with the fields Dodo sent, a page as
+ ``{"items": [...]}``."""
+ if value is None or isinstance(value, (str, int, float, bool)):
+ return value
+ if isinstance(value, (list, tuple)):
+ return [to_plain(item) for item in value]
+ if isinstance(value, dict):
+ return {key: to_plain(item) for key, item in value.items()}
+ to_dict = getattr(value, "to_dict", None)
+ if callable(to_dict):
+ return to_dict(mode="json")
+ raise NodeUserError(
+ f"This endpoint answers with a file ({type(value).__name__}), such as an invoice PDF, "
+ "which the node cannot return."
+ )
+
+
+def _preview(value: Any) -> str:
+ if value is None:
+ return ""
+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, default=str)
+ return text if len(text) <= _BODY_PREVIEW_CHARS else text[:_BODY_PREVIEW_CHARS] + "..."
+
+
+def raise_user_error(exc: Exception, endpoint: str, *, writes: bool) -> NoReturn:
+ """Translate an SDK ``APIError`` into a ``NodeUserError`` carrying Dodo's
+ own error code and message (the body is ``{"code", "message"}``)."""
+ from dodopayments import (
+ APIConnectionError,
+ APIStatusError,
+ APITimeoutError,
+ AuthenticationError,
+ InternalServerError,
+ PermissionDeniedError,
+ RateLimitError,
+ )
+
+ unknown_outcome = False
+ if isinstance(exc, APIStatusError):
+ body = exc.body if isinstance(exc.body, dict) else {}
+ code = str(body.get("code") or "")
+ detail = str(body.get("message") or "") or _preview(exc.body)
+ message = f"Dodo Payments {endpoint} failed ({exc.status_code}{' ' + code if code else ''}): {detail}"
+ if isinstance(exc, AuthenticationError):
+ message += ". The API key was rejected: validate it again in Credentials -> Dodo Payments."
+ elif isinstance(exc, PermissionDeniedError):
+ message += ". The key lacks this permission (a read-only key cannot write), or the business is not live yet."
+ elif isinstance(exc, RateLimitError):
+ message += ". Dodo Payments rate-limited the request; try again shortly."
+ elif isinstance(exc, InternalServerError):
+ unknown_outcome = True
+ elif isinstance(exc, APITimeoutError):
+ message = f"Dodo Payments {endpoint} timed out."
+ unknown_outcome = True
+ elif isinstance(exc, APIConnectionError):
+ message = f"Could not reach Dodo Payments for {endpoint}: {exc}"
+ unknown_outcome = True
+ else:
+ message = f"Dodo Payments {endpoint} failed: {exc}"
+ if writes and unknown_outcome:
+ message += " The change may or may not have been made: look it up before trying again."
+ raise NodeUserError(message) from exc
+
+
+# ---------------------------------------------------------------------------
+# Dropdown loader
+# ---------------------------------------------------------------------------
+
+
+async def load_dodo_payments_endpoints(params: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """``loadOptionsMethod`` for the ``endpoint`` dropdown. A missing SDK must
+ never break the parameter panel, so it degrades to no options."""
+ try:
+ index = await asyncio.to_thread(endpoint_index)
+ except NodeUserError as exc:
+ logger.warning("dodo payments endpoint loader failed", error=str(exc))
+ return []
+ return [
+ {"value": entry.endpoint, "label": entry.endpoint, "description": f"{entry.http_method} {entry.path}"}
+ for entry in index
+ ]
+
+
+__all__ = [
+ "CALL_TIMEOUT_SECONDS",
+ "EndpointInfo",
+ "ParamInfo",
+ "READ_RETRIES",
+ "check_request",
+ "endpoint_index",
+ "endpoint_writes",
+ "invoke",
+ "key_mode",
+ "load_dodo_payments_endpoints",
+ "open_client",
+ "raise_user_error",
+ "resolve_endpoint",
+ "to_plain",
+]
diff --git a/server/nodes/dodo_payments/dodo_payments.svg b/server/nodes/dodo_payments/dodo_payments.svg
new file mode 100644
index 00000000..46c8f77b
--- /dev/null
+++ b/server/nodes/dodo_payments/dodo_payments.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 121 121" fill="none">
+<path d="M60.5 0.5C27.364 0.5 0.5 27.364 0.5 60.5C0.5 93.636 27.364 120.5 60.5 120.5C93.636 120.5 120.5 93.636 120.5 60.5C120.5 27.364 93.636 0.5 60.5 0.5Z" fill="#C6FE1E"/>
+<mask id="dodo-payments-mark" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="18" y="27" width="91" height="76">
+<path d="M108.5 27.5002H18.5V102.5H108.5V27.5002Z" fill="white"/>
+</mask>
+<g mask="url(#dodo-payments-mark)">
+<path d="M53.3412 44.8038H53.3012C50.8212 44.0918 48.1972 45.5158 47.3572 47.8678C46.4292 50.3958 47.9012 53.2918 50.5012 54.0918C56.8692 55.8998 59.6052 46.7718 53.3412 44.8038Z" fill="#0D0D0D"/>
+<path d="M107.614 57.7079C99.4138 39.7479 73.2538 47.1799 70.8378 42.4759C63.7578 31.3639 50.5418 25.1239 36.2538 28.3399C34.0538 27.4599 26.4778 27.2199 21.5818 30.2999L24.5338 31.6039C24.7578 31.6999 24.6938 31.6759 25.0218 31.7959C26.3578 32.2999 26.1258 32.1559 25.1658 32.6839C22.9658 33.9719 20.2218 35.4679 18.5098 37.7159C18.5818 37.8199 22.2778 38.7079 22.2778 38.7079C22.3418 38.7239 23.0298 38.7959 22.8778 39.0999C10.7898 58.1879 31.1738 86.9959 41.0698 102.5H69.7178C65.2938 94.5799 60.2378 83.7719 61.9658 76.4359C62.2778 75.1079 62.6778 73.4199 64.3098 73.1959C68.2538 72.5639 73.5338 72.6199 77.2938 72.1959C77.2938 72.1959 77.3124 72.1959 77.3498 72.1959C78.1498 72.1559 97.7338 69.6679 102.422 81.8759C102.822 82.9959 103.742 82.2679 104.11 81.5319C107.606 74.5799 109.862 63.6359 107.63 57.7159L107.614 57.7079ZM75.9978 51.8119C74.6218 54.2679 73.6858 57.4599 73.4458 60.2439C73.3178 62.0119 73.5018 63.7559 73.6778 65.5239C73.7738 66.4999 73.7818 67.7319 72.9978 68.3719C72.3178 68.9479 71.1898 69.0039 70.0538 69.0839C64.4778 69.0599 50.8778 69.0839 45.6378 65.5159L45.6058 65.4919C37.9818 60.8439 33.9018 50.3479 38.4298 42.1959C39.8938 39.4279 42.5898 37.6279 45.6618 36.9479C49.6138 36.0439 53.9658 36.7159 57.4938 38.5639C58.9338 39.2919 60.6538 40.2519 61.9658 41.3559C64.5658 43.6279 66.7898 45.9879 70.1978 46.7159C71.7658 47.1639 73.3978 47.0999 74.9658 47.4199C77.9018 48.1239 77.1658 49.7959 75.9898 51.7959L75.9978 51.8119Z" fill="#0D0D0D"/>
+</g>
+</svg>
diff --git a/server/nodes/dodo_payments/dodo_payments_action.py b/server/nodes/dodo_payments/dodo_payments_action.py
new file mode 100644
index 00000000..d2d49637
--- /dev/null
+++ b/server/nodes/dodo_payments/dodo_payments_action.py
@@ -0,0 +1,530 @@
+"""Dodo Payments Action — typed payment operations over the official
+dodopayments SDK, plus a passthrough to any SDK endpoint.
+
+Dual-purpose: a workflow node and the AI tool ``dodo_payments_action``. Auth
+is the API key saved in Credentials -> Dodo Payments (``_credentials.py``),
+passed explicitly to every SDK client against the base URL of the mode the
+key was validated in. Every SDK touch lives in ``_sdk.py``, imported lazily.
+Results are Dodo's own response fields.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Dict, Literal, Mapping, Optional, Tuple
+
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue, coerce_blank_params
+from services.plugin.approval import ApprovalSpec
+
+from . import _sdk
+from ._credentials import DodoPaymentsCredential, stored_mode
+
+_OPERATIONS = (
+ "list_payments",
+ "get_payment",
+ "list_subscriptions",
+ "get_subscription",
+ "list_customers",
+ "get_customer",
+ "list_products",
+ "get_product",
+ "list_refunds",
+ "list_disputes",
+ "create_checkout_session",
+ "create_customer",
+ "create_customer_portal_link",
+ "create_refund",
+ "cancel_subscription",
+ "change_subscription_plan",
+ "call",
+ "list_operations",
+)
+
+# Calls that move money or change a customer's billing wait for the owner
+# while the workflow asks first; `call` does only when its endpoint writes.
+_HELD_OPERATIONS = frozenset({"create_refund", "cancel_subscription", "change_subscription_plan", "call"})
+
+# The SDK's own status and proration values (types/*_params.py); a test keeps
+# these in step with the installed SDK.
+PAYMENT_STATUSES = (
+ "succeeded",
+ "failed",
+ "cancelled",
+ "processing",
+ "requires_customer_action",
+ "requires_merchant_action",
+ "requires_payment_method",
+ "requires_confirmation",
+ "requires_capture",
+ "partially_captured",
+ "partially_captured_and_capturable",
+)
+SUBSCRIPTION_STATUSES = ("pending", "active", "on_hold", "paused", "cancelled", "failed", "expired", "past_due")
+REFUND_STATUSES = ("succeeded", "failed", "pending", "review")
+PRORATION_BILLING_MODES = (
+ "prorated_immediately",
+ "full_immediately",
+ "difference_immediately",
+ "do_not_bill",
+ "prorated_immediately_keep_cycle",
+)
+
+
+def _show(*ops: str) -> Dict[str, Any]:
+ return {"displayOptions": {"show": {"operation": list(ops)}}}
+
+
+_LISTS = ("list_payments", "list_subscriptions", "list_customers", "list_products", "list_refunds", "list_disputes")
+
+
+def _given(fields: Mapping[str, Any]) -> Dict[str, Any]:
+ """The fields that carry a value; blanks are left for Dodo's defaults."""
+ return {key: value for key, value in fields.items() if value not in (None, "")}
+
+
+class DodoPaymentsActionParams(BaseModel):
+ operation: Literal[_OPERATIONS] = "list_payments"
+
+ payment_id: str = Field(
+ default="",
+ description="Payment id",
+ json_schema_extra={"placeholder": "pay_...", **_show("get_payment", "create_refund")},
+ )
+ subscription_id: str = Field(
+ default="",
+ description="Subscription id (a filter for list_payments and list_refunds)",
+ json_schema_extra={
+ "placeholder": "sub_...",
+ **_show(
+ "get_subscription", "cancel_subscription", "change_subscription_plan", "list_payments", "list_refunds"
+ ),
+ },
+ )
+ customer_id: str = Field(
+ default="",
+ description=(
+ "Customer id. create_checkout_session: an existing customer (else customer_email). "
+ "A filter for the payment, subscription, refund and dispute lists"
+ ),
+ json_schema_extra={
+ "placeholder": "cus_...",
+ **_show(
+ "get_customer",
+ "create_customer_portal_link",
+ "create_checkout_session",
+ "list_payments",
+ "list_subscriptions",
+ "list_refunds",
+ "list_disputes",
+ ),
+ },
+ )
+ product_id: str = Field(
+ default="",
+ description=(
+ "Product id. create_checkout_session: what the customer buys; change_subscription_plan: the new plan; "
+ "create_refund: the item to refund (with amount for part of it). A filter for the payment and subscription lists"
+ ),
+ json_schema_extra={
+ "placeholder": "pdt_...",
+ **_show(
+ "get_product",
+ "create_checkout_session",
+ "change_subscription_plan",
+ "create_refund",
+ "list_payments",
+ "list_subscriptions",
+ ),
+ },
+ )
+ quantity: int = Field(
+ default=1,
+ ge=1,
+ description="Units of the product",
+ json_schema_extra=_show("create_checkout_session", "change_subscription_plan"),
+ )
+ customer_email: str = Field(
+ default="",
+ description="Customer email. create_checkout_session: a new customer; list_customers: a filter",
+ json_schema_extra={
+ "placeholder": "[email protected]",
+ **_show("create_checkout_session", "create_customer", "list_customers"),
+ },
+ )
+ customer_name: str = Field(
+ default="",
+ description="Customer name (required by create_customer)",
+ json_schema_extra={"placeholder": "Ada Lovelace", **_show("create_checkout_session", "create_customer")},
+ )
+ return_url: str = Field(
+ default="",
+ description="Where the customer lands afterwards",
+ json_schema_extra={
+ "placeholder": "https://example.com/thanks",
+ **_show("create_checkout_session", "create_customer_portal_link"),
+ },
+ )
+ discount_code: str = Field(
+ default="",
+ description="Discount code to apply",
+ json_schema_extra={"placeholder": "LAUNCH20", **_show("create_checkout_session")},
+ )
+ amount: Optional[int] = Field(
+ default=None,
+ ge=1,
+ description="Part of the product's price to refund, in the currency's smallest unit (cents); empty refunds it all",
+ json_schema_extra=_show("create_refund"),
+ )
+ reason: str = Field(
+ default="",
+ description="Why the refund is made",
+ json_schema_extra={"placeholder": "Duplicate order", **_show("create_refund")},
+ )
+ cancel_at_next_billing_date: bool = Field(
+ default=False,
+ description="Keep the subscription until the end of the paid period instead of cancelling now",
+ json_schema_extra=_show("cancel_subscription"),
+ )
+ proration_billing_mode: Literal[PRORATION_BILLING_MODES] = Field(
+ default="prorated_immediately",
+ description="How the plan change is billed",
+ json_schema_extra=_show("change_subscription_plan"),
+ )
+ payment_status: Literal[("all",) + PAYMENT_STATUSES] = Field(
+ default="all",
+ description="Only payments in this status",
+ json_schema_extra=_show("list_payments"),
+ )
+ subscription_status: Literal[("all",) + SUBSCRIPTION_STATUSES] = Field(
+ default="all",
+ description="Only subscriptions in this status",
+ json_schema_extra=_show("list_subscriptions"),
+ )
+ refund_status: Literal[("all",) + REFUND_STATUSES] = Field(
+ default="all",
+ description="Only refunds in this status",
+ json_schema_extra=_show("list_refunds"),
+ )
+ page: int = Field(default=0, ge=0, description="Page number, from 0", json_schema_extra=_show(*_LISTS))
+ page_size: int = Field(default=20, ge=1, le=100, description="Items per page", json_schema_extra=_show(*_LISTS))
+
+ # call / list_operations
+ endpoint: str = Field(
+ default="",
+ description="The SDK method as a dotted name, e.g. payouts.list or discounts.create",
+ json_schema_extra={
+ "placeholder": "payouts.list",
+ "dynamicOptions": True,
+ "loadOptionsMethod": "dodoPaymentsEndpoints",
+ **_show("call"),
+ },
+ )
+ request: Dict[str, Any] = Field(
+ default_factory=dict,
+ description="The method's keyword arguments as a JSON object, with the API's own names",
+ json_schema_extra={"editor": "json", "rows": 6, **_show("call")},
+ )
+ search: str = Field(
+ default="",
+ description="Case-insensitive substring over endpoint names and routes",
+ json_schema_extra={"placeholder": "refund", **_show("list_operations")},
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+ @model_validator(mode="before")
+ @classmethod
+ def _coerce(cls, values: Any) -> Any:
+ # The panel stores "" for cleared fields and renders `request` as
+ # text; an LLM may also stringify the JSON object.
+ return coerce_blank_params(cls, values, object_fields=("request",))
+
+
+class DodoPaymentsActionOutput(BaseModel):
+ operation: Optional[str] = None
+ mode: Optional[str] = None
+ endpoint: Optional[str] = None
+ result: Optional[Any] = None
+ count: Optional[int] = None
+ page: Optional[int] = None
+ page_size: Optional[int] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+def _changes_anything(data: Mapping[str, Any]) -> bool:
+ """Of the held operations, `call` waits for the owner only when its
+ endpoint writes (an unknown one counts as writing)."""
+ if str(data.get("operation") or "") != "call":
+ return True
+ return _sdk.endpoint_writes(str(data.get("endpoint") or ""))
+
+
+class DodoPaymentsActionNode(ActionNode):
+ type = "dodoPaymentsAction"
+ display_name = "Dodo Payments"
+ subtitle = "Payments & Billing"
+ group = ("payments", "tool")
+ description = (
+ "Dodo Payments through the official Python SDK: payments, subscriptions, customers, refunds, "
+ "checkout links, or any API endpoint"
+ )
+ component_kind = "square"
+ tool_name = "dodo_payments_action"
+ tool_description = (
+ "Work with Dodo Payments through its official Python SDK, using the API key saved in Credentials -> "
+ "Dodo Payments. The key decides the mode: every result carries mode (test_mode or live_mode). Amounts are "
+ "integers in the currency's smallest unit (cents). Reads: list_payments, list_subscriptions, list_customers, "
+ "list_products, list_refunds, list_disputes (one page each: page from 0, page_size up to 100; a full page "
+ "may have more), and get_payment / get_subscription / get_customer / get_product by id. "
+ "create_checkout_session (product_id, quantity; customer_id, or customer_email with customer_name; optional "
+ "return_url and discount_code) returns a checkout_url to send the customer (it works once, for 24 hours). "
+ "create_customer (customer_email and customer_name). create_customer_portal_link (customer_id) returns a "
+ "link where the customer manages their billing. create_refund (payment_id; refunds the whole payment, or "
+ "one item with product_id, or part of it with product_id and amount; optional reason), cancel_subscription "
+ "(subscription_id; cancel_at_next_billing_date keeps it until the paid period ends) and "
+ "change_subscription_plan (subscription_id, product_id, quantity, proration_billing_mode) move money and "
+ "may wait for the owner's approval. call reaches any other SDK method: endpoint is its dotted name (e.g. "
+ "payouts.list, discounts.create, subscriptions.charge), request its keyword arguments as a JSON object; "
+ "list_operations (optional search) lists every endpoint with its HTTP route and parameters and needs no "
+ "credentials. Reference: https://docs.dodopayments.com/api-reference/introduction"
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ # Refunds, cancellations, plan changes and `call` change real accounts.
+ annotations = {"destructive": True, "readonly": False, "open_world": True}
+ credentials = (DodoPaymentsCredential,)
+ task_queue = TaskQueue.REST_API
+ usable_as_tool = True
+ # usable_as_tool auto-sets both hide flags unless declared. This node
+ # stays wirable on the canvas through its declared `handles`; the
+ # frontend reads the flags only for a spec with no handles.
+ hide_input_handle = False
+ hide_output_handle = False
+ approval = ApprovalSpec(
+ channel="Dodo Payments",
+ action="Make a change in Dodo Payments",
+ operations=_HELD_OPERATIONS,
+ when=_changes_anything,
+ recipient=("customer_id", "customer_email"),
+ recipient_otherwise="the customer",
+ details=(
+ ("Operation", "operation"),
+ ("Payment", "payment_id"),
+ ("Subscription", "subscription_id"),
+ ("Product", "product_id"),
+ ("Amount", "amount"),
+ ("Reason", "reason"),
+ ("Endpoint", "endpoint"),
+ ),
+ outcome_labels=("Done", "Not done"),
+ )
+
+ Params = DodoPaymentsActionParams
+ Output = DodoPaymentsActionOutput
+
+ # ---- shared plumbing -------------------------------------------------
+
+ @staticmethod
+ def _shape(operation: str, **fields: Any) -> Dict[str, Any]:
+ """``{"operation": ...}`` plus every field that is not ``None``. An empty
+ ``[]`` / ``{}`` result is a real answer from Dodo and is kept."""
+ shaped: Dict[str, Any] = {"operation": operation}
+ shaped.update({k: v for k, v in fields.items() if v is not None})
+ return shaped
+
+ @staticmethod
+ def _required(value: str, field: str, operation: str, example: str) -> str:
+ value = value.strip()
+ if not value:
+ raise NodeUserError(f"{field} is required for {operation} (e.g. {example})")
+ return value
+
+ async def _run(self, ctx: NodeContext, endpoint: str, request: Mapping[str, Any], *, writes: bool) -> Tuple[Any, str]:
+ """One SDK call, against the mode of the stored key. The credential is
+ resolved first, so a missing key surfaces as the
+ ``PermissionDeniedError`` envelope that points at the modal."""
+ secrets = await DodoPaymentsCredential.resolve(user_id=ctx.credential_customer_id)
+ mode = stored_mode(secrets)
+ async with _sdk.open_client(
+ secrets["api_key"],
+ mode,
+ max_retries=0 if writes else _sdk.READ_RETRIES,
+ timeout=_sdk.CALL_TIMEOUT_SECONDS,
+ ) as client:
+ return await _sdk.invoke(client, endpoint, request, writes=writes), mode
+
+ async def _list(self, ctx: NodeContext, operation: str, endpoint: str, params: DodoPaymentsActionParams, **filters: Any) -> Any:
+ request = {"page_number": params.page, "page_size": params.page_size, **_given(filters)}
+ page, mode = await self._run(ctx, endpoint, request, writes=False)
+ items = page.get("items") or []
+ return self._shape(operation, mode=mode, result=items, count=len(items), page=params.page, page_size=params.page_size)
+
+ async def _one(self, ctx: NodeContext, operation: str, endpoint: str, request: Mapping[str, Any], *, writes: bool) -> Any:
+ result, mode = await self._run(ctx, endpoint, request, writes=writes)
+ return self._shape(operation, mode=mode, result=result)
+
+ @staticmethod
+ def _status(value: str) -> Optional[str]:
+ return None if value == "all" else value
+
+ # ---- reads -------------------------------------------------------------
+
+ @Operation("list_payments")
+ async def list_payments(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ return await self._list(
+ ctx, "list_payments", "payments.list", params,
+ customer_id=params.customer_id.strip(),
+ subscription_id=params.subscription_id.strip(),
+ product_id=params.product_id.strip(),
+ status=self._status(params.payment_status),
+ )
+
+ @Operation("get_payment")
+ async def get_payment(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ payment_id = self._required(params.payment_id, "payment_id", "get_payment", "pay_...")
+ return await self._one(ctx, "get_payment", "payments.retrieve", {"payment_id": payment_id}, writes=False)
+
+ @Operation("list_subscriptions")
+ async def list_subscriptions(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ return await self._list(
+ ctx, "list_subscriptions", "subscriptions.list", params,
+ customer_id=params.customer_id.strip(),
+ product_id=params.product_id.strip(),
+ status=self._status(params.subscription_status),
+ )
+
+ @Operation("get_subscription")
+ async def get_subscription(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ subscription_id = self._required(params.subscription_id, "subscription_id", "get_subscription", "sub_...")
+ return await self._one(
+ ctx, "get_subscription", "subscriptions.retrieve", {"subscription_id": subscription_id}, writes=False
+ )
+
+ @Operation("list_customers")
+ async def list_customers(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ return await self._list(ctx, "list_customers", "customers.list", params, email=params.customer_email.strip())
+
+ @Operation("get_customer")
+ async def get_customer(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ customer_id = self._required(params.customer_id, "customer_id", "get_customer", "cus_...")
+ return await self._one(ctx, "get_customer", "customers.retrieve", {"customer_id": customer_id}, writes=False)
+
+ @Operation("list_products")
+ async def list_products(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ return await self._list(ctx, "list_products", "products.list", params)
+
+ @Operation("get_product")
+ async def get_product(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ product_id = self._required(params.product_id, "product_id", "get_product", "pdt_...")
+ return await self._one(ctx, "get_product", "products.retrieve", {"id": product_id}, writes=False)
+
+ @Operation("list_refunds")
+ async def list_refunds(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ return await self._list(
+ ctx, "list_refunds", "refunds.list", params,
+ customer_id=params.customer_id.strip(),
+ subscription_id=params.subscription_id.strip(),
+ status=self._status(params.refund_status),
+ )
+
+ @Operation("list_disputes")
+ async def list_disputes(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ return await self._list(ctx, "list_disputes", "disputes.list", params, customer_id=params.customer_id.strip())
+
+ # ---- writes ------------------------------------------------------------
+
+ @Operation("create_checkout_session")
+ async def create_checkout_session(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ product_id = self._required(params.product_id, "product_id", "create_checkout_session", "pdt_...")
+ customer: Optional[Dict[str, str]] = None
+ if params.customer_id.strip():
+ customer = {"customer_id": params.customer_id.strip()}
+ elif params.customer_email.strip():
+ customer = {"email": params.customer_email.strip(), **_given({"name": params.customer_name.strip()})}
+ discount_code = params.discount_code.strip()
+ request = {
+ "product_cart": [{"product_id": product_id, "quantity": params.quantity}],
+ **_given({
+ "customer": customer,
+ "return_url": params.return_url.strip(),
+ "discount_codes": [discount_code] if discount_code else None,
+ }),
+ }
+ return await self._one(ctx, "create_checkout_session", "checkout_sessions.create", request, writes=True)
+
+ @Operation("create_customer")
+ async def create_customer(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ email = self._required(params.customer_email, "customer_email", "create_customer", "[email protected]")
+ name = self._required(params.customer_name, "customer_name", "create_customer", "Ada Lovelace")
+ return await self._one(ctx, "create_customer", "customers.create", {"email": email, "name": name}, writes=True)
+
+ @Operation("create_customer_portal_link")
+ async def create_customer_portal_link(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ customer_id = self._required(params.customer_id, "customer_id", "create_customer_portal_link", "cus_...")
+ # send_email off: the link comes back to the caller, and Dodo emails no one.
+ request = {"customer_id": customer_id, "send_email": False, **_given({"return_url": params.return_url.strip()})}
+ return await self._one(
+ ctx, "create_customer_portal_link", "customers.customer_portal.create", request, writes=True
+ )
+
+ @Operation("create_refund")
+ async def create_refund(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ payment_id = self._required(params.payment_id, "payment_id", "create_refund", "pay_...")
+ product_id = params.product_id.strip()
+ if params.amount is not None and not product_id:
+ raise NodeUserError(
+ "A partial refund names the item it refunds: set product_id with amount, "
+ "or leave amount empty to refund the whole payment."
+ )
+ request: Dict[str, Any] = {"payment_id": payment_id, **_given({"reason": params.reason.strip()})}
+ if product_id:
+ request["items"] = [{"item_id": product_id, **_given({"amount": params.amount})}]
+ return await self._one(ctx, "create_refund", "refunds.create", request, writes=True)
+
+ @Operation("cancel_subscription")
+ async def cancel_subscription(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ subscription_id = self._required(params.subscription_id, "subscription_id", "cancel_subscription", "sub_...")
+ change = {"cancel_at_next_billing_date": True} if params.cancel_at_next_billing_date else {"status": "cancelled"}
+ return await self._one(
+ ctx, "cancel_subscription", "subscriptions.update", {"subscription_id": subscription_id, **change}, writes=True
+ )
+
+ @Operation("change_subscription_plan")
+ async def change_subscription_plan(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ subscription_id = self._required(params.subscription_id, "subscription_id", "change_subscription_plan", "sub_...")
+ product_id = self._required(params.product_id, "product_id", "change_subscription_plan", "pdt_...")
+ request = {
+ "subscription_id": subscription_id,
+ "product_id": product_id,
+ "quantity": params.quantity,
+ "proration_billing_mode": params.proration_billing_mode,
+ }
+ return await self._one(ctx, "change_subscription_plan", "subscriptions.change_plan", request, writes=True)
+
+ # ---- any endpoint --------------------------------------------------------
+
+ @Operation("call")
+ async def call(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ # Resolved and checked before any credential or network use.
+ info = await asyncio.to_thread(_sdk.resolve_endpoint, params.endpoint)
+ request = _sdk.check_request(info, params.request)
+ result, mode = await self._run(ctx, info.endpoint, request, writes=not info.reads)
+ return self._shape("call", mode=mode, endpoint=info.endpoint, result=result)
+
+ @Operation("list_operations")
+ async def list_operations(self, ctx: NodeContext, params: DodoPaymentsActionParams) -> Any:
+ # Pure introspection of the installed SDK: no credentials, no network.
+ index = await asyncio.to_thread(_sdk.endpoint_index)
+ needle = params.search.strip().lower()
+ matches = [
+ info.as_dict() for info in index if not needle or needle in info.endpoint.lower() or needle in info.path.lower()
+ ]
+ return self._shape("list_operations", result=matches, count=len(matches))
+
+
+__all__ = ["DodoPaymentsActionNode", "DodoPaymentsActionOutput", "DodoPaymentsActionParams"]
diff --git a/server/nodes/dodo_payments/icon.svg b/server/nodes/dodo_payments/icon.svg
new file mode 100644
index 00000000..46c8f77b
--- /dev/null
+++ b/server/nodes/dodo_payments/icon.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 121 121" fill="none">
+<path d="M60.5 0.5C27.364 0.5 0.5 27.364 0.5 60.5C0.5 93.636 27.364 120.5 60.5 120.5C93.636 120.5 120.5 93.636 120.5 60.5C120.5 27.364 93.636 0.5 60.5 0.5Z" fill="#C6FE1E"/>
+<mask id="dodo-payments-mark" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="18" y="27" width="91" height="76">
+<path d="M108.5 27.5002H18.5V102.5H108.5V27.5002Z" fill="white"/>
+</mask>
+<g mask="url(#dodo-payments-mark)">
+<path d="M53.3412 44.8038H53.3012C50.8212 44.0918 48.1972 45.5158 47.3572 47.8678C46.4292 50.3958 47.9012 53.2918 50.5012 54.0918C56.8692 55.8998 59.6052 46.7718 53.3412 44.8038Z" fill="#0D0D0D"/>
+<path d="M107.614 57.7079C99.4138 39.7479 73.2538 47.1799 70.8378 42.4759C63.7578 31.3639 50.5418 25.1239 36.2538 28.3399C34.0538 27.4599 26.4778 27.2199 21.5818 30.2999L24.5338 31.6039C24.7578 31.6999 24.6938 31.6759 25.0218 31.7959C26.3578 32.2999 26.1258 32.1559 25.1658 32.6839C22.9658 33.9719 20.2218 35.4679 18.5098 37.7159C18.5818 37.8199 22.2778 38.7079 22.2778 38.7079C22.3418 38.7239 23.0298 38.7959 22.8778 39.0999C10.7898 58.1879 31.1738 86.9959 41.0698 102.5H69.7178C65.2938 94.5799 60.2378 83.7719 61.9658 76.4359C62.2778 75.1079 62.6778 73.4199 64.3098 73.1959C68.2538 72.5639 73.5338 72.6199 77.2938 72.1959C77.2938 72.1959 77.3124 72.1959 77.3498 72.1959C78.1498 72.1559 97.7338 69.6679 102.422 81.8759C102.822 82.9959 103.742 82.2679 104.11 81.5319C107.606 74.5799 109.862 63.6359 107.63 57.7159L107.614 57.7079ZM75.9978 51.8119C74.6218 54.2679 73.6858 57.4599 73.4458 60.2439C73.3178 62.0119 73.5018 63.7559 73.6778 65.5239C73.7738 66.4999 73.7818 67.7319 72.9978 68.3719C72.3178 68.9479 71.1898 69.0039 70.0538 69.0839C64.4778 69.0599 50.8778 69.0839 45.6378 65.5159L45.6058 65.4919C37.9818 60.8439 33.9018 50.3479 38.4298 42.1959C39.8938 39.4279 42.5898 37.6279 45.6618 36.9479C49.6138 36.0439 53.9658 36.7159 57.4938 38.5639C58.9338 39.2919 60.6538 40.2519 61.9658 41.3559C64.5658 43.6279 66.7898 45.9879 70.1978 46.7159C71.7658 47.1639 73.3978 47.0999 74.9658 47.4199C77.9018 48.1239 77.1658 49.7959 75.9898 51.7959L75.9978 51.8119Z" fill="#0D0D0D"/>
+</g>
+</svg>
diff --git a/server/nodes/dodo_payments/meta.json b/server/nodes/dodo_payments/meta.json
new file mode 100644
index 00000000..0b60ec6e
--- /dev/null
+++ b/server/nodes/dodo_payments/meta.json
@@ -0,0 +1 @@
+{"color": "#C6FE1E"}
diff --git a/server/tests/fixtures/tool_names_snapshot.json b/server/tests/fixtures/tool_names_snapshot.json
index b7ec1c4d..8bcd547f 100644
--- a/server/tests/fixtures/tool_names_snapshot.json
+++ b/server/tests/fixtures/tool_names_snapshot.json
@@ -68,6 +68,7 @@
"emailSend": "email_send",
"emailRead": "email_read",
"stripeAction": "stripe_action",
+ "dodoPaymentsAction": "dodo_payments_action",
"cloudflareAction": "cloudflare",
"githubAction": "github",
"vercelAction": "vercel",
diff --git a/server/tests/nodes/test_dodo_payments.py b/server/tests/nodes/test_dodo_payments.py
new file mode 100644
index 00000000..2235acaf
--- /dev/null
+++ b/server/tests/nodes/test_dodo_payments.py
@@ -0,0 +1,732 @@
+"""Contract tests for the Dodo Payments action node (``dodoPaymentsAction``).
+
+The node calls Dodo through the official ``dodopayments`` SDK; every SDK touch
+lives in ``nodes/dodo_payments/_sdk.py``. These tests run the real SDK and
+intercept its HTTP traffic with respx, so requests are built exactly as the
+SDK builds them and nothing touches the network. Base URLs come from the
+SDK's own ``ENVIRONMENTS``.
+"""
+
+from __future__ import annotations
+
+import inspect
+import json
+import re
+import subprocess
+import sys
+import typing
+from pathlib import Path
+from typing import get_args
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+import respx
+from dodopayments import ENVIRONMENTS
+
+from tests.nodes._mocks import patched_container
+
+pytestmark = pytest.mark.node_contract
+
+import nodes.dodo_payments as dodo_pkg # noqa: E402
+from nodes.dodo_payments import _sdk, dodo_payments_action # noqa: E402
+from nodes.dodo_payments._credentials import MODE_FIELD, MODES, DodoPaymentsCredential # noqa: E402
+from services.node_registry import get_node_class # noqa: E402
+from services.plugin.credential import CREDENTIAL_REGISTRY # noqa: E402
+from services.ws_handler_registry import get_option_loader # noqa: E402
+
+PLUGIN_DIR = Path(dodo_pkg.__file__).parent
+SERVER_DIR = PLUGIN_DIR.parents[1]
+
+TEST_URL = ENVIRONMENTS["test_mode"]
+LIVE_URL = ENVIRONMENTS["live_mode"]
+KEYS = {"dodo_payments": "dodo_test_key", MODE_FIELD: "test_mode"}
+
+
[email protected](autouse=True)
+def no_read_retries(monkeypatch):
+ """Retries back off for half a second each; tests that need them opt in."""
+ monkeypatch.setattr(_sdk, "READ_RETRIES", 0)
+
+
+async def _execute(harness, params, *, keys=KEYS, **kwargs):
+ with patched_container(auth_api_keys=keys):
+ return await harness.execute("dodoPaymentsAction", params, **kwargs)
+
+
+def _body(request: httpx.Request) -> dict:
+ return json.loads(request.content or b"{}")
+
+
+# ============================================================================
+# Registration
+# ============================================================================
+
+
+class TestRegistration:
+ def test_class_attributes(self):
+ cls = get_node_class("dodoPaymentsAction")
+ assert cls is not None, "dodoPaymentsAction is not registered"
+ assert cls.tool_name == "dodo_payments_action"
+ assert tuple(cls.group) == ("payments", "tool")
+ assert cls.usable_as_tool is True
+ assert DodoPaymentsCredential in tuple(cls.credentials)
+ assert cls.annotations["destructive"] is True
+
+ def test_both_canvas_handles_stay_visible(self):
+ cls = get_node_class("dodoPaymentsAction")
+ assert cls.hide_input_handle is False
+ assert cls.hide_output_handle is False
+ assert {h["name"] for h in cls.handles} == {"input-main", "output-main"}
+
+ def test_option_loader_and_credential_registered(self):
+ assert get_option_loader("dodoPaymentsEndpoints") is not None
+ assert CREDENTIAL_REGISTRY["dodo_payments"] is DodoPaymentsCredential
+
+ def test_tool_schema_is_flat(self):
+ from services.plugin.tool import inline_schema_refs
+
+ cls = get_node_class("dodoPaymentsAction")
+ dumped = json.dumps(inline_schema_refs(cls.Params.model_json_schema()))
+ assert "$defs" not in dumped
+ assert '"$ref"' not in dumped
+
+ def test_operations_match_the_literal_and_default_to_a_read(self):
+ cls = get_node_class("dodoPaymentsAction")
+ declared = set(get_args(cls.Params.model_fields["operation"].annotation))
+ assert declared == set(dodo_payments_action._OPERATIONS)
+ # The approval rule reads the literal operation, so a default that
+ # moved money would slip through when a model omits it.
+ assert cls.Params().operation == "list_payments"
+ assert cls.Params().operation not in dodo_payments_action._HELD_OPERATIONS
+
+ def test_reserved_field_names_absent(self):
+ # ParameterRenderer keys magic on these literal names.
+ cls = get_node_class("dodoPaymentsAction")
+ assert not {"model", "api_key", "parameters", "action", "service_id", "session_id"} & set(cls.Params.model_fields)
+
+ @pytest.mark.parametrize(
+ ("module", "typed_dict", "key", "ours"),
+ [
+ ("payment_list_params", "PaymentListParams", "status", dodo_payments_action.PAYMENT_STATUSES),
+ ("subscription_list_params", "SubscriptionListParams", "status", dodo_payments_action.SUBSCRIPTION_STATUSES),
+ ("refund_list_params", "RefundListParams", "status", dodo_payments_action.REFUND_STATUSES),
+ (
+ "subscription_change_plan_params",
+ "SubscriptionChangePlanParams",
+ "proration_billing_mode",
+ dodo_payments_action.PRORATION_BILLING_MODES,
+ ),
+ ],
+ )
+ def test_dropdown_values_follow_the_sdk(self, module, typed_dict, key, ours):
+ import importlib
+
+ params = getattr(importlib.import_module(f"dodopayments.types.{module}"), typed_dict)
+ assert set(get_args(typing.get_type_hints(params)[key])) == set(ours)
+
+ def test_modes_are_the_sdk_environments(self):
+ assert set(MODES) == set(ENVIRONMENTS)
+ assert MODES[0] == "test_mode", "validation must try the test mode first"
+
+
+# ============================================================================
+# Credential
+# ============================================================================
+
+
+class TestCredentialProbe:
+ @respx.mock
+ async def test_a_test_key_is_found_in_test_mode(self):
+ test = respx.get(f"{TEST_URL}/brands").mock(return_value=httpx.Response(200, json={"items": []}))
+
+ result = await DodoPaymentsCredential._probe("dodo_test_key")
+
+ assert result.valid is True
+ assert result.extra == {"mode": "test_mode"}
+ assert "test mode" in result.message
+ assert test.calls.last.request.headers["Authorization"] == "Bearer dodo_test_key"
+
+ @respx.mock
+ async def test_a_live_key_is_found_in_live_mode(self):
+ respx.get(f"{TEST_URL}/brands").mock(return_value=httpx.Response(401, json={"code": "UNAUTHORIZED"}))
+ respx.get(f"{LIVE_URL}/brands").mock(return_value=httpx.Response(200, json={"items": []}))
+
+ result = await DodoPaymentsCredential._probe("dodo_live_key")
+
+ assert result.valid is True
+ assert result.extra == {"mode": "live_mode"}
+
+ @respx.mock
+ async def test_a_key_both_modes_refuse_is_invalid(self):
+ respx.get(f"{TEST_URL}/brands").mock(return_value=httpx.Response(401))
+ respx.get(f"{LIVE_URL}/brands").mock(return_value=httpx.Response(401))
+
+ result = await DodoPaymentsCredential._probe("wrong")
+
+ assert result.valid is False
+ assert "both test and live mode" in result.message
+
+ @respx.mock
+ async def test_another_refusal_carries_dodos_code(self):
+ respx.get(f"{TEST_URL}/brands").mock(return_value=httpx.Response(401))
+ respx.get(f"{LIVE_URL}/brands").mock(
+ return_value=httpx.Response(403, json={"code": "MERCHANT_NOT_LIVE", "message": "Business is not live"})
+ )
+
+ result = await DodoPaymentsCredential._probe("dodo_live_key")
+
+ assert result.valid is False
+ assert "MERCHANT_NOT_LIVE" in result.message
+
+
+class TestCredentialValidate:
+ def _broadcaster(self):
+ broadcaster = MagicMock(name="StatusBroadcaster")
+ broadcaster.update_api_key_status = AsyncMock()
+ return patch("services.status_broadcaster.get_status_broadcaster", return_value=broadcaster)
+
+ @respx.mock
+ async def test_saves_the_mode_beside_the_key(self):
+ respx.get(f"{TEST_URL}/brands").mock(return_value=httpx.Response(401))
+ respx.get(f"{LIVE_URL}/brands").mock(return_value=httpx.Response(200, json={"items": []}))
+
+ with patched_container() as container, self._broadcaster():
+ response = await DodoPaymentsCredential.validate({"api_key": "dodo_live_key"})
+ stored = container.auth_service().store_api_key.await_args_list
+
+ assert response["valid"] is True
+ assert response["mode"] == "live_mode"
+ assert [call.kwargs.get("provider", call.args[0] if call.args else None) for call in stored] == [
+ "dodo_payments",
+ MODE_FIELD,
+ ]
+ assert stored[1].args[1] == "live_mode"
+
+ @respx.mock
+ async def test_a_rejected_key_saves_nothing(self):
+ respx.get(f"{TEST_URL}/brands").mock(return_value=httpx.Response(401))
+ respx.get(f"{LIVE_URL}/brands").mock(return_value=httpx.Response(401))
+
+ with patched_container() as container, self._broadcaster():
+ response = await DodoPaymentsCredential.validate({"api_key": "wrong"})
+ store = container.auth_service().store_api_key
+
+ assert response["valid"] is False
+ store.assert_not_awaited()
+
+
+# ============================================================================
+# Reads
+# ============================================================================
+
+
+class TestReads:
+ async def test_missing_key_points_at_the_modal(self, harness):
+ result = await _execute(harness, {"operation": "list_payments"}, keys={})
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "PermissionDeniedError"
+ assert result["credential"]["provider"] == "dodo_payments"
+
+ async def test_a_key_without_its_mode_asks_for_validation(self, harness):
+ result = await _execute(harness, {"operation": "list_payments"}, keys={"dodo_payments": "dodo_test_key"})
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "PermissionDeniedError"
+ assert "Validate" in result["error"]
+
+ @respx.mock
+ async def test_list_payments_sends_one_page_with_the_filters(self, harness):
+ route = respx.get(f"{TEST_URL}/payments").mock(
+ return_value=httpx.Response(200, json={"items": [{"payment_id": "pay_1", "status": "failed"}]})
+ )
+
+ result = await _execute(
+ harness,
+ {
+ "operation": "list_payments",
+ "customer_id": "cus_1",
+ "payment_status": "failed",
+ "page": 1,
+ "page_size": 5,
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ request = route.calls.last.request
+ assert dict(request.url.params) == {
+ "page_number": "1",
+ "page_size": "5",
+ "customer_id": "cus_1",
+ "status": "failed",
+ }
+ assert request.headers["Authorization"] == "Bearer dodo_test_key"
+ assert result["result"] == {
+ "operation": "list_payments",
+ "mode": "test_mode",
+ "result": [{"payment_id": "pay_1", "status": "failed"}],
+ "count": 1,
+ "page": 1,
+ "page_size": 5,
+ }
+
+ @respx.mock
+ async def test_a_live_key_calls_the_live_api(self, harness):
+ route = respx.get(f"{LIVE_URL}/payments").mock(return_value=httpx.Response(200, json={"items": []}))
+
+ result = await _execute(harness, {"operation": "list_payments"}, keys={"dodo_payments": "k", MODE_FIELD: "live_mode"})
+
+ harness.assert_envelope(result, success=True)
+ assert route.call_count == 1
+ assert result["result"]["mode"] == "live_mode"
+ assert result["result"]["result"] == []
+
+ @respx.mock
+ async def test_get_product_reads_it_by_id(self, harness):
+ route = respx.get(f"{TEST_URL}/products/pdt_1").mock(
+ return_value=httpx.Response(200, json={"product_id": "pdt_1", "name": "Pro"})
+ )
+
+ result = await _execute(harness, {"operation": "get_product", "product_id": "pdt_1"})
+
+ harness.assert_envelope(result, success=True)
+ assert route.call_count == 1
+ assert result["result"]["result"]["name"] == "Pro"
+
+ @respx.mock
+ async def test_a_missing_id_fails_before_any_request(self, harness):
+ result = await _execute(harness, {"operation": "get_payment"})
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "payment_id is required" in result["error"]
+ assert not respx.calls
+
+ @respx.mock
+ async def test_reads_are_retried(self, harness, monkeypatch):
+ monkeypatch.setattr(_sdk, "READ_RETRIES", 1)
+ route = respx.get(f"{TEST_URL}/payments").mock(
+ side_effect=[httpx.Response(500), httpx.Response(200, json={"items": []})]
+ )
+
+ result = await _execute(harness, {"operation": "list_payments"})
+
+ harness.assert_envelope(result, success=True)
+ assert route.call_count == 2
+
+
+# ============================================================================
+# Writes
+# ============================================================================
+
+
+class TestWrites:
+ @respx.mock
+ async def test_checkout_session_for_a_new_customer(self, harness):
+ route = respx.post(f"{TEST_URL}/checkouts").mock(
+ return_value=httpx.Response(200, json={"session_id": "cks_1", "checkout_url": "https://checkout.example/1"})
+ )
+
+ result = await _execute(
+ harness,
+ {
+ "operation": "create_checkout_session",
+ "product_id": "pdt_1",
+ "quantity": 2,
+ "customer_email": "[email protected]",
+ "customer_name": "Ada",
+ "return_url": "https://example.com/thanks",
+ "discount_code": "LAUNCH",
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert _body(route.calls.last.request) == {
+ "product_cart": [{"product_id": "pdt_1", "quantity": 2}],
+ "customer": {"email": "[email protected]", "name": "Ada"},
+ "return_url": "https://example.com/thanks",
+ "discount_codes": ["LAUNCH"],
+ }
+ assert result["result"]["result"]["checkout_url"] == "https://checkout.example/1"
+
+ @respx.mock
+ async def test_checkout_session_for_an_existing_customer(self, harness):
+ route = respx.post(f"{TEST_URL}/checkouts").mock(return_value=httpx.Response(200, json={"session_id": "cks_1"}))
+
+ await _execute(
+ harness,
+ {"operation": "create_checkout_session", "product_id": "pdt_1", "customer_id": "cus_1", "customer_email": "[email protected]"},
+ )
+
+ assert _body(route.calls.last.request) == {
+ "product_cart": [{"product_id": "pdt_1", "quantity": 1}],
+ "customer": {"customer_id": "cus_1"},
+ }
+
+ @respx.mock
+ async def test_create_customer_needs_email_and_name(self, harness):
+ result = await _execute(harness, {"operation": "create_customer", "customer_email": "[email protected]"})
+
+ harness.assert_envelope(result, success=False)
+ assert "customer_name is required" in result["error"]
+ assert not respx.calls
+
+ @respx.mock
+ async def test_portal_link_never_emails_the_customer(self, harness):
+ route = respx.post(f"{TEST_URL}/customers/cus_1/customer-portal/session").mock(
+ return_value=httpx.Response(200, json={"link": "https://portal.example/1"})
+ )
+
+ result = await _execute(harness, {"operation": "create_customer_portal_link", "customer_id": "cus_1"})
+
+ harness.assert_envelope(result, success=True)
+ assert route.calls.last.request.url.params["send_email"] == "false"
+ assert result["result"]["result"] == {"link": "https://portal.example/1"}
+
+ @respx.mock
+ async def test_refund_of_the_whole_payment(self, harness):
+ route = respx.post(f"{TEST_URL}/refunds").mock(
+ return_value=httpx.Response(200, json={"refund_id": "ref_1", "status": "pending"})
+ )
+
+ result = await _execute(harness, {"operation": "create_refund", "payment_id": "pay_1", "reason": "Duplicate"})
+
+ harness.assert_envelope(result, success=True)
+ assert _body(route.calls.last.request) == {"payment_id": "pay_1", "reason": "Duplicate"}
+
+ @respx.mock
+ async def test_refund_of_part_of_an_item(self, harness):
+ route = respx.post(f"{TEST_URL}/refunds").mock(return_value=httpx.Response(200, json={"refund_id": "ref_1"}))
+
+ await _execute(harness, {"operation": "create_refund", "payment_id": "pay_1", "product_id": "pdt_1", "amount": 500})
+
+ assert _body(route.calls.last.request) == {
+ "payment_id": "pay_1",
+ "items": [{"item_id": "pdt_1", "amount": 500}],
+ }
+
+ @respx.mock
+ async def test_a_partial_refund_without_its_item_is_refused(self, harness):
+ result = await _execute(harness, {"operation": "create_refund", "payment_id": "pay_1", "amount": 500})
+
+ harness.assert_envelope(result, success=False)
+ assert "product_id" in result["error"]
+ assert not respx.calls
+
+ @pytest.mark.parametrize(
+ ("at_period_end", "body"),
+ [(False, {"status": "cancelled"}), (True, {"cancel_at_next_billing_date": True})],
+ )
+ @respx.mock
+ async def test_cancel_subscription(self, harness, at_period_end, body):
+ route = respx.patch(f"{TEST_URL}/subscriptions/sub_1").mock(
+ return_value=httpx.Response(200, json={"subscription_id": "sub_1"})
+ )
+
+ await _execute(
+ harness,
+ {"operation": "cancel_subscription", "subscription_id": "sub_1", "cancel_at_next_billing_date": at_period_end},
+ )
+
+ assert _body(route.calls.last.request) == body
+
+ @respx.mock
+ async def test_change_subscription_plan(self, harness):
+ route = respx.post(f"{TEST_URL}/subscriptions/sub_1/change-plan").mock(return_value=httpx.Response(200, json={}))
+
+ await _execute(
+ harness,
+ {
+ "operation": "change_subscription_plan",
+ "subscription_id": "sub_1",
+ "product_id": "pdt_2",
+ "quantity": 3,
+ "proration_billing_mode": "do_not_bill",
+ },
+ )
+
+ assert _body(route.calls.last.request) == {
+ "product_id": "pdt_2",
+ "quantity": 3,
+ "proration_billing_mode": "do_not_bill",
+ }
+
+ @respx.mock
+ async def test_writes_are_never_retried(self, harness, monkeypatch):
+ """The SDK retries POSTs too and Dodo takes no idempotency key: a
+ retried refund could be refunded twice."""
+ monkeypatch.setattr(_sdk, "READ_RETRIES", 2)
+ route = respx.post(f"{TEST_URL}/refunds").mock(return_value=httpx.Response(500, json={"code": "INTERNAL"}))
+
+ result = await _execute(harness, {"operation": "create_refund", "payment_id": "pay_1"})
+
+ harness.assert_envelope(result, success=False)
+ assert route.call_count == 1
+ assert "may or may not have been made" in result["error"]
+
+
+# ============================================================================
+# Errors
+# ============================================================================
+
+
+class TestErrors:
+ @respx.mock
+ async def test_a_rejected_key_points_at_the_modal(self, harness):
+ respx.get(f"{TEST_URL}/payments").mock(return_value=httpx.Response(401, json={"code": "UNAUTHORIZED"}))
+
+ result = await _execute(harness, {"operation": "list_payments"})
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "Credentials -> Dodo Payments" in result["error"]
+
+ @respx.mock
+ async def test_dodos_code_and_message_come_through(self, harness):
+ respx.get(f"{TEST_URL}/payments/pay_x").mock(
+ return_value=httpx.Response(404, json={"code": "NOT_FOUND", "message": "Payment not found"})
+ )
+
+ result = await _execute(harness, {"operation": "get_payment", "payment_id": "pay_x"})
+
+ harness.assert_envelope(result, success=False)
+ assert "payments.retrieve failed (404 NOT_FOUND): Payment not found" in result["error"]
+
+ @respx.mock
+ async def test_a_read_only_key_on_a_write(self, harness):
+ respx.post(f"{TEST_URL}/refunds").mock(
+ return_value=httpx.Response(403, json={"code": "UNAUTHORIZED", "message": "Write access disabled"})
+ )
+
+ result = await _execute(harness, {"operation": "create_refund", "payment_id": "pay_1"})
+
+ harness.assert_envelope(result, success=False)
+ assert "read-only key" in result["error"]
+
+
+# ============================================================================
+# call + list_operations
+# ============================================================================
+
+
+class TestCall:
+ async def test_an_unknown_endpoint_suggests_close_names_before_credentials(self, harness):
+ result = await _execute(harness, {"operation": "call", "endpoint": "payout.list"}, keys={})
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "payouts.list" in result["error"]
+
+ @pytest.mark.parametrize(
+ ("endpoint", "request_args", "expected"),
+ [
+ ("payouts.list", {"bogus": 1}, "unknown: bogus"),
+ ("refunds.retrieve", {}, "missing: refund_id"),
+ ("payouts.list", {"extra_headers": {"Authorization": "Bearer other"}}, "unknown: extra_headers"),
+ ],
+ )
+ @respx.mock
+ async def test_the_request_is_checked_before_any_network_use(self, harness, endpoint, request_args, expected):
+ result = await _execute(harness, {"operation": "call", "endpoint": endpoint, "request": request_args})
+
+ harness.assert_envelope(result, success=False)
+ assert expected in result["error"]
+ assert not respx.calls
+
+ @respx.mock
+ async def test_a_get_endpoint_answers_with_the_api_json(self, harness):
+ route = respx.get(f"{TEST_URL}/payouts").mock(return_value=httpx.Response(200, json={"items": [{"payout_id": "po_1"}]}))
+
+ result = await _execute(
+ harness, {"operation": "call", "endpoint": "payouts.list", "request": json.dumps({"page_size": 1})}
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert route.calls.last.request.url.params["page_size"] == "1"
+ assert result["result"] == {
+ "operation": "call",
+ "mode": "test_mode",
+ "endpoint": "payouts.list",
+ "result": {"items": [{"payout_id": "po_1"}]},
+ }
+
+ @respx.mock
+ async def test_a_writing_endpoint_runs_without_retries(self, harness, monkeypatch):
+ monkeypatch.setattr(_sdk, "READ_RETRIES", 2)
+ route = respx.post(f"{TEST_URL}/subscriptions/sub_1/charge").mock(return_value=httpx.Response(502))
+
+ result = await _execute(
+ harness,
+ {"operation": "call", "endpoint": "subscriptions.charge", "request": {"subscription_id": "sub_1", "product_price": 900}},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert route.call_count == 1
+
+ async def test_webhook_endpoints_are_not_reachable(self, harness):
+ result = await _execute(harness, {"operation": "call", "endpoint": "webhooks.retrieve_secret"})
+
+ harness.assert_envelope(result, success=False)
+ assert "Unknown Dodo Payments endpoint" in result["error"]
+
+ @respx.mock
+ async def test_a_file_answer_is_refused(self, harness):
+ respx.get(f"{TEST_URL}/invoices/payments/pay_1").mock(
+ return_value=httpx.Response(200, content=b"%PDF-1.7", headers={"content-type": "application/pdf"})
+ )
+
+ result = await _execute(
+ harness, {"operation": "call", "endpoint": "invoices.payments.retrieve", "request": {"payment_id": "pay_1"}}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "invoice PDF" in result["error"]
+
+
+class TestListOperations:
+ async def test_needs_no_credentials(self, harness):
+ result = await _execute(harness, {"operation": "list_operations", "search": "refund"}, keys={})
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ endpoints = {entry["endpoint"]: entry for entry in payload["result"]}
+ assert payload["count"] == len(endpoints)
+ assert endpoints["refunds.create"]["http_method"] == "POST"
+ assert endpoints["refunds.create"]["reads"] is False
+ assert {"name": "payment_id", "type": "str", "required": True} in endpoints["refunds.create"]["params"]
+ assert endpoints["refunds.list"]["reads"] is True
+
+ def test_every_sdk_method_has_a_route(self):
+ """A method the route pattern misses would silently vanish from the
+ index, and so from `call` and the approval rule."""
+ from dodopayments import DodoPayments
+ from dodopayments._resource import SyncAPIResource
+
+ missed = []
+
+ def walk(path, resource):
+ for name, fn in inspect.getmembers(type(resource), inspect.isfunction):
+ if not name.startswith("_") and _sdk._describe(f"{path}.{name}", fn) is None:
+ missed.append(f"{path}.{name}")
+ for name, child in _sdk._resources(resource, SyncAPIResource):
+ walk(f"{path}.{name}", child)
+
+ with DodoPayments(bearer_token="x", base_url="http://introspection.invalid") as client:
+ for name, resource in _sdk._resources(client, SyncAPIResource):
+ if name not in _sdk._EXCLUDED_RESOURCES:
+ walk(name, resource)
+ assert missed == []
+
+ def test_the_index_matches_the_typed_operations(self):
+ index = {entry.endpoint: entry for entry in _sdk.endpoint_index()}
+ assert not [name for name in index if name.startswith("webhooks.")]
+ for endpoint, method in {
+ "payments.list": "GET",
+ "payments.retrieve": "GET",
+ "products.retrieve": "GET",
+ "checkout_sessions.create": "POST",
+ "customers.customer_portal.create": "POST",
+ "refunds.create": "POST",
+ "subscriptions.update": "PATCH",
+ "subscriptions.change_plan": "POST",
+ }.items():
+ assert index[endpoint].http_method == method, endpoint
+
+ async def test_the_dropdown_lists_every_endpoint(self):
+ options = await get_option_loader("dodoPaymentsEndpoints")({})
+ assert len(options) == len(_sdk.endpoint_index())
+ assert {"value": "payouts.list", "label": "payouts.list", "description": "GET /payouts"} in options
+
+
+# ============================================================================
+# Approval rule
+# ============================================================================
+
+
+class TestApproval:
+ @pytest.fixture
+ def spec(self):
+ return get_node_class("dodoPaymentsAction").approval
+
+ @pytest.mark.parametrize(
+ "operation",
+ ["list_payments", "get_payment", "create_checkout_session", "create_customer", "create_customer_portal_link", "list_operations"],
+ )
+ def test_reads_and_harmless_writes_run(self, spec, operation):
+ assert spec.sends({"operation": operation}) is False
+
+ @pytest.mark.parametrize("operation", ["create_refund", "cancel_subscription", "change_subscription_plan"])
+ def test_money_moves_wait_for_the_owner(self, spec, operation):
+ assert spec.sends({"operation": operation}) is True
+
+ @pytest.mark.parametrize(
+ ("endpoint", "held"),
+ [("payouts.list", False), ("subscriptions.charge", True), ("discounts.delete", True), ("no.such", True)],
+ )
+ def test_call_waits_only_when_its_endpoint_writes(self, spec, endpoint, held):
+ assert spec.sends({"operation": "call", "endpoint": endpoint}) is held
+
+ def test_the_card_shows_flat_details(self, spec):
+ preview = spec.preview({"operation": "create_refund", "payment_id": "pay_1", "amount": 500, "reason": "Duplicate"})
+ assert preview["channel"] == "Dodo Payments"
+ assert preview["recipient_label"] == "the customer"
+ assert {"label": "Payment", "value": "pay_1"} in preview["details"]
+ assert {"label": "Amount", "value": "500"} in preview["details"]
+
+
+# ============================================================================
+# Import laziness
+# ============================================================================
+
+
+class TestNoEagerSdkImport:
+ """Importing the plugin must never import the SDK (clean interpreter: the
+ pytest process already loaded it above)."""
+
+ def _probe(self, code: str) -> str:
+ result = subprocess.run([sys.executable, "-c", code], cwd=SERVER_DIR, capture_output=True, text=True, timeout=180)
+ assert result.returncode == 0, f"probe subprocess failed (rc={result.returncode}):\n{result.stderr}"
+ return result.stdout
+
+ def test_plugin_registers_without_the_sdk(self):
+ out = self._probe(
+ "import sys\n"
+ "sys.modules['dodopayments'] = None\n"
+ "import nodes.dodo_payments\n"
+ "from services.node_registry import get_node_class\n"
+ "print('REGISTERED=' + str(get_node_class('dodoPaymentsAction') is not None))\n"
+ )
+ assert "REGISTERED=True" in out
+
+ def test_plugin_import_does_not_load_the_sdk(self):
+ out = self._probe("import sys\nimport nodes.dodo_payments\nprint('LEAKED=' + str('dodopayments' in sys.modules))\n")
+ assert "LEAKED=False" in out
+
+
+# ============================================================================
+# Catalogue + assets
+# ============================================================================
+
+
+class TestCatalogueAndAssets:
+ def test_credential_providers_entry(self):
+ config = json.loads((SERVER_DIR / "config" / "credential_providers.json").read_text(encoding="utf-8"))
+ entry = config["providers"]["dodo_payments"]
+ assert entry["kind"] == "apiKey"
+ assert entry["category"] == "payments"
+ assert entry["icon_ref"] == "/api/schemas/credentials/dodo_payments/icon"
+ assert [f["key"] for f in entry["fields"]] == ["apiKey", "dodo_payments_webhook_key"]
+ assert all(f["secret"] is True for f in entry["fields"])
+ # The mode is written by validation, never shown as a field.
+ assert tuple(DodoPaymentsCredential.extra_fields) == (MODE_FIELD, "dodo_payments_webhook_key")
+
+ def test_tool_name_snapshot(self):
+ snapshot = json.loads((SERVER_DIR / "tests" / "fixtures" / "tool_names_snapshot.json").read_text(encoding="utf-8"))
+ assert snapshot["dodoPaymentsAction"] == "dodo_payments_action"
+
+ def test_plugin_folder_assets(self):
+ meta = json.loads((PLUGIN_DIR / "meta.json").read_text(encoding="utf-8"))
+ assert re.fullmatch(r"#[0-9a-fA-F]{6}", meta["color"])
+ assert "<svg" in (PLUGIN_DIR / "icon.svg").read_text(encoding="utf-8")
+ assert DodoPaymentsCredential.get_icon_path() == PLUGIN_DIR / "dodo_payments.svg"
diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.py
index c06e218f..62038af1 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -63,6 +63,7 @@ _MIGRATED_PLUGINS = (
"cloudflare",
"code",
"discord",
+ "dodo_payments",
"email",
"gcloud",
"github",