Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(analytics): stripe subscription events not tracked in posthog (#2254)

dev-rb764340825134
diff --git a/infra/stacks/authentication-service/Pulumi.dev.yaml b/infra/stacks/authentication-service/Pulumi.dev.yaml
index 2b5b80f5fe..a210351e1f 100644
--- a/infra/stacks/authentication-service/Pulumi.dev.yaml
+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml
@@ -23,6 +23,8 @@ config:
authentication-service:ga_measurement_id: G-52HPEL3FTV
authentication-service:ga_api_secret: ga-api-secret
authentication-service:meta_pixel_id: 639142540393286
+ authentication-service:posthog_host: https://us.i.posthog.com
+ authentication-service:posthog_api_key: posthog-api-key
authentication-service:stripe_price_id_haiku: stripe-price-id-haiku-dev
authentication-service:stripe_price_id_sonnet: stripe-price-id-sonnet-dev
authentication-service:stripe_price_id_opus: stripe-price-id-opus-dev
diff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yaml
index 8fd5ab18db..137479ba63 100644
--- a/infra/stacks/authentication-service/Pulumi.prod.yaml
+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml
@@ -23,6 +23,8 @@ config:
authentication-service:ga_measurement_id: G-52HPEL3FTV
authentication-service:ga_api_secret: ga-api-secret
authentication-service:meta_pixel_id: 639142540393286
+ authentication-service:posthog_host: https://us.i.posthog.com
+ authentication-service:posthog_api_key: posthog-api-key
authentication-service:stripe_price_id_haiku: stripe-price-id-haiku-prod
authentication-service:stripe_price_id_sonnet: stripe-price-id-sonnet-prod
authentication-service:stripe_price_id_opus: stripe-price-id-opus-prod
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.ts
index 98a70d4c48..b692b71295 100644
--- a/infra/stacks/authentication-service/index.ts
+++ b/infra/stacks/authentication-service/index.ts
@@ -162,6 +162,11 @@ const META_PIXEL_ID = config.require('meta_pixel_id');
// .getSecretVersionOutput({ secretId: config.require('meta_access_token') })
// .apply((secret) => secret.secretString);
+const POSTHOG_HOST = config.require('posthog_host');
+const POSTHOG_API_KEY: pulumi.Output<string> = aws.secretsmanager
+ .getSecretVersionOutput({ secretId: config.require('posthog_api_key') })
+ .apply((secret) => secret.secretString);
+
const secretKeyArns = [
pulumi.interpolate`${jwtSecretKeyArn}`,
pulumi.interpolate`${fusionauthApiKeySecretKeyArn}`,
@@ -368,6 +373,14 @@ const service = new AuthenticationService('authentication-service', {
name: 'META_PIXEL_ID',
value: META_PIXEL_ID,
},
+ {
+ name: 'POSTHOG_HOST',
+ value: POSTHOG_HOST,
+ },
+ {
+ name: 'POSTHOG_API_KEY',
+ value: pulumi.interpolate`${POSTHOG_API_KEY}`,
+ },
],
});
diff --git a/rust/cloud-storage/analytics_client/src/lib.rs b/rust/cloud-storage/analytics_client/src/lib.rs
index 714578c81d..e5373710de 100644
--- a/rust/cloud-storage/analytics_client/src/lib.rs
+++ b/rust/cloud-storage/analytics_client/src/lib.rs
@@ -1,11 +1,11 @@
#![deny(missing_docs)]
-//! Analytics client for tracking events to GA and Meta.
+//! Analytics client for tracking events to GA, Meta, and PostHog.
mod providers;
pub use providers::{MetaActionSource, MetaUserData};
-use providers::{GoogleAnalyticsProvider, MetaProvider};
+use providers::{GoogleAnalyticsProvider, MetaProvider, PostHogProvider};
use serde::Serialize;
use std::sync::Arc;
@@ -29,6 +29,15 @@ pub struct MetaConfig {
pub test_event_code: Option<String>,
}
+/// Configuration for PostHog.
+#[derive(Clone)]
+pub struct PostHogConfig {
+ /// PostHog project API key
+ pub api_key: String,
+ /// PostHog host
+ pub host: String,
+}
+
/// Configuration for the analytics client.
#[derive(Clone, Default)]
pub struct AnalyticsClientConfig {
@@ -36,13 +45,16 @@ pub struct AnalyticsClientConfig {
pub google_analytics: Option<GoogleAnalyticsConfig>,
/// Meta Conversions API configuration (optional)
pub meta: Option<MetaConfig>,
+ /// PostHog configuration (optional)
+ pub posthog: Option<PostHogConfig>,
}
-/// Analytics client for tracking events to GA and Meta.
+/// Analytics client for tracking events to GA, Meta, and PostHog.
#[derive(Clone)]
pub struct AnalyticsClient {
google: Option<Arc<GoogleAnalyticsProvider>>,
meta: Option<Arc<MetaProvider>>,
+ posthog: Option<Arc<PostHogProvider>>,
}
impl AnalyticsClient {
@@ -60,7 +72,15 @@ impl AnalyticsClient {
))
});
- Self { google, meta }
+ let posthog = config
+ .posthog
+ .map(|c| Arc::new(PostHogProvider::new(c.api_key, c.host)));
+
+ Self {
+ google,
+ meta,
+ posthog,
+ }
}
/// Creates a no-op analytics client (no providers configured).
@@ -68,6 +88,7 @@ impl AnalyticsClient {
Self {
google: None,
meta: None,
+ posthog: None,
}
}
@@ -118,4 +139,29 @@ impl AnalyticsClient {
Ok(())
}
+
+ /// Tracks an event to PostHog.
+ ///
+ /// Returns `Ok(())` if PostHog is not configured (no-op).
+ ///
+ /// - `distinct_id`: Unique identifier for the user (e.g., email or user ID)
+ /// - `event_name`: Name of the event (e.g., "subscription_created")
+ /// - `properties`: Additional event properties
+ #[tracing::instrument(skip(self, properties), err)]
+ pub async fn track_posthog(
+ &self,
+ distinct_id: &str,
+ event_name: &str,
+ properties: impl Serialize,
+ ) -> Result<(), reqwest::Error> {
+ if let Some(ref provider) = self.posthog {
+ provider
+ .capture(distinct_id, event_name, properties)
+ .await?;
+ } else {
+ tracing::warn!("posthog not configured")
+ }
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/analytics_client/src/providers/mod.rs b/rust/cloud-storage/analytics_client/src/providers/mod.rs
index 8e44b538e8..aafb5199a1 100644
--- a/rust/cloud-storage/analytics_client/src/providers/mod.rs
+++ b/rust/cloud-storage/analytics_client/src/providers/mod.rs
@@ -2,6 +2,8 @@
mod google_analytics;
mod meta;
+mod posthog;
pub use google_analytics::GoogleAnalyticsProvider;
pub use meta::{MetaActionSource, MetaProvider, MetaUserData};
+pub use posthog::PostHogProvider;
diff --git a/rust/cloud-storage/analytics_client/src/providers/posthog.rs b/rust/cloud-storage/analytics_client/src/providers/posthog.rs
new file mode 100644
index 0000000000..40b42b370f
--- /dev/null
+++ b/rust/cloud-storage/analytics_client/src/providers/posthog.rs
@@ -0,0 +1,58 @@
+//! PostHog analytics provider.
+
+use serde::Serialize;
+
+/// PostHog analytics provider for server-side event tracking.
+#[derive(Clone)]
+pub struct PostHogProvider {
+ client: reqwest::Client,
+ api_key: String,
+ host: String,
+}
+
+impl PostHogProvider {
+ /// Creates a new PostHog provider.
+ ///
+ /// - `api_key`: PostHog project API key
+ /// - `host`: PostHog host
+ pub fn new(api_key: String, host: String) -> Self {
+ Self {
+ client: reqwest::Client::new(),
+ api_key,
+ host,
+ }
+ }
+
+ /// Captures an event to PostHog.
+ ///
+ /// - `distinct_id`: Unique identifier for the user (e.g., email or user ID)
+ /// - `event_name`: Name of the event (e.g., "subscription_created")
+ /// - `properties`: Additional event properties
+ #[tracing::instrument(skip(self, properties), err)]
+ pub async fn capture(
+ &self,
+ distinct_id: &str,
+ event_name: &str,
+ properties: impl Serialize,
+ ) -> Result<(), reqwest::Error> {
+ let url = format!("{}/i/v0/e/", self.host.trim_end_matches('/'));
+
+ let properties = serde_json::to_value(properties).unwrap_or_default();
+
+ let payload = serde_json::json!({
+ "api_key": self.api_key,
+ "event": event_name,
+ "distinct_id": distinct_id,
+ "properties": properties,
+ });
+
+ self.client
+ .post(&url)
+ .json(&payload)
+ .send()
+ .await?
+ .error_for_status()?;
+
+ Ok(())
+ }
+}
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.rs
index 8c76ba00ff..50aa5b811a 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
@@ -453,15 +453,14 @@ fn track_stripe_subscription(
match (data.status.as_str(), data.is_new) {
("active" | "trialing", true) => {
if let Some(ref ga_client_id) = data.ga_client_id {
- match client.track_ga(ga_client_id, "purchase", &event).await {
- Ok(()) => tracing::info!("tracked GA purchase event"),
- Err(e) => tracing::warn!(error = ?e, "failed to track GA purchase event"),
- }
+ let _ = client.track_ga(ga_client_id, "purchase", &event)
+ .await
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to track GA purchase event"));
} else {
tracing::debug!("skipping GA purchase tracking: no ga_client_id");
}
- match client
+ let _ = client
.track_meta(
"Purchase",
&user_data,
@@ -470,22 +469,23 @@ fn track_stripe_subscription(
&event,
)
.await
- {
- Ok(()) => tracing::info!("tracked Meta purchase event"),
- Err(e) => tracing::warn!(error = ?e, "failed to track Meta purchase event"),
- }
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to track Meta purchase event"));
+
+ let _ = client
+ .track_posthog(&data.email, "subscription_created", &event)
+ .await
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to track PostHog subscription_created event"));
}
("canceled", _) => {
if let Some(ref ga_client_id) = data.ga_client_id {
- match client.track_ga(ga_client_id, "refund", &event).await {
- Ok(()) => tracing::info!("tracked GA refund event"),
- Err(e) => tracing::warn!(error = ?e, "failed to track GA refund event"),
- }
+ let _ = client.track_ga(ga_client_id, "refund", &event)
+ .await
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to track GA refund event"));
} else {
tracing::debug!("skipping GA refund tracking: no ga_client_id");
}
- match client
+ let _ = client
.track_meta(
"CancelSubscription",
&user_data,
@@ -494,10 +494,12 @@ fn track_stripe_subscription(
&event,
)
.await
- {
- Ok(()) => tracing::info!("tracked Meta cancel event"),
- Err(e) => tracing::warn!(error = ?e, "failed to track Meta cancel event"),
- }
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to track Meta cancel event"));
+
+ let _ = client
+ .track_posthog(&data.email, "subscription_canceled", &event)
+ .await
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to track PostHog subscription_canceled event"));
}
_ => {
tracing::debug!(status = %data.status, is_new = data.is_new, "skipping analytics tracking: unhandled status/is_new combination");
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index 3c63f57f9f..0c7996c054 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -82,6 +82,11 @@ pub struct Config {
/// Meta test event code for testing (optional)
pub meta_test_event_code: Option<String>,
+ /// PostHog API key (optional)
+ pub posthog_api_key: Option<String>,
+ /// PostHog host (optional)
+ pub posthog_host: Option<String>,
+
/// The stripe price ids
pub stripe_price_ids: StripePriceIds,
}
@@ -164,6 +169,10 @@ impl Config {
let meta_access_token = std::env::var("META_ACCESS_TOKEN").ok();
let meta_test_event_code = std::env::var("META_TEST_EVENT_CODE").ok();
+ // PostHog configuration
+ let posthog_api_key = std::env::var("POSTHOG_API_KEY").ok();
+ let posthog_host = std::env::var("POSTHOG_HOST").ok();
+
let stripe_price_ids = StripePriceIds::new()?;
Ok(Config {
@@ -194,6 +203,8 @@ impl Config {
meta_pixel_id,
meta_access_token,
meta_test_event_code,
+ posthog_api_key,
+ posthog_host,
stripe_price_ids,
})
}
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 3ee1dd3739..5fbc7c60d2 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -1,5 +1,7 @@
#![recursion_limit = "256"]
-use analytics_client::{AnalyticsClient, AnalyticsClientConfig, GoogleAnalyticsConfig, MetaConfig};
+use analytics_client::{
+ AnalyticsClient, AnalyticsClientConfig, GoogleAnalyticsConfig, MetaConfig, PostHogConfig,
+};
use anyhow::Context;
use config::{Config, Environment};
use document_storage_service_client::DocumentStorageServiceClient;
@@ -215,6 +217,16 @@ async fn main() -> anyhow::Result<()> {
test_event_code: config.meta_test_event_code.clone(),
}
}),
+ posthog: config.posthog_api_key.as_ref().map(|api_key| {
+ tracing::info!("configuring PostHog");
+ PostHogConfig {
+ api_key: api_key.clone(),
+ host: config
+ .posthog_host
+ .clone()
+ .unwrap_or_else(|| "https://us.i.posthog.com".to_string()),
+ }
+ }),
});
tracing::trace!("initialized analytics client");