Skip to content

PostHog Integration Plan

PostHog Integration Plan

Comprehensive analytics integration for product launches and marketing automation.

Overview

PostHog provides end-to-end product analytics across the entire Master Automation Plan (MAP) lifecycle. This document defines integration points, event schemas, and implementation details for each phase.

AttributeValue
Instancehttps://data.philoveracity.com
Project API Keyphc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ
Personal API Keyphx_58bIL8qrZmhcxQZJT9jQohpnJhhs2JQnlFHc5fcI3oh
Project ID2

Integration by MAP Phase

Phase 1: DNS (Cloudflare)

Integration Point: Post-zone creation hook

EventPropertiesTrigger
map_dns_zone_createddomain, archetype, brandAfter zone creation
map_dns_records_configureddomain, record_countAfter DNS propagation
Terminal window
# Server-side event capture after DNS setup
curl -X POST "https://data.philoveracity.com/capture/" \
-H "Content-Type: application/json" \
-d '{
"api_key": "phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ",
"event": "map_dns_zone_created",
"distinct_id": "system",
"properties": {
"domain": "example.com",
"archetype": "saas_landing",
"brand": "pvdify"
}
}'

Phase 2: Hosting (cPanel)

Integration Point: Post-account creation hook

EventPropertiesTrigger
map_hosting_account_createddomain, username, package, archetypeAfter cPanel account
map_ssl_provisioneddomain, providerAfter SSL issuance

Phase 3: Website Build (Block Assembler / WP UI AI)

Integration Point: Block Assembler CLI and WP frontend

EventPropertiesTrigger
map_page_createdarchetype, page_type, pattern_count, domainAfter page generation
map_pattern_usedpattern_name, category, archetypeWhen pattern inserted
map_intake_completedarchetype, question_count, duration_secondsAfter Q&A flow
map_site_publisheddomain, page_count, archetypeSite goes live

Frontend Tracking (WordPress sites):

<!-- Add to theme header or Block Assembler output -->
<script>
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ', {
api_host: 'https://data.philoveracity.com',
person_profiles: 'identified_only'
})
</script>

WP Block Assembler CLI Integration:

// In Block Assembler plugin - class-cli-commands.php
private function track_event($event, $properties = []) {
$payload = [
'api_key' => 'phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ',
'event' => $event,
'distinct_id' => get_current_user_id() ?: 'system',
'properties' => array_merge($properties, [
'domain' => home_url(),
'timestamp' => date('c')
])
];
wp_remote_post('https://data.philoveracity.com/capture/', [
'body' => json_encode($payload),
'headers' => ['Content-Type' => 'application/json'],
'timeout' => 5,
'blocking' => false // Non-blocking for performance
]);
}

Phase 4: Fleet Management (MainWP)

Integration Point: MainWP sync hooks

EventPropertiesTrigger
map_site_synceddomain, wp_version, plugin_count, themeAfter MainWP sync
map_updates_availabledomain, update_type, update_countUpdate detected
map_updates_applieddomain, update_type, success_count, fail_countAfter update

Phase 5: Email (Sendy)

Integration Point: Sendy API hooks + subscriber tracking

EventPropertiesTrigger
map_list_createdlist_name, brand, archetypeAfter Sendy list creation
newsletter_signupemail_hash, list_name, source, archetypeUser subscribes
email_confirmedemail_hash, list_nameDouble opt-in confirmed
campaign_sentcampaign_name, list_name, recipient_countCampaign dispatched
campaign_clickedemail_hash, campaign_name, link_urlLink clicked in email

Sendy Webhook Integration:

// Webhook receiver for Sendy events
add_action('rest_api_init', function() {
register_rest_route('posthog/v1', '/sendy-webhook', [
'methods' => 'POST',
'callback' => function($request) {
$event_map = [
'subscribe' => 'newsletter_signup',
'confirm' => 'email_confirmed',
'unsubscribe' => 'newsletter_unsubscribe'
];
$sendy_event = $request->get_param('event');
$posthog_event = $event_map[$sendy_event] ?? "sendy_{$sendy_event}";
// Forward to PostHog
wp_remote_post('https://data.philoveracity.com/capture/', [
'body' => json_encode([
'api_key' => 'phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ',
'event' => $posthog_event,
'distinct_id' => hash('sha256', $request->get_param('email')),
'properties' => $request->get_params()
]),
'headers' => ['Content-Type' => 'application/json']
]);
return ['status' => 'ok'];
},
'permission_callback' => '__return_true'
]);
});

Phase 6: Commerce (Stripe)

Integration Point: Stripe webhooks + checkout tracking

EventPropertiesTrigger
checkout_startedproduct_name, price, currency, archetypeUser clicks buy
checkout_completedproduct_name, price, currency, stripe_session_idPayment success
checkout_abandonedproduct_name, price, abandonment_stepSession expired
subscription_createdplan_name, interval, priceNew subscription
subscription_canceledplan_name, cancel_reasonSubscription ended
refund_issuedamount, reason, product_nameRefund processed

Stripe Webhook to PostHog:

// Node.js webhook handler
app.post('/stripe-webhook', async (req, res) => {
const event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
const eventMap = {
'checkout.session.completed': 'checkout_completed',
'customer.subscription.created': 'subscription_created',
'customer.subscription.deleted': 'subscription_canceled',
'charge.refunded': 'refund_issued'
};
const posthogEvent = eventMap[event.type];
if (posthogEvent) {
await posthog.capture({
distinctId: event.data.object.customer_email || event.data.object.customer,
event: posthogEvent,
properties: {
stripe_event_id: event.id,
amount: event.data.object.amount_total / 100,
currency: event.data.object.currency,
product: event.data.object.metadata?.product_name
}
});
}
res.json({ received: true });
});

Phase 7: Fulfillment (License Delivery)

Integration Point: License generation and activation

EventPropertiesTrigger
license_generatedproduct_name, license_type, validity_daysLicense created
license_deliveredproduct_name, delivery_methodSent to customer
license_activatedproduct_name, activation_count, max_activationsFirst use
first_value_momentproduct_name, time_to_value_seconds, actionUser achieves goal

Pvdify Web App Deployments

Integration Point: pvdifyd daemon, Admin UI, GitHub Actions, deployed apps

Pvdify is the Heroku-style PaaS for deploying containerized web applications. PostHog tracks the entire deployment lifecycle.

Deployment Events

EventPropertiesTrigger
pvdify_app_createdapp_name, environment, brandNew app slot created
pvdify_deploy_startedapp_name, image, release_version, environmentDeploy initiated
pvdify_deploy_completedapp_name, release_version, duration_seconds, successDeploy finished
pvdify_deploy_failedapp_name, error_type, error_messageDeploy error
pvdify_health_check_passedapp_name, release_version, response_time_msHealth OK
pvdify_health_check_failedapp_name, release_version, errorHealth failed

Release Management Events

EventPropertiesTrigger
pvdify_release_createdapp_name, version, image_sha, config_versionNew release
pvdify_rollback_initiatedapp_name, from_version, to_version, reasonRollback started
pvdify_rollback_completedapp_name, to_version, duration_secondsRollback done

Config & Scaling Events

EventPropertiesTrigger
pvdify_config_updatedapp_name, changed_vars, config_versionEnv vars changed
pvdify_secret_setapp_name, secret_name (no value!)Secret added
pvdify_process_scaledapp_name, process_type, old_count, new_countScaling
pvdify_process_restartedapp_name, process_type, reasonRestart

Domain & Routing Events

EventPropertiesTrigger
pvdify_domain_addedapp_name, domain, tunnel_routeDomain configured
pvdify_domain_removedapp_name, domainDomain removed
pvdify_tunnel_route_updatedapp_name, domain, old_port, new_portBlue-green swap

Preview Environment Events

EventPropertiesTrigger
pvdify_preview_createdapp_name, pr_number, preview_urlPR preview up
pvdify_preview_deletedapp_name, pr_number, ttl_expiredPreview cleaned

Implementation: pvdifyd Daemon

// In pvdifyd - server/services/analytics.js
const { PostHog } = require('posthog-node');
const posthog = new PostHog(
'phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ',
{ host: 'https://data.philoveracity.com' }
);
async function trackDeploy(app, release, duration, success) {
await posthog.capture({
distinctId: 'pvdifyd',
event: success ? 'pvdify_deploy_completed' : 'pvdify_deploy_failed',
properties: {
app_name: app.name,
environment: app.environment,
release_version: release.version,
image: release.image,
duration_seconds: duration,
success
}
});
}
async function trackRollback(app, fromVersion, toVersion, reason) {
await posthog.capture({
distinctId: 'pvdifyd',
event: 'pvdify_rollback_initiated',
properties: {
app_name: app.name,
from_version: fromVersion,
to_version: toVersion,
reason
}
});
}
async function trackScale(app, processType, oldCount, newCount) {
await posthog.capture({
distinctId: 'pvdifyd',
event: 'pvdify_process_scaled',
properties: {
app_name: app.name,
process_type: processType,
old_count: oldCount,
new_count: newCount
}
});
}
module.exports = { trackDeploy, trackRollback, trackScale };

Implementation: GitHub Actions

.github/workflows/deploy.yml
- name: Track Deploy to PostHog
if: always()
run: |
curl -X POST "https://data.philoveracity.com/capture/" \
-H "Content-Type: application/json" \
-d '{
"api_key": "phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ",
"event": "pvdify_deploy_${{ job.status }}",
"distinct_id": "github-actions",
"properties": {
"app_name": "${{ env.APP_NAME }}",
"release_version": "${{ github.sha }}",
"environment": "${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}",
"repo": "${{ github.repository }}",
"actor": "${{ github.actor }}",
"workflow": "${{ github.workflow }}"
}
}'

Implementation: Deployed Apps

All Pvdify-deployed apps should include PostHog for product analytics:

Terminal window
# Set PostHog env vars for every app
pvdify config:set myapp \
POSTHOG_HOST=https://data.philoveracity.com \
POSTHOG_KEY=phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ

App Initialization (Node.js):

src/lib/analytics.js
const { PostHog } = require('posthog-node');
const posthog = new PostHog(
process.env.POSTHOG_KEY,
{ host: process.env.POSTHOG_HOST }
);
// Identify user on login
function identifyUser(user) {
posthog.identify({
distinctId: user.id,
properties: {
email: user.email,
name: user.name,
plan: user.subscription?.plan,
created_at: user.createdAt
}
});
}
// Track feature usage
function trackFeature(userId, feature, properties = {}) {
posthog.capture({
distinctId: userId,
event: 'feature_used',
properties: {
feature_name: feature,
app_name: process.env.APP_NAME,
...properties
}
});
}
// Check feature flags
async function isFeatureEnabled(userId, flag) {
return await posthog.isFeatureEnabled(flag, userId);
}
module.exports = { posthog, identifyUser, trackFeature, isFeatureEnabled };

Pvdify DevOps Dashboard

Metrics:
- Deploys per day/week
- Deploy success rate (%)
- Average deploy duration
- Rollback frequency
- Apps by environment (production/staging/preview)
Key Events:
- pvdify_deploy_completed, pvdify_deploy_failed
- pvdify_rollback_initiated
- pvdify_health_check_failed
- pvdify_process_scaled

Feature Flags for Canary Deploys

Terminal window
# Create canary rollout flag
curl -X POST "https://data.philoveracity.com/api/projects/2/feature_flags/" \
-H "Authorization: Bearer phx_58bIL8qrZmhcxQZJT9jQohpnJhhs2JQnlFHc5fcI3oh" \
-H "Content-Type: application/json" \
-d '{
"key": "myapp_v2_rollout",
"name": "MyApp v2 Canary",
"active": true,
"filters": {
"groups": [
{
"properties": [{"key": "email", "value": "@philoveracity.com", "operator": "icontains"}],
"rollout_percentage": 100
},
{
"rollout_percentage": 10
}
]
}
}'

This enables:

  • 100% rollout to internal users (@philoveracity.com)
  • 10% rollout to everyone else
  • Gradually increase to 25% → 50% → 100%

Marketing Funnel Analytics

Complete Launch Funnel

┌─────────────────┐
│ Landing Page │ pageview, cta_click
│ Visit │
└────────┬────────┘
┌─────────────────┐
│ Newsletter │ newsletter_signup
│ Signup │
└────────┬────────┘
┌─────────────────┐
│ Email │ email_confirmed, campaign_clicked
│ Engagement │
└────────┬────────┘
┌─────────────────┐
│ Checkout │ checkout_started, checkout_completed
│ Conversion │
└────────┬────────┘
┌─────────────────┐
│ Product │ license_activated, first_value_moment
│ Activation │
└─────────────────┘

Key Marketing Events (All Sites)

EventPropertiesPurpose
cta_clickcta_text, cta_location, page_urlConversion tracking
form_submitform_name, form_fieldsLead generation
video_playvideo_title, video_duration, percent_watchedEngagement
pricing_viewplan_viewed, billing_periodIntent signal
demo_requestcompany_size, use_caseSales qualification

Dashboards by Archetype

saas_landing Dashboard

Metrics:
- Visitors → Signups (conversion rate)
- Signups → Trial Started (activation rate)
- Trial → Paid (conversion rate)
- MRR, Churn Rate
Events tracked:
- pageview, cta_click, signup_started, signup_completed
- trial_started, feature_used, upgrade_clicked, checkout_completed

digital_product Dashboard

Metrics:
- Visitors → Cart (browse to buy intent)
- Cart → Purchase (checkout conversion)
- Purchase → Download (delivery success)
- Refund rate
Events tracked:
- product_view, add_to_cart, checkout_started, checkout_completed
- download_started, download_completed, refund_requested

newsletter_media Dashboard

Metrics:
- Visitors → Subscribers (signup rate)
- Open rate, Click rate
- Subscriber growth (net new per week)
- Engagement score
Events tracked:
- pageview, newsletter_signup, email_confirmed
- email_opened, email_clicked, unsubscribe

Feature Flags for Launches

PostHog feature flags enable controlled rollouts and A/B testing.

Launch Feature Flags

Flag NamePurposeDefault
show_launch_bannerHero announcement bannerfalse
enable_early_accessEarly access signup formfalse
show_pricingDisplay pricing sectionfalse
checkout_enabledAllow purchasesfalse
new_onboarding_flowA/B test onboarding50%

Usage Example:

// Check feature flag before showing pricing
if (posthog.isFeatureEnabled('show_pricing')) {
document.getElementById('pricing-section').style.display = 'block';
}
// Track which variant user saw
posthog.capture('pricing_viewed', {
variant: posthog.getFeatureFlag('pricing_layout') // 'control' or 'test'
});

Implementation Checklist

Phase 3 (Website Build) - Priority 1

  • Add PostHog JS snippet to Block Assembler header pattern
  • Implement track_event() in Block Assembler CLI
  • Track map_page_created on page generation
  • Track map_pattern_used for each pattern insert
  • Create “Page Builder” dashboard in PostHog

Phase 5 (Email) - Priority 1

  • Configure Sendy webhook to PostHog endpoint
  • Track newsletter_signup on all landing pages
  • Hash emails for privacy (SHA-256)
  • Create “Email Funnel” dashboard

Phase 6 (Commerce) - Priority 1

  • Add Stripe webhook handler with PostHog forwarding
  • Track checkout_started on pricing page clicks
  • Track checkout_completed on success
  • Create “Revenue” dashboard

Pvdify Deployments - Priority 1

  • Add PostHog Node.js SDK to pvdifyd daemon
  • Track pvdify_deploy_completed and pvdify_deploy_failed events
  • Track pvdify_rollback_initiated events
  • Track pvdify_process_scaled events
  • Add GitHub Actions step to track deploys
  • Create “Pvdify DevOps” dashboard
  • Set up canary rollout feature flags

Pvdify Apps (All Deployed Apps) - Priority 1

  • Document PostHog env var setup in pvdify CLI help
  • Auto-inject POSTHOG_HOST and POSTHOG_KEY for new apps
  • Create app analytics boilerplate (Node.js, Python, Go)
  • Track feature_used events in all apps
  • Set up user identification on login

Cross-Cutting - Priority 2

  • Create archetype-specific dashboard templates
  • Set up feature flags for launch control
  • Configure email alerts for key events
  • Document event schema in this doc

API Reference

Capture Event (Server-side)

Terminal window
curl -X POST "https://data.philoveracity.com/capture/" \
-H "Content-Type: application/json" \
-d '{
"api_key": "phc_VJTJuEEcwsoV2ZWOWn7CivOsaOK92ZI9g9fynVcRoUZ",
"event": "event_name",
"distinct_id": "user_or_system_id",
"properties": {
"key": "value"
}
}'

Query Events (Admin)

Terminal window
curl -H "Authorization: Bearer phx_58bIL8qrZmhcxQZJT9jQohpnJhhs2JQnlFHc5fcI3oh" \
"https://data.philoveracity.com/api/projects/2/events/?event=checkout_completed"

Create Feature Flag (Admin)

Terminal window
curl -X POST "https://data.philoveracity.com/api/projects/2/feature_flags/" \
-H "Authorization: Bearer phx_58bIL8qrZmhcxQZJT9jQohpnJhhs2JQnlFHc5fcI3oh" \
-H "Content-Type: application/json" \
-d '{
"key": "show_launch_banner",
"name": "Launch Banner",
"active": false,
"filters": {
"groups": [{"rollout_percentage": 0}]
}
}'

Last updated: 2026-01-05