Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(bots): add Stripe payment bot (#5375)
teo319046c527b9
diff --git a/bun.lock b/bun.lockindex fe1b13ae36..809ba91d74 100644--- a/bun.lock+++ b/bun.lock@@ -325,6 +325,18 @@"wrangler": "^4.110.0",},},+ "services/bots/stripe-payment-bot": {+ "name": "stripe-payment-bot",+ "version": "0.0.1",+ "dependencies": {+ "stripe": "^22.4.0",+ },+ "devDependencies": {+ "@types/node": "^25.9.3",+ "bun-types": "^1.3.14",+ "wrangler": "^4.110.0",+ },+ },"services/lexical-service": {"name": "lexical-service","version": "0.0.1",@@ -3001,6 +3013,10 @@"strip-literal": ["[email protected]", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="],+ "stripe": ["[email protected]", "", { "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-LVJ+tcSYeqOSnXr3i+Kz2tZ7y0crLLdP2uwD/4wccrmEVyn0g/Heo0pF7as7rxS/sOjJzrb1lxgZY0Y0Dx1pSA=="],++ "stripe-payment-bot": ["stripe-payment-bot@workspace:services/bots/stripe-payment-bot"],+"strnum": ["[email protected]", "", {}, "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA=="],"stubs": ["[email protected]", "", {}, "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw=="],@@ -3603,6 +3619,8 @@"strip-literal/js-tokens": ["[email protected]", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="],+ "stripe-payment-bot/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg=="],+"superagent/readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],"supports-hyperlinks/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],@@ -3843,6 +3861,8 @@"string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],+ "stripe-payment-bot/@types/node/undici-types": ["[email protected]", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],+"swagger2openapi/node-fetch/whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],"swagger2openapi/yargs/cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],diff --git a/package.json b/package.jsonindex 845dbc71ef..baeccd9d37 100644--- a/package.json+++ b/package.json@@ -69,6 +69,7 @@"packages/lexical-core","services/ai-editing-worker","services/bots/anthropic-status-bot",+ "services/bots/stripe-payment-bot","services/lexical-service"],"catalog": {diff --git a/services/bots/stripe-payment-bot/README.md b/services/bots/stripe-payment-bot/README.mdnew file mode 100644index 0000000000..06f12ef0ac--- /dev/null+++ b/services/bots/stripe-payment-bot/README.md@@ -0,0 +1,105 @@+# stripe-payment-bot++Posts to every Macro channel containing the bot when a new Stripe payment is+received. It can be deployed from any Cloudflare account; it has no dependency+on a Macro-owned Worker or domain.++The bot handles paid Checkout sessions, delayed payment methods, and the first+successful invoice after a free trial. Unpaid sessions and unrelated Stripe+events are acknowledged and ignored.++## How it works++```text+Stripe webhook ──POST /webhook──> Cloudflare Worker+ │ Stripe SDK verifies the signature+ │ identify the first real payment+ ▼+ Macro SDK → list the bot's channel memberships+ → POST each channel's bot webhook+```++The destinations do not come from the Stripe event or Worker configuration.+`MACRO_BOT_TOKEN` authenticates the SDK request, and every channel where that+bot is an active participant receives the notification. Adding or removing the+bot from a channel changes the destinations automatically.++## Configuration++All deployment-specific values are Worker bindings:++- `MACRO_BOT_TOKEN`: API key for a team-owned Macro bot.+- `MACRO_ENV`: `dev`, `prod`, or `local`.+- `MACRO_STORAGE_URL`: optional storage API base URL override for a custom+ Macro deployment.+- `STRIPE_API_KEY`: restricted or secret Stripe API key.+- `STRIPE_WEBHOOK_SECRET`: signing secret for this deployment's Stripe webhook+ destination.++## Deploy++From this directory:++```bash+printf '%s' 'mbot_...' | wrangler secret put MACRO_BOT_TOKEN+printf '%s' 'prod' | wrangler secret put MACRO_ENV+printf '%s' 'rk_live_...' | wrangler secret put STRIPE_API_KEY+printf '%s' 'whsec_...' | wrangler secret put STRIPE_WEBHOOK_SECRET+bun run deploy+```++For a nonstandard Macro storage endpoint, also set:++```bash+printf '%s' 'https://your-storage-api.example.com' | \+ wrangler secret put MACRO_STORAGE_URL+```++`STRIPE_API_KEY` can be a restricted key with read access to subscriptions; it+is only used to confirm that a paid invoice is the first one after a trial.++Wrangler prints the URL assigned to the Worker in the deploying Cloudflare+account. In Stripe Workbench, create a webhook destination pointing to:++```text+<your-worker-url>/webhook+```++Subscribe it to these events:++- `checkout.session.completed`+- `checkout.session.async_payment_succeeded`+- `invoice.paid`++Copy that destination's signing secret (`whsec_...`) into the Worker secret+above. Test-mode and live-mode webhook destinations have different signing+secrets.++## Local development++Copy `dev.vars.example` to `.dev.vars`, fill in its values, then run:++```bash+just dev+```++Forward Stripe test events to the local server:++```bash+stripe listen \+ --events checkout.session.completed,checkout.session.async_payment_succeeded,invoice.paid \+ --forward-to localhost:8787/webhook+```++Use the `whsec_...` printed by `stripe listen` as+`STRIPE_WEBHOOK_SECRET`.++Stripe can occasionally deliver the same event more than once. This bot+intentionally accepts the small risk of duplicate channel notifications rather+than adding a database solely for deduplication.++## Checks++```bash+just check+```diff --git a/services/bots/stripe-payment-bot/biome.jsonc b/services/bots/stripe-payment-bot/biome.jsoncnew file mode 100644index 0000000000..6551745331--- /dev/null+++ b/services/bots/stripe-payment-bot/biome.jsonc@@ -0,0 +1,11 @@+{+ "$schema": "https://biomejs.dev/schemas/2.5.6/schema.json",+ "root": true,+ "extends": ["../../../biome.base.jsonc"],+ "vcs": {+ "root": "../../.."+ },+ "files": {+ "includes": ["**/*.{ts,tsx,js,jsx}", "!**/*.d.ts", "!**/node_modules"]+ }+}diff --git a/services/bots/stripe-payment-bot/dev.vars.example b/services/bots/stripe-payment-bot/dev.vars.examplenew file mode 100644index 0000000000..41fbd482b0--- /dev/null+++ b/services/bots/stripe-payment-bot/dev.vars.example@@ -0,0 +1,5 @@+MACRO_BOT_TOKEN=mbot_replace_me+MACRO_ENV=prod+# MACRO_STORAGE_URL=https://your-storage-api.example.com+STRIPE_API_KEY=rk_test_replace_me+STRIPE_WEBHOOK_SECRET=whsec_replace_mediff --git a/services/bots/stripe-payment-bot/justfile b/services/bots/stripe-payment-bot/justfilenew file mode 100644index 0000000000..47fe76a7bf--- /dev/null+++ b/services/bots/stripe-payment-bot/justfile@@ -0,0 +1,5 @@+dev:+ bunx wrangler dev++check:+ bunx tsc --noEmit --project tsconfig.jsondiff --git a/services/bots/stripe-payment-bot/package.json b/services/bots/stripe-payment-bot/package.jsonnew file mode 100644index 0000000000..e9557d06c7--- /dev/null+++ b/services/bots/stripe-payment-bot/package.json@@ -0,0 +1,19 @@+{+ "name": "stripe-payment-bot",+ "version": "0.0.1",+ "private": true,+ "type": "module",+ "scripts": {+ "dev": "wrangler dev",+ "check": "tsc --noEmit --project tsconfig.json",+ "deploy": "wrangler deploy"+ },+ "dependencies": {+ "stripe": "^22.4.0"+ },+ "devDependencies": {+ "@types/node": "^25.9.3",+ "bun-types": "^1.3.14",+ "wrangler": "^4.110.0"+ }+}diff --git a/services/bots/stripe-payment-bot/src/channel.ts b/services/bots/stripe-payment-bot/src/channel.tsnew file mode 100644index 0000000000..7132850217--- /dev/null+++ b/services/bots/stripe-payment-bot/src/channel.ts@@ -0,0 +1,60 @@+import type { Env } from '../../../../packages/sdk/src/config';+import { Macro } from '../../../../packages/sdk/src/macro';+import { unwrap } from '../../../../packages/sdk/src/utils';++export type ChannelConfig = {+ /** Bot API key (`mbot_...`) for the bot whose channels receive notifications. */+ botToken: string;+ /** Macro environment selected by the host. */+ env: Env;+ /** Optional storage API base URL for a custom Macro deployment. */+ storageUrl?: string;+};++/** Delivers a formatted message to every channel containing the bot. */+export type ChannelBroadcaster = (content: string) => Promise<void>;++/** Create a broadcaster backed by Macro's bot and channel webhook SDK methods. */+export function createChannelBroadcaster(+ config: ChannelConfig+): ChannelBroadcaster {+ const macro = new Macro({+ env: config.env,+ auth: { type: 'bot', token: config.botToken, scope: 'team' },+ hosts: config.storageUrl ? { storage: config.storageUrl } : undefined,+ });++ return async (content) => {+ const channels = await macro.bots.channels();+ const deliveries = await Promise.allSettled(+ channels.map(async (channel) => {+ const { message_id } = unwrap(+ await macro._client.storage.postChannelBotWebhook({+ path: { channel_id: channel.channel_id },+ body: { content },+ })+ );+ return { channelId: channel.channel_id, messageId: message_id };+ })+ );++ const failures = deliveries.filter(+ (delivery): delivery is PromiseRejectedResult =>+ delivery.status === 'rejected'+ );+ if (failures.length > 0) {+ failures.forEach((failure) => {+ console.error('Failed to post Stripe payment to a Macro channel', {+ error: failure.reason,+ });+ });+ throw new Error(+ `Failed to post to ${failures.length} of ${channels.length} Macro channels`+ );+ }++ console.log('Posted Stripe payment notification', {+ channelCount: channels.length,+ });+ };+}diff --git a/services/bots/stripe-payment-bot/src/worker.ts b/services/bots/stripe-payment-bot/src/worker.tsnew file mode 100644index 0000000000..a2db2ab8ba--- /dev/null+++ b/services/bots/stripe-payment-bot/src/worker.ts@@ -0,0 +1,258 @@+import Stripe from 'stripe';+import type { Env as MacroEnv } from '../../../../packages/sdk/src/config';+import { createChannelBroadcaster } from './channel';++type WorkerEnv = {+ MACRO_BOT_TOKEN: string;+ MACRO_ENV: string;+ MACRO_STORAGE_URL?: string;+ STRIPE_API_KEY: string;+ STRIPE_WEBHOOK_SECRET: string;+};++const REQUIRED_BINDINGS: readonly (keyof WorkerEnv)[] = [+ 'MACRO_BOT_TOKEN',+ 'MACRO_ENV',+ 'STRIPE_API_KEY',+ 'STRIPE_WEBHOOK_SECRET',+];++const MACRO_ENVIRONMENTS: readonly MacroEnv[] = ['dev', 'prod', 'local'];++type Payment = {+ amount: number;+ currency: string;+ customer: string;+ eventId: string;+ livemode: boolean;+ subscriptionId?: string;+};++const cryptoProvider = Stripe.createSubtleCryptoProvider();++function customerId(+ customer: string | Stripe.Customer | Stripe.DeletedCustomer | null+): string | undefined {+ return typeof customer === 'string' ? customer : customer?.id;+}++function subscriptionId(+ subscription: string | Stripe.Subscription | null+): string | undefined {+ return typeof subscription === 'string' ? subscription : subscription?.id;+}++function checkoutPayment(+ event:+ | Stripe.CheckoutSessionCompletedEvent+ | Stripe.CheckoutSessionAsyncPaymentSucceededEvent+): Payment | undefined {+ const session = event.data.object;+ if (+ session.payment_status !== 'paid' ||+ session.amount_total === null ||+ session.currency === null+ ) {+ return undefined;+ }++ const expandedCustomer =+ typeof session.customer === 'object' &&+ session.customer !== null &&+ !('deleted' in session.customer)+ ? session.customer+ : undefined;+ const email =+ session.customer_details?.email ??+ session.customer_email ??+ expandedCustomer?.email;+ const name = session.customer_details?.name ?? expandedCustomer?.name;++ return {+ amount: session.amount_total,+ currency: session.currency,+ customer:+ email && name+ ? `${name} (${email})`+ : (email ?? name ?? customerId(session.customer) ?? 'Unknown customer'),+ eventId: event.id,+ livemode: event.livemode,+ subscriptionId: subscriptionId(session.subscription),+ };+}++async function postTrialPayment(+ stripe: Stripe,+ event: Stripe.InvoicePaidEvent+): Promise<Payment | undefined> {+ const invoice = event.data.object;+ if (invoice.status !== 'paid' || invoice.amount_paid <= 0) return undefined;++ const legacyInvoice = invoice as Stripe.Invoice & {+ subscription?: string | Stripe.Subscription | null;+ };+ const subscriptionRef =+ invoice.parent?.subscription_details?.subscription ??+ legacyInvoice.subscription;+ if (!subscriptionRef) return undefined;++ const subscription =+ typeof subscriptionRef === 'string'+ ? await stripe.subscriptions.retrieve(subscriptionRef)+ : subscriptionRef;+ const trialEnd = subscription.trial_end;+ const fiveMinutes = 5 * 60;+ if (+ trialEnd === null ||+ trialEnd < invoice.period_start - fiveMinutes ||+ trialEnd > invoice.period_end + fiveMinutes+ ) {+ return undefined;+ }++ return {+ amount: invoice.amount_paid,+ currency: invoice.currency,+ customer:+ invoice.customer_email && invoice.customer_name+ ? `${invoice.customer_name} (${invoice.customer_email})`+ : (invoice.customer_email ??+ invoice.customer_name ??+ customerId(invoice.customer) ??+ 'Unknown customer'),+ eventId: event.id,+ livemode: event.livemode,+ subscriptionId: subscription.id,+ };+}++async function paymentFromEvent(+ stripe: Stripe,+ event: Stripe.Event+): Promise<Payment | undefined> {+ switch (event.type) {+ case 'checkout.session.completed':+ case 'checkout.session.async_payment_succeeded':+ return checkoutPayment(event);+ case 'invoice.paid':+ return postTrialPayment(stripe, event);+ default:+ return undefined;+ }+}++function formatAmount(amount: number, currency: string): string {+ const code = currency.toUpperCase();+ const formatter = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: code,+ });+ const fractionDigits = formatter.resolvedOptions().maximumFractionDigits ?? 2;+ return `${formatter.format(amount / 10 ** fractionDigits)} ${code}`;+}++function formatPayment(payment: Payment): string {+ const dashboardPrefix = payment.livemode ? '' : 'test/';+ const lines = [+ '💸 New Stripe payment',+ `Customer: ${payment.customer}`,+ `Amount: ${formatAmount(payment.amount, payment.currency)}`,+ ];+ if (payment.subscriptionId) {+ lines.push(`Subscription: ${payment.subscriptionId}`);+ }+ lines.push(+ `https://dashboard.stripe.com/${dashboardPrefix}events/${payment.eventId}`+ );+ return lines.join('\n');+}++function missingBindings(env: WorkerEnv): string[] {+ return REQUIRED_BINDINGS.filter((key) => !env[key]);+}++function parseMacroEnv(value: string): MacroEnv | undefined {+ return MACRO_ENVIRONMENTS.find((environment) => environment === value);+}++export default {+ async fetch(request: Request, env: WorkerEnv): Promise<Response> {+ const url = new URL(request.url);+ if (request.method === 'GET' && url.pathname === '/health') {+ return Response.json({ ok: true });+ }+ if (request.method !== 'POST' || url.pathname !== '/webhook') {+ return new Response('Not found', { status: 404 });+ }++ const missing = missingBindings(env);+ if (missing.length > 0) {+ return Response.json(+ { error: `missing worker bindings: ${missing.join(', ')}` },+ { status: 500 }+ );+ }++ const macroEnv = parseMacroEnv(env.MACRO_ENV);+ if (!macroEnv) {+ return Response.json(+ {+ error: `MACRO_ENV must be one of: ${MACRO_ENVIRONMENTS.join(', ')}`,+ },+ { status: 500 }+ );+ }++ const signature = request.headers.get('stripe-signature');+ if (!signature) {+ return new Response('Missing Stripe-Signature header', { status: 400 });+ }++ const stripe = new Stripe(env.STRIPE_API_KEY, {+ httpClient: Stripe.createFetchHttpClient(),+ });+ let event: Stripe.Event;+ try {+ event = await stripe.webhooks.constructEventAsync(+ await request.text(),+ signature,+ env.STRIPE_WEBHOOK_SECRET,+ undefined,+ cryptoProvider+ );+ } catch (error) {+ console.error('Invalid Stripe webhook', error);+ return new Response('Invalid Stripe webhook', { status: 400 });+ }++ let payment: Payment | undefined;+ try {+ payment = await paymentFromEvent(stripe, event);+ } catch (error) {+ console.error('Failed to load Stripe payment details', error);+ return new Response('Failed to load Stripe payment details', {+ status: 502,+ });+ }+ if (!payment) return Response.json({ ok: true, ignored: true });++ try {+ await createChannelBroadcaster({+ botToken: env.MACRO_BOT_TOKEN,+ env: macroEnv,+ storageUrl: env.MACRO_STORAGE_URL,+ })(formatPayment(payment));+ } catch (error) {+ console.error('Failed to post Stripe payment to Macro', error);+ return new Response('Failed to post Stripe payment to Macro', {+ status: 502,+ });+ }++ console.log('Posted Stripe payment', {+ eventId: payment.eventId,+ subscriptionId: payment.subscriptionId,+ });+ return Response.json({ ok: true });+ },+};diff --git a/services/bots/stripe-payment-bot/tsconfig.json b/services/bots/stripe-payment-bot/tsconfig.jsonnew file mode 100644index 0000000000..e48a371e23--- /dev/null+++ b/services/bots/stripe-payment-bot/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "target": "es2022",+ "module": "es2022",+ "moduleResolution": "Bundler",+ "resolveJsonModule": true,+ "moduleDetection": "force",+ "strict": true,+ "noEmit": true,+ "lib": ["es2022", "dom"],+ "types": ["@types/node", "bun-types"]+ },+ "exclude": ["node_modules"],+ "include": ["src"]+}diff --git a/services/bots/stripe-payment-bot/wrangler.jsonc b/services/bots/stripe-payment-bot/wrangler.jsoncnew file mode 100644index 0000000000..820d4d1602--- /dev/null+++ b/services/bots/stripe-payment-bot/wrangler.jsonc@@ -0,0 +1,10 @@+{+ "$schema": "node_modules/wrangler/config-schema.json",+ "name": "stripe-payment-bot",+ "main": "src/worker.ts",+ "compatibility_date": "2026-08-01",+ "compatibility_flags": ["nodejs_compat"],+ "observability": {+ "enabled": true+ }+}