AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(stripe): Stripe subscription webhook trigger blocks (#13435)
Toran Bruce Richardsa0166aca0c21
diff --git a/.secrets.baseline b/.secrets.baselineindex 1ae8d5ecf1..4f75d0f2e1 100644--- a/.secrets.baseline+++ b/.secrets.baseline@@ -279,6 +279,117 @@"line_number": 100}],+ "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json": [+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json",+ "hashed_secret": "cde3500f5313fd772a2dc099c1358027257a335c",+ "is_verified": false,+ "line_number": 2+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json",+ "hashed_secret": "68307e34b3f588c11555e13cb00ef4d1ceb55346",+ "is_verified": false,+ "line_number": 10+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json",+ "hashed_secret": "f1e99855c875358b8cedde339e7d24642fbcb992",+ "is_verified": false,+ "line_number": 28+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json",+ "hashed_secret": "4a4c0c32e090c4eba2b374146d8587f2aaafc80b",+ "is_verified": false,+ "line_number": 32+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json",+ "hashed_secret": "5bbe1aee88016a4e6cd7d168e723e1895f6d765b",+ "is_verified": false,+ "line_number": 50+ }+ ],+ "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json": [+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json",+ "hashed_secret": "099f7afd1c406967f2da6a6659bd5f2ee8ace940",+ "is_verified": false,+ "line_number": 2+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json",+ "hashed_secret": "68307e34b3f588c11555e13cb00ef4d1ceb55346",+ "is_verified": false,+ "line_number": 10+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json",+ "hashed_secret": "f1e99855c875358b8cedde339e7d24642fbcb992",+ "is_verified": false,+ "line_number": 29+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json",+ "hashed_secret": "4a4c0c32e090c4eba2b374146d8587f2aaafc80b",+ "is_verified": false,+ "line_number": 33+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json",+ "hashed_secret": "5bbe1aee88016a4e6cd7d168e723e1895f6d765b",+ "is_verified": false,+ "line_number": 51+ }+ ],+ "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json": [+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json",+ "hashed_secret": "cf8e6e6e14ebf1d4f06e1dc065683b15e27f0cda",+ "is_verified": false,+ "line_number": 2+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json",+ "hashed_secret": "68307e34b3f588c11555e13cb00ef4d1ceb55346",+ "is_verified": false,+ "line_number": 10+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json",+ "hashed_secret": "f1e99855c875358b8cedde339e7d24642fbcb992",+ "is_verified": false,+ "line_number": 26+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json",+ "hashed_secret": "a676dac957788e2d791f8674762acb4e71ce4e14",+ "is_verified": false,+ "line_number": 30+ },+ {+ "type": "Base64 High Entropy String",+ "filename": "autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json",+ "hashed_secret": "4a4c0c32e090c4eba2b374146d8587f2aaafc80b",+ "is_verified": false,+ "line_number": 73+ }+ ],"autogpt_platform/backend/backend/blocks/talking_head.py": [{"type": "Base64 High Entropy String",diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex a86d56364b..df7d4ff77b 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -708,7 +708,13 @@ async def webhook_ingress_generic(except NotFoundError as e:logger.warning(f"Webhook payload received for unknown webhook #{webhook_id}")raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))- logger.debug(f"Webhook #{webhook_id}: {webhook}")+ # `secret` and `config` are excluded: both can hold platform- or+ # provider-issued signing secrets, which must not reach the logs.+ # Guarded so the dump doesn't run on every delivery when DEBUG is off.+ if logger.isEnabledFor(logging.DEBUG):+ logger.debug(+ f"Webhook #{webhook_id}: {webhook.model_dump(exclude={'secret', 'config'})}"+ )user_id = webhook.user_idtry:diff --git a/autogpt_platform/backend/backend/blocks/stripe/__init__.py b/autogpt_platform/backend/backend/blocks/stripe/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/blocks/stripe/_auth.py b/autogpt_platform/backend/backend/blocks/stripe/_auth.pynew file mode 100644index 0000000000..a60235a0e1--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe/_auth.py@@ -0,0 +1,34 @@+from typing import Literal++from pydantic import SecretStr++from backend.data.model import APIKeyCredentials, CredentialsField, CredentialsMetaInput+from backend.integrations.providers import ProviderName++StripeCredentials = APIKeyCredentials+StripeCredentialsInput = CredentialsMetaInput[+ Literal[ProviderName.STRIPE],+ Literal["api_key"],+]+++def StripeCredentialsField() -> StripeCredentialsInput:+ return CredentialsField(+ description="Stripe API secret key (sk_live_... or sk_test_...). "+ "Requires permission to create and delete webhook endpoints.",+ )+++TEST_CREDENTIALS = APIKeyCredentials(+ id="01234567-89ab-cdef-0123-456789abcdef",+ provider="stripe",+ api_key=SecretStr("mock-stripe-api-key"),+ title="Mock Stripe API key",+ expires_at=None,+)+TEST_CREDENTIALS_INPUT = {+ "provider": TEST_CREDENTIALS.provider,+ "id": TEST_CREDENTIALS.id,+ "type": TEST_CREDENTIALS.type,+ "title": TEST_CREDENTIALS.title,+}diff --git a/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json b/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.jsonnew file mode 100644index 0000000000..3cec90dda2--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json@@ -0,0 +1,71 @@+{+ "id": "evt_1OxK2fLkdIwHu7ixSubscriptionCreated",+ "object": "event",+ "api_version": "2023-10-16",+ "created": 1712000000,+ "type": "customer.subscription.created",+ "livemode": false,+ "data": {+ "object": {+ "id": "sub_1OxK2fLkdIwHu7ixABCDEFGH",+ "object": "subscription",+ "application": null,+ "billing_cycle_anchor": 1712000000,+ "cancel_at": null,+ "cancel_at_period_end": false,+ "canceled_at": null,+ "collection_method": "charge_automatically",+ "created": 1712000000,+ "currency": "usd",+ "current_period_end": 1714678400,+ "current_period_start": 1712000000,+ "customer": "cus_Pq1234ABCDEF",+ "description": null,+ "items": {+ "object": "list",+ "data": [+ {+ "id": "si_1OxK2fLkdIwHu7ixABCDEFGH",+ "object": "subscription_item",+ "created": 1712000000,+ "price": {+ "id": "price_1OxABCLkdIwHu7ixMonthlyPro",+ "object": "price",+ "active": true,+ "billing_scheme": "per_unit",+ "currency": "usd",+ "nickname": "Pro Monthly",+ "product": "prod_Pq1234ProPlan",+ "recurring": {+ "interval": "month",+ "interval_count": 1+ },+ "type": "recurring",+ "unit_amount": 2000+ },+ "quantity": 1+ }+ ]+ },+ "latest_invoice": "in_1OxK2fLkdIwHu7ixABCDEFGH",+ "livemode": false,+ "metadata": {},+ "plan": {+ "id": "price_1OxABCLkdIwHu7ixMonthlyPro",+ "object": "plan",+ "active": true,+ "amount": 2000,+ "currency": "usd",+ "interval": "month",+ "interval_count": 1,+ "nickname": "Pro Monthly",+ "product": "prod_Pq1234ProPlan"+ },+ "quantity": 1,+ "start_date": 1712000000,+ "status": "active",+ "trial_end": null,+ "trial_start": null+ }+ }+}diff --git a/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json b/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.jsonnew file mode 100644index 0000000000..f43188f652--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.deleted.json@@ -0,0 +1,72 @@+{+ "id": "evt_1OxK2fLkdIwHu7ixSubscriptionDeleted",+ "object": "event",+ "api_version": "2023-10-16",+ "created": 1714678400,+ "type": "customer.subscription.deleted",+ "livemode": false,+ "data": {+ "object": {+ "id": "sub_1OxK2fLkdIwHu7ixABCDEFGH",+ "object": "subscription",+ "application": null,+ "billing_cycle_anchor": 1712000000,+ "cancel_at": null,+ "cancel_at_period_end": false,+ "canceled_at": 1714678400,+ "collection_method": "charge_automatically",+ "created": 1712000000,+ "currency": "usd",+ "current_period_end": 1714678400,+ "current_period_start": 1712000000,+ "customer": "cus_Pq1234ABCDEF",+ "description": null,+ "ended_at": 1714678400,+ "items": {+ "object": "list",+ "data": [+ {+ "id": "si_1OxK2fLkdIwHu7ixABCDEFGH",+ "object": "subscription_item",+ "created": 1712000000,+ "price": {+ "id": "price_1OxABCLkdIwHu7ixMonthlyPro",+ "object": "price",+ "active": true,+ "billing_scheme": "per_unit",+ "currency": "usd",+ "nickname": "Pro Monthly",+ "product": "prod_Pq1234ProPlan",+ "recurring": {+ "interval": "month",+ "interval_count": 1+ },+ "type": "recurring",+ "unit_amount": 2000+ },+ "quantity": 1+ }+ ]+ },+ "latest_invoice": "in_1OxK2fLkdIwHu7ixABCDEFGH",+ "livemode": false,+ "metadata": {},+ "plan": {+ "id": "price_1OxABCLkdIwHu7ixMonthlyPro",+ "object": "plan",+ "active": true,+ "amount": 2000,+ "currency": "usd",+ "interval": "month",+ "interval_count": 1,+ "nickname": "Pro Monthly",+ "product": "prod_Pq1234ProPlan"+ },+ "quantity": 1,+ "start_date": 1712000000,+ "status": "canceled",+ "trial_end": null,+ "trial_start": null+ }+ }+}diff --git a/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json b/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.jsonnew file mode 100644index 0000000000..9f4e293c58--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.updated.json@@ -0,0 +1,88 @@+{+ "id": "evt_1OxK2fLkdIwHu7ixSubscriptionUpdated",+ "object": "event",+ "api_version": "2023-10-16",+ "created": 1712086400,+ "type": "customer.subscription.updated",+ "livemode": false,+ "data": {+ "object": {+ "id": "sub_1OxK2fLkdIwHu7ixABCDEFGH",+ "object": "subscription",+ "billing_cycle_anchor": 1712000000,+ "cancel_at": null,+ "cancel_at_period_end": false,+ "canceled_at": null,+ "collection_method": "charge_automatically",+ "created": 1712000000,+ "currency": "usd",+ "current_period_end": 1717948800,+ "current_period_start": 1715356800,+ "customer": "cus_Pq1234ABCDEF",+ "items": {+ "object": "list",+ "data": [+ {+ "id": "si_1OxK2fLkdIwHu7ixABCDEFGH",+ "object": "subscription_item",+ "created": 1712000000,+ "price": {+ "id": "price_1OxABCLkdIwHu7ixYearlyPro",+ "object": "price",+ "active": true,+ "billing_scheme": "per_unit",+ "currency": "usd",+ "nickname": "Pro Yearly",+ "product": "prod_Pq1234ProPlan",+ "recurring": {+ "interval": "year",+ "interval_count": 1+ },+ "type": "recurring",+ "unit_amount": 19200+ },+ "quantity": 1+ }+ ]+ },+ "latest_invoice": "in_1OxK2fLkdIwHu7ixUPDATED",+ "livemode": false,+ "metadata": {},+ "plan": {+ "id": "price_1OxABCLkdIwHu7ixYearlyPro",+ "object": "plan",+ "active": true,+ "amount": 19200,+ "currency": "usd",+ "interval": "year",+ "interval_count": 1,+ "nickname": "Pro Yearly",+ "product": "prod_Pq1234ProPlan"+ },+ "quantity": 1,+ "start_date": 1712000000,+ "status": "active",+ "trial_end": null,+ "trial_start": null+ },+ "previous_attributes": {+ "items": {+ "data": [+ {+ "price": {+ "id": "price_1OxABCLkdIwHu7ixMonthlyPro",+ "nickname": "Pro Monthly",+ "unit_amount": 2000+ }+ }+ ]+ },+ "plan": {+ "id": "price_1OxABCLkdIwHu7ixMonthlyPro",+ "amount": 2000,+ "interval": "month",+ "nickname": "Pro Monthly"+ }+ }+ }+}diff --git a/autogpt_platform/backend/backend/blocks/stripe/triggers.py b/autogpt_platform/backend/backend/blocks/stripe/triggers.pynew file mode 100644index 0000000000..876c87c584--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe/triggers.py@@ -0,0 +1,207 @@+import json+from pathlib import Path+from typing import Any++from pydantic import BaseModel++from backend.blocks._base import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ BlockWebhookConfig,+)+from backend.data.model import SchemaField+from backend.integrations.providers import ProviderName++from ._auth import (+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ StripeCredentialsField,+ StripeCredentialsInput,+)++_PAYLOAD_DIR = Path(__file__).parent / "example_payloads"+++def load_example_payload(event_type: str) -> dict[str, Any]:+ """Load a bundled example event payload, e.g. `customer.subscription.created`."""+ return json.loads((_PAYLOAD_DIR / f"{event_type}.json").read_text(encoding="utf-8"))+++# Read once at import; `Block.__init__` runs on every block-registry cache miss.+EXAMPLE_SUBSCRIPTION_CREATED = load_example_payload("customer.subscription.created")+++class StripeSubscriptionTriggerBlock(Block):+ """+ Triggers whenever a Stripe subscription is created, upgraded, or cancelled.+ Connects directly to Stripe — no internal DB polling, so internal/demo+ accounts are naturally excluded.+ """++ class Input(BlockSchemaInput):+ credentials: StripeCredentialsInput = StripeCredentialsField()+ payload: dict = SchemaField(hidden=True, default_factory=dict)++ class EventsFilter(BaseModel):+ """+ The `customer.subscription.*` lifecycle events:+ https://docs.stripe.com/api/events/types#event_types-customer.subscription.created+ """++ created: bool = True+ updated: bool = True+ deleted: bool = False++ events: EventsFilter = SchemaField(+ title="Events",+ description="Subscription lifecycle events to subscribe to. "+ "Cancellation and churn workflows need `deleted`, which is off by "+ "default. Note that `updated` is high-volume — Stripe sends it for "+ "any change to the subscription, including renewals, payment-method "+ "changes and metadata edits, not just upgrades. Use "+ "`previous_attributes` to tell an upgrade from routine churn.",+ default_factory=EventsFilter,+ advanced=False,+ )++ class Output(BlockSchemaOutput):+ payload: dict = SchemaField(+ description="Full Stripe event object as received from the webhook"+ )+ event_type: str = SchemaField(+ description="Stripe event type, e.g. customer.subscription.created"+ )+ subscription_id: str = SchemaField(+ description="Stripe subscription ID (sub_...)"+ )+ customer_id: str = SchemaField(description="Stripe customer ID (cus_...)")+ status: str = SchemaField(+ description="Subscription status: active, trialing, past_due, canceled, etc."+ )+ cancel_at_period_end: bool = SchemaField(+ description="True if the subscription is scheduled to end when the "+ "current billing period does, rather than having ended already"+ )+ canceled_at: int = SchemaField(+ description="Unix timestamp of when the subscription was canceled, "+ "or 0 if it has not been canceled"+ )+ previous_attributes: dict = SchemaField(+ description="On `updated` events, the changed fields' prior values, as "+ "sent by Stripe. Empty for other events. Compare against the "+ "subscription in `payload` to tell an upgrade from a renewal — e.g. a "+ "key of `items` or `plan` means the plan itself changed."+ )+ plan_name: str = SchemaField(+ description=(+ "Nickname of the subscription's first item price. Prices without "+ "a nickname fall back to the raw price ID (price_...). Only the "+ "first item is read; see `payload` for multi-item subscriptions."+ )+ )+ plan_interval: str = SchemaField(+ description="Billing interval of the first subscription item: "+ "day, week, month or year"+ )+ amount_cents: int = SchemaField(+ description="Unit amount of the first subscription item, in the smallest "+ "currency unit — cents for USD, but whole units for zero-decimal "+ "currencies like JPY and KRW. This is not the subscription total when "+ "there is more than one item."+ )+ currency: str = SchemaField(description="Three-letter ISO currency code")+ livemode: bool = SchemaField(+ description="True for live Stripe data, False for test mode"+ )+ error: str = SchemaField(+ description="Error message if the payload could not be parsed"+ )++ def __init__(self):+ # Imported here (as in the other trigger blocks) to avoid the import+ # cycle between the block package and the webhook managers.+ from backend.integrations.webhooks.stripe import StripeWebhookType++ super().__init__(+ id="bc05f7ef-ba6f-4cb7-a899-3913b745ed11",+ description=(+ "Triggers on Stripe subscription events (new, upgrade, cancel). "+ "Uses Stripe webhooks directly — real external customers only, "+ "no internal or demo account noise."+ ),+ categories={BlockCategory.INPUT, BlockCategory.DATA},+ input_schema=StripeSubscriptionTriggerBlock.Input,+ output_schema=StripeSubscriptionTriggerBlock.Output,+ webhook_config=BlockWebhookConfig(+ provider=ProviderName.STRIPE,+ webhook_type=StripeWebhookType.ACCOUNT,+ resource_format="",+ event_filter_input="events",+ event_format="customer.subscription.{event}",+ ),+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "events": {"created": True, "updated": True, "deleted": False},+ "payload": EXAMPLE_SUBSCRIPTION_CREATED,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("payload", EXAMPLE_SUBSCRIPTION_CREATED),+ ("event_type", "customer.subscription.created"),+ ("subscription_id", "sub_1OxK2fLkdIwHu7ixABCDEFGH"),+ ("customer_id", "cus_Pq1234ABCDEF"),+ ("status", "active"),+ ("cancel_at_period_end", False),+ ("canceled_at", 0),+ ("previous_attributes", {}),+ ("plan_name", "Pro Monthly"),+ ("plan_interval", "month"),+ ("amount_cents", 2000),+ ("currency", "usd"),+ ("livemode", False),+ ],+ )++ async def run(self, input_data: Input, **kwargs) -> BlockOutput:+ payload = input_data.payload++ # Parse before yielding anything: a yield on "error" aborts the block+ # with a BlockExecutionError, so emitting outputs first would leave the+ # node both partially succeeded and failed.+ try:+ subscription = payload["data"]["object"]++ # Plan info lives on the first subscription item; older Stripe API+ # versions only expose it as a top-level `plan`. The two shapes+ # differ only in where the interval and amount live.+ if items := subscription.get("items", {}).get("data", []):+ price_source = items[0].get("price", {})+ plan_interval = price_source.get("recurring", {}).get("interval", "")+ amount_cents = price_source.get("unit_amount") or 0+ else:+ price_source = subscription.get("plan", {})+ plan_interval = price_source.get("interval", "")+ amount_cents = price_source.get("amount") or 0+ plan_name = price_source.get("nickname") or price_source.get("id", "")+ except (KeyError, TypeError) as e:+ yield "error", f"Failed to parse Stripe subscription payload: {e}"+ return++ yield "payload", payload+ yield "event_type", payload.get("type", "")+ yield "subscription_id", subscription.get("id", "")+ yield "customer_id", subscription.get("customer", "")+ yield "status", subscription.get("status", "")+ yield "cancel_at_period_end", bool(subscription.get("cancel_at_period_end"))+ yield "canceled_at", subscription.get("canceled_at") or 0+ yield "previous_attributes", payload.get("data", {}).get(+ "previous_attributes"+ ) or {}+ yield "plan_name", plan_name+ yield "plan_interval", plan_interval+ yield "amount_cents", amount_cents+ yield "currency", subscription.get("currency", "")+ yield "livemode", payload.get("livemode", False)diff --git a/autogpt_platform/backend/backend/blocks/stripe/triggers_test.py b/autogpt_platform/backend/backend/blocks/stripe/triggers_test.pynew file mode 100644index 0000000000..df5333386b--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/stripe/triggers_test.py@@ -0,0 +1,182 @@+"""Tests for StripeSubscriptionTriggerBlock.run() payload parsing.++The bundled ``test_input``/``test_output`` (exercised by the standard block+runner) only covers ``customer.subscription.created``. These cover the other+two subscribable events, the older top-level ``plan`` payload shape, the+nickname fallback, and the malformed-payload path.+"""++import copy++import pytest++from backend.blocks.stripe._auth import TEST_CREDENTIALS_INPUT+from backend.blocks.stripe.triggers import (+ StripeSubscriptionTriggerBlock,+ load_example_payload,+)+++async def run_block(payload: dict) -> dict:+ """Run the block over ``payload`` and collect its outputs by name."""+ block = StripeSubscriptionTriggerBlock()+ input_data = StripeSubscriptionTriggerBlock.Input.model_validate(+ {"credentials": TEST_CREDENTIALS_INPUT, "payload": payload}+ )+ return {name: value async for name, value in block.run(input_data)}+++async def test_updated_event_reports_the_new_plan():+ """An upgrade must surface the price the subscription moved *to*."""+ outputs = await run_block(load_example_payload("customer.subscription.updated"))++ assert outputs["event_type"] == "customer.subscription.updated"+ assert outputs["subscription_id"] == "sub_1OxK2fLkdIwHu7ixABCDEFGH"+ assert outputs["customer_id"] == "cus_Pq1234ABCDEF"+ assert outputs["status"] == "active"+ assert outputs["plan_name"] == "Pro Yearly"+ assert outputs["plan_interval"] == "year"+ assert outputs["amount_cents"] == 19200+ assert outputs["currency"] == "usd"+ assert outputs["livemode"] is False+++async def test_deleted_event_surfaces_cancellation_context():+ """A cancellation must be distinguishable from a scheduled end."""+ outputs = await run_block(load_example_payload("customer.subscription.deleted"))++ assert outputs["event_type"] == "customer.subscription.deleted"+ assert outputs["status"] == "canceled"+ assert outputs["canceled_at"] == 1714678400+ assert outputs["cancel_at_period_end"] is False+++async def test_scheduled_cancellation_is_not_reported_as_canceled():+ """``cancel_at_period_end`` is the only signal for a not-yet-ended cancel."""+ payload = copy.deepcopy(load_example_payload("customer.subscription.updated"))+ payload["data"]["object"]["cancel_at_period_end"] = True++ outputs = await run_block(payload)++ assert outputs["cancel_at_period_end"] is True+ assert outputs["canceled_at"] == 0+ assert outputs["status"] == "active"+++async def test_falls_back_to_top_level_plan_on_older_api_versions():+ """Pre-2019 API versions send no ``items``, only a flat ``plan``."""+ payload = copy.deepcopy(load_example_payload("customer.subscription.created"))+ del payload["data"]["object"]["items"]++ outputs = await run_block(payload)++ assert outputs["plan_name"] == "Pro Monthly"+ assert outputs["plan_interval"] == "month"+ assert outputs["amount_cents"] == 2000+++async def test_plan_name_falls_back_to_price_id_without_a_nickname():+ """Most prices have no nickname; the raw ID is better than an empty string."""+ payload = copy.deepcopy(load_example_payload("customer.subscription.created"))+ payload["data"]["object"]["items"]["data"][0]["price"]["nickname"] = None++ outputs = await run_block(payload)++ assert outputs["plan_name"] == "price_1OxABCLkdIwHu7ixMonthlyPro"+++async def test_missing_unit_amount_falls_back_to_zero():+ """Metered prices carry no `unit_amount`; the output is typed `int`."""+ payload = copy.deepcopy(load_example_payload("customer.subscription.created"))+ payload["data"]["object"]["items"]["data"][0]["price"]["unit_amount"] = None++ outputs = await run_block(payload)++ assert outputs["amount_cents"] == 0+++ "events, expected",+ [+ (+ {"created": True, "updated": True, "deleted": False},+ ["customer.subscription.created", "customer.subscription.updated"],+ ),+ (+ {"created": False, "updated": False, "deleted": True},+ ["customer.subscription.deleted"],+ ),+ (+ {"created": True, "updated": True, "deleted": True},+ [+ "customer.subscription.created",+ "customer.subscription.updated",+ "customer.subscription.deleted",+ ],+ ),+ ],+)+def test_event_filter_maps_to_stripe_event_names(events, expected):+ """The toggles must expand to the exact names registered with Stripe.++ A typo in `event_format`, or a toggle that stops reaching the filter, would+ silently register the wrong events — the webhook would then be live but+ never deliver.+ """+ config = StripeSubscriptionTriggerBlock().webhook_config+ assert config is not None+ derived = [+ config.event_format.format(event=name)+ for name, enabled in events.items()+ if enabled+ ]+ assert derived == expected+++ "event_type, enabled",+ [+ ("customer.subscription.created", True),+ ("customer.subscription.deleted", False),+ ("customer.subscription.trial_will_end", False),+ ],+)+def test_block_only_triggers_on_enabled_events(event_type, enabled):+ """The same mapping is used on the way back in, to route a delivery."""+ block = StripeSubscriptionTriggerBlock()+ trigger_config = {"events": {"created": True, "updated": True, "deleted": False}}+ assert block.is_triggered_by_event_type(trigger_config, event_type) is enabled+++async def test_updated_event_exposes_previous_attributes():+ """`updated` fires on any mutation; this is what separates an upgrade."""+ payload = copy.deepcopy(load_example_payload("customer.subscription.updated"))+ payload["data"]["previous_attributes"] = {"items": {"data": [{"price": "old"}]}}++ outputs = await run_block(payload)++ assert outputs["previous_attributes"] == {"items": {"data": [{"price": "old"}]}}+++async def test_previous_attributes_defaults_to_empty_mapping():+ """Absent on created/deleted — must be {} rather than None for a dict output."""+ outputs = await run_block(load_example_payload("customer.subscription.created"))++ assert outputs["previous_attributes"] == {}+++async def test_malformed_payload_emits_no_partial_output():+ """Yielding "error" aborts the block, so nothing may be emitted before it."""+ outputs = await run_block({"type": "customer.subscription.created"})++ assert list(outputs) == ["error"]+ assert "Failed to parse Stripe subscription payload" in outputs["error"]diff --git a/autogpt_platform/backend/backend/integrations/providers.py b/autogpt_platform/backend/backend/integrations/providers.pyindex ac4c968edb..34c154f5a8 100644--- a/autogpt_platform/backend/backend/integrations/providers.py+++ b/autogpt_platform/backend/backend/integrations/providers.py@@ -50,6 +50,7 @@ class ProviderName(str, Enum):SLANT3D = "slant3d"SMARTLEAD = "smartlead"SMTP = "smtp"+ STRIPE = "stripe"TELEGRAM = "telegram"TWITTER = "twitter"TODOIST = "todoist"diff --git a/autogpt_platform/backend/backend/integrations/webhooks/__init__.py b/autogpt_platform/backend/backend/integrations/webhooks/__init__.pyindex 4deb79b064..83307c273b 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/__init__.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/__init__.py@@ -15,6 +15,7 @@ def load_webhook_managers() -> dict["ProviderName", type["BaseWebhooksManager"]]from .compass import CompassWebhookManagerfrom .github import GithubWebhooksManagerfrom .slant3d import Slant3DWebhooksManager+ from .stripe import StripeWebhooksManagerfrom .telegram import TelegramWebhooksManagerwebhook_managers.update(@@ -24,6 +25,7 @@ def load_webhook_managers() -> dict["ProviderName", type["BaseWebhooksManager"]]CompassWebhookManager,GithubWebhooksManager,Slant3DWebhooksManager,+ StripeWebhooksManager,TelegramWebhooksManager,]}diff --git a/autogpt_platform/backend/backend/integrations/webhooks/stripe.py b/autogpt_platform/backend/backend/integrations/webhooks/stripe.pynew file mode 100644index 0000000000..582717bff0--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/webhooks/stripe.py@@ -0,0 +1,205 @@+import hashlib+import hmac+import logging+import time+from urllib.parse import urlencode++from fastapi import HTTPException, Request+from strenum import StrEnum++from backend.data import integrations+from backend.data.model import APIKeyCredentials, Credentials+from backend.integrations.providers import ProviderName+from backend.util.request import Requests, Response++from ._base import BaseWebhooksManager++logger = logging.getLogger(__name__)++STRIPE_API_URL = "https://api.stripe.com/v1"+# Tolerance window for Stripe timestamp verification (5 minutes)+STRIPE_TIMESTAMP_TOLERANCE = 300+# `webhook.config` key holding the secret Stripe returns at endpoint creation.+# Shared by the writer (`_register_webhook`) and the reader (`verify_signature`).+SIGNING_SECRET_KEY = "signing_secret" # pragma: allowlist secret+++class StripeWebhookType(StrEnum):+ ACCOUNT = "account"+++def _signatures_match(expected: str, candidate: str) -> bool:+ """Constant-time compare that treats a non-ASCII candidate as a mismatch."""+ try:+ return hmac.compare_digest(expected, candidate)+ except TypeError:+ return False+++def _error_message(response: Response) -> str:+ """+ Pull Stripe's error message out of a failed response.++ Falls back to the status code: an error from a proxy in front of Stripe+ (or a 5xx HTML page) isn't necessarily JSON, and a JSONDecodeError here+ would mask the actual failure.+ """+ try:+ message = response.json().get("error", {}).get("message")+ except Exception:+ message = None+ return message or f"HTTP {response.status}"+++class StripeWebhooksManager(BaseWebhooksManager):+ PROVIDER_NAME = ProviderName.STRIPE+ WebhookType = StripeWebhookType++ @classmethod+ async def verify_signature(+ cls,+ webhook: integrations.Webhook,+ request: Request,+ ) -> None:+ sig_header = request.headers.get("Stripe-Signature")+ if not sig_header:+ raise HTTPException(+ status_code=403, detail="Stripe-Signature header is missing"+ )++ # Stripe stores its signing secret in config, not the platform-generated secret+ signing_secret = webhook.config.get(SIGNING_SECRET_KEY, "")+ if not signing_secret:+ raise HTTPException(+ status_code=500, detail="Stripe signing secret not configured"+ )++ # Parse Stripe-Signature header: t=timestamp,v1=signature. During a+ # signing-secret rotation Stripe signs each delivery with every active+ # secret, so there can be more than one v1 entry.+ timestamp = ""+ v1_sigs: list[str] = []+ for part in sig_header.split(","):+ key, _, value = part.partition("=")+ key = key.strip()+ if key == "t":+ timestamp = value.strip()+ elif key == "v1":+ v1_sigs.append(value.strip())+ if not timestamp or not v1_sigs:+ raise HTTPException(+ status_code=403, detail="Invalid Stripe-Signature format"+ )++ # Reject stale timestamps. `int()` parses arbitrarily large values, so+ # subtracting one from a float raises OverflowError rather than+ # ValueError — both are just a malformed header, not a server fault.+ try:+ age = abs(time.time() - int(timestamp))+ except (ValueError, OverflowError):+ raise HTTPException(+ status_code=403, detail="Invalid Stripe-Signature timestamp"+ )+ if age > STRIPE_TIMESTAMP_TOLERANCE:+ raise HTTPException(+ status_code=403, detail="Stripe webhook timestamp is too old"+ )++ # Sign the raw bytes: decoding and re-encoding the body would transcode+ # the whole payload for nothing, and blow up on a non-UTF-8 body.+ payload_body = await request.body()+ expected = hmac.new(+ signing_secret.encode("utf-8"),+ msg=f"{timestamp}.".encode("utf-8") + payload_body,+ digestmod=hashlib.sha256,+ ).hexdigest()++ # `compare_digest` raises TypeError on a non-ASCII str, and Starlette+ # decodes headers as latin-1 — so an arbitrary `v1=<non-ascii>` would+ # turn a 403 into an unhandled 500 on a public endpoint.+ if not any(_signatures_match(expected, sig) for sig in v1_sigs):+ raise HTTPException(+ status_code=403, detail="Stripe webhook signature mismatch"+ )++ @classmethod+ async def validate_payload(+ cls,+ webhook: integrations.Webhook,+ request: Request,+ credentials: Credentials | None,+ ) -> tuple[dict, str]:+ payload = await request.json()+ event_type = payload.get("type", "")+ if not event_type:+ raise HTTPException(+ status_code=400, detail="Stripe event type missing from payload"+ )+ return payload, event_type++ async def _register_webhook(+ self,+ credentials: Credentials,+ webhook_type: StripeWebhookType,+ resource: str,+ events: list[str],+ ingress_url: str,+ secret: str,+ ) -> tuple[str, dict]:+ if not isinstance(credentials, APIKeyCredentials):+ raise ValueError("Stripe webhook registration requires an API key")++ api_key = credentials.api_key.get_secret_value()++ # Stripe's API takes form encoding, not JSON+ form_data = urlencode(+ [("url", ingress_url)] + [("enabled_events[]", event) for event in events]+ )++ response = await Requests(raise_for_status=False).post(+ f"{STRIPE_API_URL}/webhook_endpoints",+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/x-www-form-urlencoded",+ },+ data=form_data,+ )++ if not response.ok:+ raise ValueError(+ f"Stripe webhook registration failed: {_error_message(response)}"+ )++ data = response.json()+ # Store Stripe's signing secret in config — it's only returned on creation,+ # so a 200 without it leaves a webhook that can never verify a delivery.+ if not data.get("id") or not data.get("secret"):+ raise ValueError(+ "Stripe webhook registration returned no endpoint ID or signing secret"+ )+ return data["id"], {SIGNING_SECRET_KEY: data["secret"]}++ async def _deregister_webhook(+ self, webhook: integrations.Webhook, credentials: Credentials+ ) -> None:+ if not isinstance(credentials, APIKeyCredentials):+ logger.warning(+ "Cannot deregister Stripe webhook: API key credentials required"+ )+ return++ endpoint_id = webhook.provider_webhook_id+ if not endpoint_id:+ return++ api_key = credentials.api_key.get_secret_value()+ response = await Requests(raise_for_status=False).delete(+ f"{STRIPE_API_URL}/webhook_endpoints/{endpoint_id}",+ headers={"Authorization": f"Bearer {api_key}"},+ )++ if response.status not in (200, 404):+ logger.warning(+ f"Failed to deregister Stripe webhook {endpoint_id}: "+ f"{_error_message(response)}"+ )diff --git a/autogpt_platform/backend/backend/integrations/webhooks/stripe_test.py b/autogpt_platform/backend/backend/integrations/webhooks/stripe_test.pynew file mode 100644index 0000000000..a9430d251c--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/webhooks/stripe_test.py@@ -0,0 +1,405 @@+import hashlib+import hmac+import json+import time+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from fastapi import HTTPException, Request+from pydantic import SecretStr++from backend.data import integrations+from backend.data.model import APIKeyCredentials, OAuth2Credentials+from backend.integrations.providers import ProviderName+from backend.integrations.webhooks.stripe import (+ STRIPE_TIMESTAMP_TOLERANCE,+ StripeWebhooksManager,+ StripeWebhookType,+)++SIGNING_SECRET = "whsec_test_secret"+PAYLOAD = json.dumps({"type": "customer.subscription.created"}).encode()+++def make_webhook(config: dict | None = None) -> integrations.Webhook:+ return integrations.Webhook(+ id="webhook_123",+ user_id="user_123",+ provider=ProviderName.STRIPE,+ credentials_id="creds_123",+ webhook_type=StripeWebhookType.ACCOUNT,+ resource="",+ events=["customer.subscription.created"],+ config={"signing_secret": SIGNING_SECRET} if config is None else config,+ secret="platform-secret-not-used-by-stripe",+ provider_webhook_id="we_123",+ )+++def make_request(headers: dict[str, str], body: bytes = PAYLOAD) -> Request:+ request = Request(+ {+ "type": "http",+ "method": "POST",+ "path": "/ingress",+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()],+ }+ )+ request._body = body+ return request+++def sign(timestamp: int, body: bytes = PAYLOAD, secret: str = SIGNING_SECRET) -> str:+ signature = hmac.new(+ secret.encode(),+ msg=f"{timestamp}.{body.decode()}".encode(),+ digestmod=hashlib.sha256,+ ).hexdigest()+ return f"t={timestamp},v1={signature}"+++def oauth2_credentials() -> OAuth2Credentials:+ return OAuth2Credentials(+ id="creds_123",+ provider="stripe",+ title="Stripe OAuth",+ access_token=SecretStr("token"),+ scopes=[],+ )+++def api_key_credentials() -> APIKeyCredentials:+ return APIKeyCredentials(+ id="creds_123",+ provider="stripe",+ api_key=SecretStr("sk_test_123"),+ title="Stripe API key",+ expires_at=None,+ )+++async def test_verify_signature_accepts_valid_signature() -> None:+ request = make_request({"Stripe-Signature": sign(int(time.time()))})+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+++async def test_verify_signature_rejects_tampered_payload() -> None:+ # Signature is computed over PAYLOAD but a different body is delivered+ request = make_request(+ {"Stripe-Signature": sign(int(time.time()))}, body=b'{"type": "spoofed"}'+ )+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+++async def test_verify_signature_accepts_one_of_several_v1_signatures() -> None:+ """Stripe signs with every active secret during a secret rotation."""+ now = int(time.time())+ rotated = sign(now, secret="whsec_previous_secret")+ current = sign(now)+ header = f"{rotated},{current.split(',', 1)[1]}"+ await StripeWebhooksManager.verify_signature(+ make_webhook(), make_request({"Stripe-Signature": header})+ )+++async def test_verify_signature_handles_non_utf8_body() -> None:+ """Signing operates on raw bytes, so an undecodable body must not 500."""+ body = b"\xff\xfe not utf-8"+ now = int(time.time())+ signature = hmac.new(+ SIGNING_SECRET.encode(),+ msg=f"{now}.".encode() + body,+ digestmod=hashlib.sha256,+ ).hexdigest()+ request = make_request({"Stripe-Signature": f"t={now},v1={signature}"}, body=body)+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+++async def test_verify_signature_rejects_wrong_secret() -> None:+ request = make_request(+ {"Stripe-Signature": sign(int(time.time()), secret="whsec_other_secret")}+ )+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+++async def test_verify_signature_rejects_replayed_timestamp() -> None:+ stale = int(time.time()) - 3600+ request = make_request({"Stripe-Signature": sign(stale)})+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+++ "sig_header",+ ["garbage", "t=notanumber,v1=abc", "v1=abc", "t=123"],+)+async def test_verify_signature_rejects_malformed_header(sig_header: str) -> None:+ request = make_request({"Stripe-Signature": sig_header})+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+++async def test_verify_signature_rejects_non_ascii_signature() -> None:+ """Starlette decodes headers as latin-1, and compare_digest rejects+ non-ASCII str with a TypeError — which would 500 a public endpoint."""+ now = int(time.time())+ request = make_request({"Stripe-Signature": f"t={now},v1=ÿ"})+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+++async def test_verify_signature_tolerates_whitespace_around_values() -> None:+ now = int(time.time())+ signature = sign(now).split(",", 1)[1].removeprefix("v1=")+ request = make_request({"Stripe-Signature": f"t= {now} , v1= {signature} "})+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+++async def test_verify_signature_rejects_absurd_timestamp() -> None:+ """`int()` parses unbounded values, so the float subtraction overflows —+ a malformed header must still be a 403, not an unhandled 500."""+ request = make_request({"Stripe-Signature": f"t={'9' * 400},v1=abc"})+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+++async def test_verify_signature_accepts_edge_of_tolerance_window() -> None:+ """Just inside the 5-minute window is still a valid delivery."""+ recent = int(time.time()) - (STRIPE_TIMESTAMP_TOLERANCE - 5)+ request = make_request({"Stripe-Signature": sign(recent)})+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+++async def test_verify_signature_rejects_just_outside_tolerance_window() -> None:+ stale = int(time.time()) - (STRIPE_TIMESTAMP_TOLERANCE + 5)+ request = make_request({"Stripe-Signature": sign(stale)})+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+++async def test_verify_signature_rejects_missing_header() -> None:+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(), make_request({}))+ assert exc_info.value.status_code == 403+++async def test_verify_signature_errors_without_signing_secret() -> None:+ request = make_request({"Stripe-Signature": sign(int(time.time()))})+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.verify_signature(make_webhook(config={}), request)+ assert exc_info.value.status_code == 500+++async def test_validate_payload_returns_event_type() -> None:+ request = make_request({})+ payload, event_type = await StripeWebhooksManager.validate_payload(+ make_webhook(), request, None+ )+ assert event_type == "customer.subscription.created"+ assert payload == json.loads(PAYLOAD)+++async def test_validate_payload_rejects_payload_without_type() -> None:+ request = make_request({}, body=b"{}")+ with pytest.raises(HTTPException) as exc_info:+ await StripeWebhooksManager.validate_payload(make_webhook(), request, None)+ assert exc_info.value.status_code == 400+++async def test_register_webhook_form_encodes_events_and_stores_signing_secret() -> None:+ response = AsyncMock()+ response.ok = True+ response.json = lambda: {"id": "we_new", "secret": SIGNING_SECRET}++ with patch(+ "backend.integrations.webhooks.stripe.Requests.post",+ new=AsyncMock(return_value=response),+ ) as mock_post:+ webhook_id, config = await StripeWebhooksManager()._register_webhook(+ credentials=api_key_credentials(),+ webhook_type=StripeWebhookType.ACCOUNT,+ resource="",+ events=["customer.subscription.created", "customer.subscription.updated"],+ ingress_url="https://example.com/api/integrations/stripe/webhooks/1/ingress",+ secret="unused",+ )++ assert webhook_id == "we_new"+ assert config == {"signing_secret": SIGNING_SECRET}++ sent_body = mock_post.call_args.kwargs["data"]+ # The ingress URL must be percent-encoded, not interpolated raw+ assert "https%3A%2F%2Fexample.com" in sent_body+ assert sent_body.count("enabled_events") == 2+++async def test_register_webhook_surfaces_stripe_error_message() -> None:+ response = AsyncMock()+ response.ok = False+ response.status = 400+ response.json = lambda: {"error": {"message": "You have reached the maximum"}}++ with patch(+ "backend.integrations.webhooks.stripe.Requests.post",+ new=AsyncMock(return_value=response),+ ):+ with pytest.raises(ValueError, match="You have reached the maximum"):+ await StripeWebhooksManager()._register_webhook(+ credentials=api_key_credentials(),+ webhook_type=StripeWebhookType.ACCOUNT,+ resource="",+ events=["customer.subscription.created"],+ ingress_url="https://example.com/ingress",+ secret="unused",+ )+++async def test_register_webhook_error_falls_back_when_body_is_not_json() -> None:+ """A 5xx from a proxy in front of Stripe isn't JSON; don't mask it."""+ response = AsyncMock()+ response.ok = False+ response.status = 502+ response.json = MagicMock(side_effect=ValueError("not JSON"))++ with patch(+ "backend.integrations.webhooks.stripe.Requests.post",+ new=AsyncMock(return_value=response),+ ):+ with pytest.raises(ValueError, match="HTTP 502"):+ await StripeWebhooksManager()._register_webhook(+ credentials=api_key_credentials(),+ webhook_type=StripeWebhookType.ACCOUNT,+ resource="",+ events=["customer.subscription.created"],+ ingress_url="https://example.com/ingress",+ secret="unused",+ )+++async def test_register_webhook_requires_api_key_credentials() -> None:+ oauth_credentials = oauth2_credentials()+ with pytest.raises(ValueError):+ await StripeWebhooksManager()._register_webhook(+ credentials=oauth_credentials,+ webhook_type=StripeWebhookType.ACCOUNT,+ resource="",+ events=["customer.subscription.created"],+ ingress_url="https://example.com/ingress",+ secret="unused",+ )+++async def test_deregister_webhook_deletes_endpoint() -> None:+ response = AsyncMock()+ response.status = 200+ response.json = lambda: {}++ with patch(+ "backend.integrations.webhooks.stripe.Requests.delete",+ new=AsyncMock(return_value=response),+ ) as mock_delete:+ await StripeWebhooksManager()._deregister_webhook(+ make_webhook(), api_key_credentials()+ )++ assert mock_delete.call_args.args[0].endswith("/webhook_endpoints/we_123")+++async def test_deregister_webhook_warns_on_delete_failure(caplog) -> None:+ """A failed teardown must be visible: it leaves a live endpoint at Stripe."""+ response = AsyncMock()+ response.status = 500+ response.json = lambda: {"error": {"message": "Something went wrong"}}++ with patch(+ "backend.integrations.webhooks.stripe.Requests.delete",+ new=AsyncMock(return_value=response),+ ):+ await StripeWebhooksManager()._deregister_webhook(+ make_webhook(), api_key_credentials()+ )++ assert "Something went wrong" in caplog.text+++async def test_deregister_webhook_skips_non_api_key_credentials() -> None:+ oauth_credentials = oauth2_credentials()+ with patch(+ "backend.integrations.webhooks.stripe.Requests.delete",+ new=AsyncMock(),+ ) as mock_delete:+ await StripeWebhooksManager()._deregister_webhook(+ make_webhook(), oauth_credentials+ )++ mock_delete.assert_not_called()+++async def test_deregister_webhook_without_endpoint_id_makes_no_request() -> None:+ webhook = make_webhook()+ webhook.provider_webhook_id = ""++ with patch(+ "backend.integrations.webhooks.stripe.Requests.delete",+ new=AsyncMock(),+ ) as mock_delete:+ await StripeWebhooksManager()._deregister_webhook(+ webhook, api_key_credentials()+ )++ mock_delete.assert_not_called()+++async def test_register_webhook_rejects_success_body_without_secret() -> None:+ """A 200 with no signing secret would leave a webhook that can never verify."""+ response = AsyncMock()+ response.ok = True+ response.json = lambda: {"id": "we_new"}++ with patch(+ "backend.integrations.webhooks.stripe.Requests.post",+ new=AsyncMock(return_value=response),+ ):+ with pytest.raises(ValueError, match="no endpoint ID or signing secret"):+ await StripeWebhooksManager()._register_webhook(+ credentials=api_key_credentials(),+ webhook_type=StripeWebhookType.ACCOUNT,+ resource="",+ events=["customer.subscription.created"],+ ingress_url="https://example.com/ingress",+ secret="unused",+ )diff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex c5ffd77fec..07199a8eea 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -185,6 +185,7 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [Retrieve Information](block-integrations/data.md#retrieve-information) | Reads back a key-value pair previously saved by PersistInformationBlock || [SQL Query](block-integrations/data.md#sql-query) | Execute a SQL query || [Screenshot Web Page](block-integrations/data.md#screenshot-web-page) | Takes a screenshot of a specified website using ScreenshotOne API |+| [Stripe Subscription Trigger](block-integrations/stripe/triggers.md#stripe-subscription-trigger) | Triggers on Stripe subscription events (new, upgrade, cancel) |## Text Processingdiff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.mdindex debb0d15df..482d20d2ec 100644--- a/docs/integrations/SUMMARY.md+++ b/docs/integrations/SUMMARY.md@@ -121,6 +121,7 @@* [Slant3D Webhook](block-integrations/slant3d/webhook.md)* [Smartlead Campaign](block-integrations/smartlead/campaign.md)* [Stagehand Blocks](block-integrations/stagehand/blocks.md)+* [Stripe Triggers](block-integrations/stripe/triggers.md)* [System Library Operations](block-integrations/system/library_operations.md)* [System Store Operations](block-integrations/system/store_operations.md)* [Tavily Crawl](block-integrations/tavily/crawl.md)diff --git a/docs/integrations/block-integrations/stripe/triggers.md b/docs/integrations/block-integrations/stripe/triggers.mdnew file mode 100644index 0000000000..f6dc37f71c--- /dev/null+++ b/docs/integrations/block-integrations/stripe/triggers.md@@ -0,0 +1,71 @@+# Stripe Triggers+<!-- MANUAL: file_description -->+Blocks that trigger on subscription lifecycle events delivered by Stripe webhooks.+<!-- END MANUAL -->++## Stripe Subscription Trigger++### What it is+Triggers on Stripe subscription events (new, upgrade, cancel). Uses Stripe webhooks directly — real external customers only, no internal or demo account noise.++### How it works+<!-- MANUAL: how_it_works -->+Connect a Stripe API secret key (`sk_live_...` or `sk_test_...`) with permission to+manage webhook endpoints. The platform registers a webhook endpoint in your Stripe+account for the events you selected and stores the signing secret Stripe returns.+Every incoming delivery is checked against that secret — timestamp plus HMAC-SHA256+over the raw body, with a five-minute replay window — before the block fires.++Plan details are read from the subscription's first item price, falling back to the+top-level `plan` object on older Stripe API versions. The endpoint is deleted from+your Stripe account when the last trigger using it goes away.++Deliveries that fail verification never reach the block: a missing or malformed+`Stripe-Signature` header, a signature that doesn't match, or a timestamp outside+the five-minute window are all rejected with `403`, and an event with no `type` is+rejected with `400`. If a delivery passes verification but its subscription object+can't be parsed, the block fails with a parse error rather than emitting partial+outputs.++Endpoints are shared, not one per trigger: the platform reuses an existing webhook+whose registered events already cover the ones you asked for, keyed on your+credentials. Stripe caps an account at 16 endpoints, so that ceiling is reached+only with many distinct event-filter combinations on the same key, not with many+triggers.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| events | Subscription lifecycle events to subscribe to. Cancellation and churn workflows need `deleted`, which is off by default. Note that `updated` is high-volume — Stripe sends it for any change to the subscription, including renewals, payment-method changes and metadata edits, not just upgrades. Use `previous_attributes` to tell an upgrade from routine churn. | Events | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the payload could not be parsed | str |+| payload | Full Stripe event object as received from the webhook | Dict[str, Any] |+| event_type | Stripe event type, e.g. customer.subscription.created | str |+| subscription_id | Stripe subscription ID (sub_...) | str |+| customer_id | Stripe customer ID (cus_...) | str |+| status | Subscription status: active, trialing, past_due, canceled, etc. | str |+| cancel_at_period_end | True if the subscription is scheduled to end when the current billing period does, rather than having ended already | bool |+| canceled_at | Unix timestamp of when the subscription was canceled, or 0 if it has not been canceled | int |+| previous_attributes | On `updated` events, the changed fields' prior values, as sent by Stripe. Empty for other events. Compare against the subscription in `payload` to tell an upgrade from a renewal — e.g. a key of `items` or `plan` means the plan itself changed. | Dict[str, Any] |+| plan_name | Nickname of the subscription's first item price. Prices without a nickname fall back to the raw price ID (price_...). Only the first item is read; see `payload` for multi-item subscriptions. | str |+| plan_interval | Billing interval of the first subscription item: day, week, month or year | str |+| amount_cents | Unit amount of the first subscription item, in the smallest currency unit — cents for USD, but whole units for zero-decimal currencies like JPY and KRW. This is not the subscription total when there is more than one item. | int |+| currency | Three-letter ISO currency code | str |+| livemode | True for live Stripe data, False for test mode | bool |++### Possible use case+<!-- MANUAL: use_case -->+**Revenue Notifications**: Post to a team Slack or Discord channel whenever someone subscribes or upgrades, wiring `customer_id`, `plan_name`, and `amount_cents` into the message. Because the events come from Stripe rather than an internal database, only real paying customers are counted.++**Onboarding Sequences**: Kick off a welcome email series on `customer.subscription.created`, branching on `plan_name` so each tier gets the setup steps that apply to it.++**Churn Recovery**: Start a win-back workflow on `customer.subscription.deleted`, using `cancel_at_period_end` to tell a scheduled end (still time to intervene) from an account that has already lapsed.+<!-- END MANUAL -->++---