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(analytics): track stripe subscription events (#2012)
dev-rbcd3f7ed18979
diff --git a/infra/stacks/authentication-service/Pulumi.dev.yaml b/infra/stacks/authentication-service/Pulumi.dev.yamlindex 1b5342c82f..0470d281d4 100644--- a/infra/stacks/authentication-service/Pulumi.dev.yaml+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml@@ -21,3 +21,7 @@ config:authentication-service:github_client_id_key: github-client-id-devauthentication-service:github_client_secret_key: github-client-secret-devauthentication-service:github_idp_id_key: github-idp-id-dev++ authentication-service:ga_measurement_id: G-52HPEL3FTV+ authentication-service:ga_api_secret: ga-api-secret+ authentication-service:meta_pixel_id: 639142540393286diff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yamlindex d165fe3936..e265361aa9 100644--- a/infra/stacks/authentication-service/Pulumi.prod.yaml+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml@@ -21,3 +21,7 @@ config:authentication-service:github_client_id_key: github-client-id-prodauthentication-service:github_client_secret_key: github-client-secret-prodauthentication-service:github_idp_id_key: github-idp-id-prod++ authentication-service:ga_measurement_id: G-52HPEL3FTV+ authentication-service:ga_api_secret: ga-api-secret+ authentication-service:meta_pixel_id: 639142540393286diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex 18239587a9..11aabe1df2 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -143,6 +143,18 @@ const stripeWebhookSecretKeyArn: pulumi.Output<string> = aws.secretsmanagerconst MACRO_API_TOKENS = getMacroApiToken();+const GA_ANALYTICS_MEASUREMENT_ID = config.require('ga_measurement_id');++const GA_API_SECRET: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: config.require('ga_api_secret') })+ .apply((secret) => secret.secretString);++const META_PIXEL_ID = config.require('meta_pixel_id');++// const META_ACCESS_TOKEN: pulumi.Output<string> = aws.secretsmanager+// .getSecretVersionOutput({ secretId: config.require('meta_access_token') })+// .apply((secret) => secret.secretString);+const secretKeyArns = [pulumi.interpolate`${jwtSecretKeyArn}`,pulumi.interpolate`${fusionauthApiKeySecretKeyArn}`,@@ -323,6 +335,19 @@ const service = new AuthenticationService('authentication-service', {name: 'DD_ENV',value: stack,},+ // Analytics+ {+ name: 'GA_MEASUREMENT_ID',+ value: GA_ANALYTICS_MEASUREMENT_ID,+ },+ {+ name: 'GA_API_SECRET',+ value: pulumi.interpolate`${GA_API_SECRET}`,+ },+ {+ name: 'META_PIXEL_ID',+ value: META_PIXEL_ID,+ },],});diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.tsindex 1eec547fa6..84c2915ee0 100644--- a/js/app/packages/service-clients/service-auth/client.ts+++ b/js/app/packages/service-clients/service-auth/client.ts@@ -407,6 +407,7 @@ export const authServiceClient = {successUrl: string;cancelUrl: string;discount?: string | null;+ gaClientId?: string | null;}) {return mapOk(await fetchWithAuth<{ url: string }>(`${authHost}/user/stripe/checkout`, {@@ -415,6 +416,7 @@ export const authServiceClient = {successUrl: args.successUrl,cancelUrl: args.cancelUrl,discount: args.discount ?? undefined,+ gaClientId: args.gaClientId ?? undefined,}),}),(result) => result.urldiff --git a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequest.tsindex 138c0d7fee..08967c4bcb 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequest.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequest.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { CreateCheckoutSessionRequestDiscount } from './createCheckoutSessionRequestDiscount';+import type { CreateCheckoutSessionRequestGaClientId } from './createCheckoutSessionRequestGaClientId';/*** Request body for creating a Stripe checkout session@@ -14,6 +15,8 @@ export interface CreateCheckoutSessionRequest {cancelUrl: string;/** Optional discount/promo code to apply */discount?: CreateCheckoutSessionRequestDiscount;+ /** Google Analytics client ID for conversion tracking */+ gaClientId?: CreateCheckoutSessionRequestGaClientId;/** The URL to redirect to on successful checkout */successUrl: string;}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequestGaClientId.ts b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequestGaClientId.tsnew file mode 100644index 0000000000..6196a931f9--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequestGaClientId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Google Analytics client ID for conversion tracking+ */+export type CreateCheckoutSessionRequestGaClientId = string | null;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.tsindex 501a6046e5..1fe62345ab 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts@@ -10,6 +10,7 @@ export * from './appleLoginRequest';export * from './createAccountMergeRequest';export * from './createCheckoutSessionRequest';export * from './createCheckoutSessionRequestDiscount';+export * from './createCheckoutSessionRequestGaClientId';export * from './createInProgressLinkResponse';export * from './createPortalSessionRequest';export * from './createTeamRequest';diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 79a922fe6f..e88f2308d1 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -2982,6 +2982,10 @@"type": ["string", "null"],"description": "Optional discount/promo code to apply"},+ "gaClientId": {+ "type": ["string", "null"],+ "description": "Google Analytics client ID for conversion tracking"+ },"successUrl": {"type": "string","description": "The URL to redirect to on successful checkout"diff --git a/js/app/packages/service-clients/service-stripe/client.ts b/js/app/packages/service-clients/service-stripe/client.tsindex 325e33bc6e..25bc133385 100644--- a/js/app/packages/service-clients/service-stripe/client.ts+++ b/js/app/packages/service-clients/service-stripe/client.ts@@ -2,16 +2,45 @@ import { isOk } from '@core/util/maybeResult';import { registerClient } from '@core/util/mockClient';import { authServiceClient } from '@service-auth/client';+/**+ * Gets the Google Analytics client ID using gtag.+ * Returns a promise that resolves with the client ID or undefined if GA is blocked/unavailable.+ * Times out after 500ms to avoid blocking checkout if GA is blocked by an ad blocker.+ */+function getGaClientId(): Promise<string | undefined> {+ return new Promise((resolve) => {+ if (typeof gtag !== 'function') {+ resolve(undefined);+ return;+ }++ const timeout = setTimeout(() => resolve(undefined), 500);++ gtag(+ 'get',+ import.meta.env.VITE_GA_MEASUREMENT_ID,+ 'client_id',+ (clientId: string) => {+ clearTimeout(timeout);+ resolve(clientId);+ }+ );+ });+}+export const stripeServiceClient = {/*** Creates a checkout session* @returns The URL of the checkout session*/createCheckoutSession: async (type: string = '', discount?: string) => {+ const gaClientId = await getGaClientId();+const result = await authServiceClient.createCheckoutSession({successUrl: `${window.location.origin}/app/?subscriptionSuccess=true${type ? `&type=${type}` : ''}`,cancelUrl: `${window.location.origin}/app`,discount: discount ?? null,+ gaClientId: gaClientId ?? null,});if (!isOk(result)) {diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 0cb661eeb5..492866dae7 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -190,6 +190,19 @@ dependencies = ["url",]+[[package]]+name = "analytics_client"+version = "0.1.0"+dependencies = [+ "chrono",+ "hex",+ "reqwest",+ "serde",+ "serde_json",+ "sha2",+ "tracing",+]+[[package]]name = "android_system_properties"version = "0.1.5"@@ -558,6 +571,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"name = "authentication_service"version = "0.1.0"dependencies = [+ "analytics_client","anyhow","async-stripe","async-stripe-webhook",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 1490544dec..75199ee6af 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -4,6 +4,7 @@ resolver = "2"members = ["ai","ai_format",+ "analytics_client","ai_tools","ai_toolset","anthropic",diff --git a/rust/cloud-storage/analytics_client/Cargo.toml b/rust/cloud-storage/analytics_client/Cargo.tomlnew file mode 100644index 0000000000..98f13f5d7d--- /dev/null+++ b/rust/cloud-storage/analytics_client/Cargo.toml@@ -0,0 +1,14 @@+[package]+edition = "2021"+name = "analytics_client"+version = "0.1.0"+publish = false++[dependencies]+chrono = { workspace = true }+hex = { workspace = true }+reqwest = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sha2 = { workspace = true }+tracing = { workspace = true }diff --git a/rust/cloud-storage/analytics_client/src/lib.rs b/rust/cloud-storage/analytics_client/src/lib.rsnew file mode 100644index 0000000000..f29948000c--- /dev/null+++ b/rust/cloud-storage/analytics_client/src/lib.rs@@ -0,0 +1,115 @@+#![deny(missing_docs)]+//! Analytics client for tracking events to GA and Meta.++mod providers;++pub use providers::{MetaActionSource, MetaUserData};++use providers::{GoogleAnalyticsProvider, MetaProvider};+use serde::Serialize;+use std::sync::Arc;++/// Configuration for Google Analytics.+#[derive(Clone)]+pub struct GoogleAnalyticsConfig {+ /// GA4 Measurement ID (e.g., "G-XXXXXXXXXX")+ pub measurement_id: String,+ /// Measurement Protocol API secret+ pub api_secret: String,+}++/// Configuration for Meta Conversions API.+#[derive(Clone)]+pub struct MetaConfig {+ /// Meta Pixel ID+ pub pixel_id: String,+ /// Conversions API access token+ pub access_token: String,+ /// Test event code for testing (optional)+ pub test_event_code: Option<String>,+}++/// Configuration for the analytics client.+#[derive(Clone, Default)]+pub struct AnalyticsClientConfig {+ /// Google Analytics configuration (optional)+ pub google_analytics: Option<GoogleAnalyticsConfig>,+ /// Meta Conversions API configuration (optional)+ pub meta: Option<MetaConfig>,+}++/// Analytics client for tracking events to GA and Meta.+#[derive(Clone)]+pub struct AnalyticsClient {+ google: Option<Arc<GoogleAnalyticsProvider>>,+ meta: Option<Arc<MetaProvider>>,+}++impl AnalyticsClient {+ /// Creates a new analytics client with the given configuration.+ pub fn new(config: AnalyticsClientConfig) -> Self {+ let google = config+ .google_analytics+ .map(|c| Arc::new(GoogleAnalyticsProvider::new(c.measurement_id, c.api_secret)));++ let meta = config.meta.map(|c| {+ Arc::new(MetaProvider::new(+ c.pixel_id,+ c.access_token,+ c.test_event_code,+ ))+ });++ Self { google, meta }+ }++ /// Creates a no-op analytics client (no providers configured).+ pub fn noop() -> Self {+ Self {+ google: None,+ meta: None,+ }+ }++ /// Tracks an event to Google Analytics.+ ///+ /// Returns `Ok(())` if GA is not configured (no-op).+ #[tracing::instrument(skip(self, params), err)]+ pub async fn track_ga(+ &self,+ client_id: &str,+ event_name: &str,+ params: impl Serialize,+ ) -> Result<(), reqwest::Error> {+ if let Some(ref provider) = self.google {+ provider.track(client_id, event_name, params).await?;+ }+ Ok(())+ }++ /// Tracks an event to Meta Conversions API.+ ///+ /// Returns `Ok(())` if Meta is not configured (no-op).+ ///+ /// - `event_name`: Standard event name (e.g., "Purchase", "Lead") or custom event+ /// - `user_data`: User identification data for matching+ /// - `action_source`: Where the conversion originated+ /// - `event_id`: Optional deduplication ID (recommended for server events)+ /// - `custom_data`: Additional event data+ #[tracing::instrument(skip(self, user_data, custom_data), err)]+ pub async fn track_meta(+ &self,+ event_name: &str,+ user_data: &MetaUserData,+ action_source: MetaActionSource,+ event_id: Option<&str>,+ custom_data: impl Serialize,+ ) -> Result<(), reqwest::Error> {+ if let Some(ref provider) = self.meta {+ provider+ .track(event_name, user_data, action_source, event_id, custom_data)+ .await?;+ }+ Ok(())+ }+}diff --git a/rust/cloud-storage/analytics_client/src/providers/google_analytics.rs b/rust/cloud-storage/analytics_client/src/providers/google_analytics.rsnew file mode 100644index 0000000000..b4480cf2b5--- /dev/null+++ b/rust/cloud-storage/analytics_client/src/providers/google_analytics.rs@@ -0,0 +1,55 @@+//! Google Analytics 4 Measurement Protocol provider.++use serde::Serialize;++/// Google Analytics 4 Measurement Protocol provider.+#[derive(Clone, Debug)]+pub struct GoogleAnalyticsProvider {+ client: reqwest::Client,+ measurement_id: String,+ api_secret: String,+}++impl GoogleAnalyticsProvider {+ /// Creates a new Google Analytics provider.+ pub fn new(measurement_id: String, api_secret: String) -> Self {+ Self {+ client: reqwest::Client::new(),+ measurement_id,+ api_secret,+ }+ }++ /// Tracks an event to GA4.+ #[tracing::instrument(skip(self, params), err)]+ pub async fn track(+ &self,+ client_id: &str,+ event_name: &str,+ params: impl Serialize,+ ) -> Result<(), reqwest::Error> {+ let url = format!(+ "https://www.google-analytics.com/mp/collect?measurement_id={}&api_secret={}",+ self.measurement_id, self.api_secret+ );++ let params = serde_json::to_value(params).unwrap_or_default();++ let payload = serde_json::json!({+ "client_id": client_id,+ "events": [{+ "name": event_name,+ "params": params,+ }],+ });++ self.client+ .post(&url)+ .json(&payload)+ .send()+ .await?+ .error_for_status()?;++ Ok(())+ }+}diff --git a/rust/cloud-storage/analytics_client/src/providers/meta.rs b/rust/cloud-storage/analytics_client/src/providers/meta.rsnew file mode 100644index 0000000000..9cee6872b3--- /dev/null+++ b/rust/cloud-storage/analytics_client/src/providers/meta.rs@@ -0,0 +1,140 @@+//! Meta (Facebook) Conversions API provider.++use serde::Serialize;+use sha2::{Digest, Sha256};++/// Action source for Meta Conversions API events.+#[derive(Clone, Debug, Default)]+pub enum MetaActionSource {+ /// Conversion happened on a website+ #[default]+ Website,+ /// Conversion happened in a mobile app+ App,+}++impl MetaActionSource {+ fn as_str(&self) -> &'static str {+ match self {+ MetaActionSource::Website => "website",+ MetaActionSource::App => "app",+ }+ }+}++/// User data for Meta Conversions API.+/// Email is automatically hashed (SHA256) before sending.+#[derive(Clone, Debug, Default)]+pub struct MetaUserData {+ /// User email (will be normalized and hashed)+ pub email: Option<String>,+ /// Facebook click ID from URL parameter `fbclid`+ pub fbc: Option<String>,+ /// Facebook browser ID from `_fbp` cookie+ pub fbp: Option<String>,+}++impl MetaUserData {+ /// Creates user data with an email.+ pub fn with_email(email: impl Into<String>) -> Self {+ Self {+ email: Some(email.into()),+ ..Default::default()+ }+ }++ fn to_json(&self) -> serde_json::Value {+ let mut data = serde_json::Map::new();++ if let Some(ref email) = self.email {+ data.insert("em".to_string(), serde_json::json!([hash_sha256(email)]));+ }+ if let Some(ref fbc) = self.fbc {+ data.insert("fbc".to_string(), serde_json::json!(fbc));+ }+ if let Some(ref fbp) = self.fbp {+ data.insert("fbp".to_string(), serde_json::json!(fbp));+ }++ serde_json::Value::Object(data)+ }+}++fn hash_sha256(value: &str) -> String {+ let mut hasher = Sha256::new();+ hasher.update(value.to_lowercase().trim().as_bytes());+ hex::encode(hasher.finalize())+}++/// Meta provider for server-side event tracking.+#[derive(Clone)]+pub struct MetaProvider {+ client: reqwest::Client,+ pixel_id: String,+ access_token: String,+ test_event_code: Option<String>,+}++impl MetaProvider {+ /// Creates a new Meta provider.+ pub fn new(pixel_id: String, access_token: String, test_event_code: Option<String>) -> Self {+ Self {+ client: reqwest::Client::new(),+ pixel_id,+ access_token,+ test_event_code,+ }+ }++ /// Tracks an event to Meta Conversions API.+ ///+ /// - `event_name`: Standard event name (e.g., "Purchase", "Lead") or custom event+ /// - `user_data`: User identification data for matching+ /// - `action_source`: Where the conversion originated+ /// - `event_id`: Optional deduplication ID (recommended for server events)+ /// - `custom_data`: Additional event data (will be serialized to JSON)+ #[tracing::instrument(skip(self, user_data, custom_data), err)]+ pub async fn track(+ &self,+ event_name: &str,+ user_data: &MetaUserData,+ action_source: MetaActionSource,+ event_id: Option<&str>,+ custom_data: impl Serialize,+ ) -> Result<(), reqwest::Error> {+ let url = format!("https://graph.facebook.com/v18.0/{}/events", self.pixel_id);++ let event_time = chrono::Utc::now().timestamp();+ let custom_data = serde_json::to_value(custom_data).unwrap_or_default();++ let mut event = serde_json::json!({+ "event_name": event_name,+ "event_time": event_time,+ "action_source": action_source.as_str(),+ "user_data": user_data.to_json(),+ "custom_data": custom_data,+ });++ if let Some(id) = event_id {+ event["event_id"] = serde_json::json!(id);+ }++ let mut payload = serde_json::json!({+ "data": [event],+ "access_token": self.access_token,+ });++ if let Some(ref test_code) = self.test_event_code {+ payload["test_event_code"] = serde_json::json!(test_code);+ }++ self.client+ .post(&url)+ .json(&payload)+ .send()+ .await?+ .error_for_status()?;++ Ok(())+ }+}diff --git a/rust/cloud-storage/analytics_client/src/providers/mod.rs b/rust/cloud-storage/analytics_client/src/providers/mod.rsnew file mode 100644index 0000000000..8e44b538e8--- /dev/null+++ b/rust/cloud-storage/analytics_client/src/providers/mod.rs@@ -0,0 +1,7 @@+//! Analytics provider implementations.++mod google_analytics;+mod meta;++pub use google_analytics::GoogleAnalyticsProvider;+pub use meta::{MetaActionSource, MetaProvider, MetaUserData};diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.tomlindex 9ab9aa06c1..5f1992ea60 100644--- a/rust/cloud-storage/authentication_service/Cargo.toml+++ b/rust/cloud-storage/authentication_service/Cargo.toml@@ -23,6 +23,7 @@ local = []rate_limit = [][dependencies]+analytics_client = { path = "../analytics_client" }anyhow = { workspace = true }async-stripe = { workspace = true, default-features = false, features = ["billing",diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 70ec0e06c7..3b0ec23216 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -1,5 +1,6 @@use std::sync::Arc;+use analytics_client::AnalyticsClient;use axum::extract::FromRef;use github::domain::service::GithubLinkServiceImpl;use github::outbound::github_auth_client::GithubAuthImpl;@@ -58,6 +59,7 @@ pub(crate) struct ApiContext {Arc<UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>>, // Note: since FromRef doesn't support generics we have to specify the concrete types herepub teams_service: Arc<TeamsServiceType>,pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,+ pub analytics_client: Arc<AnalyticsClient>,pub referral_service: Arc<ReferralServiceType>,}diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe.rsindex 0754e26ff9..3d28fcb1c4 100644--- a/rust/cloud-storage/authentication_service/src/api/user/stripe.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe.rs@@ -74,6 +74,8 @@ pub struct CreateCheckoutSessionRequest {pub cancel_url: String,/// Optional discount/promo code to applypub discount: Option<String>,+ /// Google Analytics client ID for conversion tracking+ pub ga_client_id: Option<String>,}/// Response containing the Stripe session URL@@ -165,6 +167,19 @@ pub async fn create_checkout_session(None};+ // Build subscription metadata from optional tracking fields+ let mut metadata = std::collections::HashMap::new();+ if let Some(ga_client_id) = req.ga_client_id {+ metadata.insert("ga_client_id".to_string(), ga_client_id);+ }++ // Only set subscription_data if we have metadata to include+ let subscription_data =+ (!metadata.is_empty()).then_some(stripe::CreateCheckoutSessionSubscriptionData {+ metadata: Some(metadata),+ ..Default::default()+ });+// Create the checkout sessionlet params = stripe::CreateCheckoutSession {customer: Some(customer_id),@@ -183,6 +198,7 @@ pub async fn create_checkout_session(quantity: Some(1),..Default::default()}]),+ subscription_data,..Default::default()};diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rsindex d6a996aa16..affd21d79c 100644--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs@@ -1,6 +1,8 @@use std::collections::HashMap;use crate::api::context::ApiContext;++use analytics_client::{AnalyticsClient, MetaActionSource, MetaUserData};use anyhow::Context;use axum::{body::Bytes,@@ -13,8 +15,10 @@ use macro_user_id::email::Email;use model::response::ErrorResponse;use referral::domain::ports::ReferralService;use roles_and_permissions::domain::port::UserRolesAndPermissionsService;+use serde::Serialize;use stripe_webhook::{EventObject, EventType};use teams::domain::team_repo::TeamService;+use tracing::Instrument;/// The main entrypoint for all stripe webhook events handling#[tracing::instrument(skip(ctx, headers, body))]@@ -73,12 +77,13 @@ pub async fn handler("processing stripe event");+ let event_type = event.type_.clone();match event.type_ {EventType::CustomerSubscriptionCreated| EventType::CustomerSubscriptionUpdated| EventType::CustomerSubscriptionDeleted| EventType::CustomerSubscriptionPaused => {- handle_customer_subscription_event(&ctx, event.data.object).await+ handle_customer_subscription_event(&ctx, event.data.object, event_type).await}_ => {tracing::error!(event_type=?event.type_, "unexpected event type");@@ -97,6 +102,7 @@ pub async fn handler(async fn handle_customer_subscription_event(ctx: &ApiContext,event_object: EventObject,+ event_type: EventType,) -> anyhow::Result<()> {let subscription = match event_object {EventObject::CustomerSubscriptionCreated(subscription) => subscription,@@ -135,10 +141,32 @@ async fn handle_customer_subscription_event(let subscription_id = subscription.id.as_str();let subscription_status = subscription.status.as_str();+ // Extract subscription value and currency for analytics+ let subscription_currency = Some(subscription.currency.to_string());+ let subscription_value: i64 = subscription+ .items+ .data+ .iter()+ .filter_map(|item| {+ let unit_amount = item.price.unit_amount?;+ let quantity = item.quantity.unwrap_or(1) as i64;+ Some(unit_amount * quantity)+ })+ .sum();+ let subscription_value = if subscription_value > 0 {+ Some(subscription_value)+ } else {+ None+ };++ // Extract GA client ID from subscription metadata for analytics tracking+ let ga_client_id = subscription.metadata.get("ga_client_id").cloned();+tracing::info!(email=%email.as_ref(),subscription_id,subscription_status,+ ga_client_id=?ga_client_id,"processing stripe subscription");@@ -147,8 +175,21 @@ async fn handle_customer_subscription_event(if let Some(team_id) = subscription.metadata.get("team_id") {let team_id = macro_uuid::string_to_uuid(team_id)?;// We need to handle team subscriptions differently than regular subscriptions.- return handle_team_subscription_event(ctx, subscription_id, subscription_status, &team_id)- .await;+ return handle_team_subscription_event(+ ctx,+ subscription_id,+ subscription_status,+ &team_id,+ SubscriptionTrackingData {+ ga_client_id: ga_client_id.clone(),+ email: email.as_ref().to_string(),+ value_cents: subscription_value,+ currency: subscription_currency,+ status: subscription_status.to_string(),+ is_new: matches!(event_type, EventType::CustomerSubscriptionCreated),+ },+ )+ .await;}// Check for duplicate subscriptions@@ -240,9 +281,26 @@ async fn handle_customer_subscription_event(}ctx.user_roles_and_permissions_service- .update_user_roles_and_permissions_for_subscription(email, subscription_status.try_into()?)+ .update_user_roles_and_permissions_for_subscription(+ email.clone(),+ subscription_status.try_into()?,+ ).await?;+ // Track conversion events to GA and Meta (fire-and-forget)+ track_stripe_subscription(+ ctx.analytics_client.clone(),+ subscription_id,+ SubscriptionTrackingData {+ ga_client_id,+ email: email.as_ref().to_string(),+ value_cents: subscription_value,+ currency: subscription_currency,+ status: subscription_status.to_string(),+ is_new: matches!(event_type, EventType::CustomerSubscriptionCreated),+ },+ );+Ok(())}@@ -281,27 +339,36 @@ async fn check_and_process_referral(/// Handles team subscription events./// NOTE: We use strs here because there is a mismatch between stripe crate and/// stripe_webhook crate for these types. *sigh*-#[tracing::instrument(skip(ctx), err, ret)]+#[tracing::instrument(skip(ctx, tracking_data), err, ret)]async fn handle_team_subscription_event(ctx: &ApiContext,subscription_id: &str,subscription_status: &str,team_id: &uuid::Uuid,+ tracking_data: SubscriptionTrackingData,) -> anyhow::Result<()> {if subscription_status == "trialing" {anyhow::bail!("unexpected trialing status for team subscription");}match subscription_status {- // Subscription is active, we do not need to do anything.- // Perhaps eventually we would have a "paused" status on the team we'd want to update- "active" => Ok(()),- // If the stripe subscription is somehow cancelled, we need to remove roles from the team- // members.+ "active" => {+ track_stripe_subscription(ctx.analytics_client.clone(), subscription_id, tracking_data);+ Ok(())+ }"canceled" | "past_due" | "paused" | "unpaid" => {ctx.teams_service.revoke_permissions_for_team_members(team_id).await?;++ track_stripe_subscription(+ ctx.analytics_client.clone(),+ subscription_id,+ SubscriptionTrackingData {+ is_new: false,+ ..tracking_data+ },+ );Ok(())}_ => {@@ -309,3 +376,100 @@ async fn handle_team_subscription_event(}}}++#[derive(Debug, Clone, Serialize)]+struct SubscriptionEvent {+ transaction_id: String,+ value: f64,+ currency: String,+}++#[derive(Debug, Clone)]+struct SubscriptionTrackingData {+ ga_client_id: Option<String>,+ email: String,+ value_cents: Option<i64>,+ currency: Option<String>,+ status: String,+ is_new: bool,+}++/// Tracks a Stripe subscription event to GA and Meta (fire-and-forget).+#[tracing::instrument(skip(client, data), fields(subscription_id, email = %data.email, status = %data.status, is_new = data.is_new))]+fn track_stripe_subscription(+ client: std::sync::Arc<AnalyticsClient>,+ subscription_id: &str,+ data: SubscriptionTrackingData,+) {+ let Some(value_cents) = data.value_cents else {+ return;+ };+ let Some(currency) = data.currency else {+ return;+ };++ // Create a child span for the spawned task, linked to the current span+ let task_span = tracing::info_span!(+ parent: tracing::Span::current(),+ "track_stripe_subscription_task"+ );++ let subscription_id = subscription_id.to_string();++ tokio::spawn(+ async move {+ let event = SubscriptionEvent {+ transaction_id: subscription_id.clone(),+ value: value_cents as f64 / 100.0,+ currency: currency.to_uppercase(),+ };+ let user_data = MetaUserData::with_email(&data.email);+ let event_id = Some(subscription_id.as_str());++ match (data.status.as_str(), data.is_new) {+ ("active" | "trialing", true) => {+ if let Some(ref ga_client_id) = data.ga_client_id+ && let Err(e) = client.track_ga(ga_client_id, "purchase", &event).await+ {+ tracing::warn!(error = ?e, "failed to track GA purchase event");+ }++ if let Err(e) = client+ .track_meta(+ "Purchase",+ &user_data,+ MetaActionSource::Website,+ event_id,+ &event,+ )+ .await+ {+ tracing::warn!(error = ?e, "failed to track Meta purchase event");+ }+ }+ ("canceled", _) => {+ if let Some(ref ga_client_id) = data.ga_client_id+ && let Err(e) = client.track_ga(ga_client_id, "refund", &event).await+ {+ tracing::warn!(error = ?e, "failed to track GA refund event");+ }++ if let Err(e) = client+ .track_meta(+ "CancelSubscription",+ &user_data,+ MetaActionSource::Website,+ event_id,+ &event,+ )+ .await+ {+ tracing::warn!(error = ?e, "failed to track Meta cancel event");+ }+ }+ _ => {}+ }+ }+ .instrument(task_span),+ );+}diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rsindex d4310a3c7c..e908c2df4a 100644--- a/rust/cloud-storage/authentication_service/src/config.rs+++ b/rust/cloud-storage/authentication_service/src/config.rs@@ -68,6 +68,18 @@ pub struct Config {pub github_client_secret: String,/// The github idp idpub github_idp_id: String,++ /// GA4 Measurement ID (optional, e.g., "G-XXXXXXXXXX")+ pub ga_measurement_id: Option<String>,+ /// GA4 Measurement Protocol API secret (optional)+ pub ga_api_secret: Option<String>,++ /// Meta Pixel ID (optional)+ pub meta_pixel_id: Option<String>,+ /// Meta Conversions API access token (optional)+ pub meta_access_token: Option<String>,+ /// Meta test event code for testing (optional)+ pub meta_test_event_code: Option<String>,}impl Config {@@ -127,6 +139,15 @@ impl Config {let github_idp_id =std::env::var("GITHUB_IDP_ID").context("GITHUB_IDP_ID must be provided")?;+ // Google Analytics configuration+ let ga_measurement_id = std::env::var("GA_MEASUREMENT_ID").ok();+ let ga_api_secret = std::env::var("GA_API_SECRET").ok();++ // Meta Conversions API configuration+ let meta_pixel_id = std::env::var("META_PIXEL_ID").ok();+ let meta_access_token = std::env::var("META_ACCESS_TOKEN").ok();+ let meta_test_event_code = std::env::var("META_TEST_EVENT_CODE").ok();+Ok(Config {base_url,database_url,@@ -150,6 +171,11 @@ impl Config {github_client_id,github_client_secret,github_idp_id,+ ga_measurement_id,+ ga_api_secret,+ meta_pixel_id,+ meta_access_token,+ meta_test_event_code,})}}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex a9bafdbd84..48fd39b531 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -1,4 +1,5 @@#![recursion_limit = "256"]+use analytics_client::{AnalyticsClient, AnalyticsClientConfig, GoogleAnalyticsConfig, MetaConfig};use anyhow::Context;use config::{Config, Environment};use document_storage_service_client::DocumentStorageServiceClient;@@ -189,6 +190,34 @@ async fn main() -> anyhow::Result<()> {.search_event_queue(&config.search_event_queue);tracing::trace!("initialized sqs client");+ // Initialize analytics client with configured providers+ let analytics_client = AnalyticsClient::new(AnalyticsClientConfig {+ google_analytics: config+ .ga_measurement_id+ .as_ref()+ .zip(config.ga_api_secret.as_ref())+ .map(|(measurement_id, api_secret)| {+ tracing::info!("configuring Google Analytics");+ GoogleAnalyticsConfig {+ measurement_id: measurement_id.clone(),+ api_secret: api_secret.clone(),+ }+ }),+ meta: config+ .meta_pixel_id+ .as_ref()+ .zip(config.meta_access_token.as_ref())+ .map(|(pixel_id, access_token)| {+ tracing::info!("configuring Meta Conversions API");+ MetaConfig {+ pixel_id: pixel_id.clone(),+ access_token: access_token.clone(),+ test_event_code: config.meta_test_event_code.clone(),+ }+ }),+ });+ tracing::trace!("initialized analytics client");+let user_roles_and_permissions_macro_db = MacroDB::new(db.clone());let user_roles_and_permissions_service = UserRolesAndPermissionsServiceImpl::new(@@ -258,6 +287,7 @@ async fn main() -> anyhow::Result<()> {ios_app_bundle_id: IOS_APP_BUNDLE_ID.to_string(),},}),+ analytics_client: Arc::new(analytics_client),},config.port,)