Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: enhance Stripe webhook handling with invoice notifications (#712)

Naveen Kashyap2bba5c3adb15
diff --git a/.env.example b/.env.example
index 4d444fbbfd..f498c51dae 100644
--- a/.env.example
+++ b/.env.example
@@ -35,6 +35,10 @@ POSTHOG_PROJECT_PUBLIC_KEY="********************"
STRIPE_SECRET_KEY="sk_test_*************"
STRIPE_WEBHOOK_SECRET="whsec_************"
+# GTM (notifications fan-out)
+GTM_URL="http://localhost:4000"
+GTM_EVENTS_API_SECRET_KEY=""
+
# Resend
RESEND_API_KEY="************************"
RESEND_DOMAIN="carbon.ms" # or your domain (no trailing slashes or protocols)
diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.ts
index b200aed51e..58b5678da6 100644
--- a/packages/auth/src/config/env.ts
+++ b/packages/auth/src/config/env.ts
@@ -64,6 +64,8 @@ declare global {
STRIPE_WEBHOOK_SECRET: string;
STRIPE_BYPASS_COMPANY_IDS: string;
STRIPE_BYPASS_USER_IDS: string;
+ GTM_URL: string;
+ GTM_EVENTS_API_SECRET_KEY: string;
SUPABASE_ANON_KEY: string;
SUPABASE_URL: string;
SUPABASE_DB_URL: string;
@@ -285,6 +287,14 @@ export const STRIPE_BYPASS_COMPANY_IDS = getEnv("STRIPE_BYPASS_COMPANY_IDS", {
export const STRIPE_BYPASS_USER_IDS = getEnv("STRIPE_BYPASS_USER_IDS", {
isRequired: false
});
+export const GTM_URL = getEnv("GTM_URL", {
+ isRequired: false,
+ isSecret: false
+});
+export const GTM_EVENTS_API_SECRET_KEY = getEnv("GTM_EVENTS_API_SECRET_KEY", {
+ isRequired: false,
+ isSecret: true
+});
export const REDIS_URL = getEnv("REDIS_URL", {
isRequired: true,
isSecret: true
diff --git a/packages/stripe/src/gtm-events.server.ts b/packages/stripe/src/gtm-events.server.ts
new file mode 100644
index 0000000000..f91586988d
--- /dev/null
+++ b/packages/stripe/src/gtm-events.server.ts
@@ -0,0 +1,24 @@
+import { GTM_EVENTS_API_SECRET_KEY, GTM_URL } from "@carbon/auth";
+
+export async function forwardToGtm(
+ type: string,
+ metadata: Record<string, unknown>
+): Promise<void> {
+ if (!GTM_URL || !GTM_EVENTS_API_SECRET_KEY) return;
+
+ const res = await fetch(`${GTM_URL}/api/events`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ "x-gtm-events-key": GTM_EVENTS_API_SECRET_KEY
+ },
+ body: JSON.stringify({ type, metadata }),
+ signal: AbortSignal.timeout(5000)
+ });
+
+ if (!res.ok) {
+ throw new Error(
+ `[gtm-events] ${res.status}: ${await res.text().catch(() => "")}`
+ );
+ }
+}
diff --git a/packages/stripe/src/stripe.server.ts b/packages/stripe/src/stripe.server.ts
index afaf93c01d..98f3483c2a 100644
--- a/packages/stripe/src/stripe.server.ts
+++ b/packages/stripe/src/stripe.server.ts
@@ -13,6 +13,7 @@ import { Edition, Plan } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { Stripe } from "stripe";
import { z } from "zod";
+import { forwardToGtm } from "./gtm-events.server";
export const stripe = STRIPE_SECRET_KEY
? new Stripe(STRIPE_SECRET_KEY, {
@@ -58,6 +59,7 @@ const allowedEventTypes = [
"customer.subscription.pending_update_applied",
"customer.subscription.pending_update_expired",
"customer.subscription.trial_will_end",
+ "invoice.sent",
"invoice.paid",
"invoice.payment_failed",
"invoice.payment_action_required",
@@ -280,6 +282,10 @@ export async function getCheckoutUrl({
success_url: `${getAppUrl()}/api/webhook/stripe`,
cancel_url: `${getAppUrl()}/api/webhook/stripe`,
payment_method_types: ["card", "us_bank_account", "cashapp"],
+ billing_address_collection: "required",
+ automatic_tax: { enabled: true },
+ tax_id_collection: { enabled: true, required: "never" },
+ customer_update: { name: "auto", address: "auto" },
...(plan.data?.stripeTrialPeriodDays &&
plan.data.stripeTrialPeriodDays > 0 && {
subscription_data: {
@@ -393,6 +399,8 @@ export async function processStripeEvent({
throw new Error("Stripe webhook handler failed");
}
+ const collectedTaxId = data.customer_details?.tax_ids?.[0]?.value;
+
try {
await Promise.all([
syncStripeDataToKV(customer, companyId),
@@ -401,7 +409,13 @@ export async function processStripeEvent({
companyId,
userId,
data.customer_details?.email ?? undefined
- )
+ ),
+ collectedTaxId
+ ? getCarbonServiceRole()
+ .from("company")
+ .update({ taxId: collectedTaxId })
+ .eq("id", companyId)
+ : Promise.resolve()
]);
} catch (error) {
console.error("Error processing webhook:", error);
@@ -444,6 +458,14 @@ export async function processStripeEvent({
console.error("Error processing webhook:", error);
throw new Error("Stripe webhook handler failed");
}
+ } else if (
+ eventType === "invoice.sent" ||
+ eventType === "invoice.payment_succeeded" ||
+ eventType === "invoice.payment_failed"
+ ) {
+ forwardToGtm(eventType, { invoice: event.data.object }).catch((err) => {
+ console.error("[gtm-events] forward failed:", err);
+ });
}
}