Stripe is the source of truth for payments, subscriptions, renewals, refunds and failed charges. Most of those happen without the user on your website, so browser tracking can’t see them. Sending Stripe events to Mixpanel puts real billing activity next to product behavior, so you can analyze which features, channels and cohorts drive revenue and churn.
This guide covers Mixpanel’s documented webhook approach, a production-ready version of it, how to link Stripe customers to Mixpanel users, which Stripe events to keep, and the alternatives.
How the integration works
- Something happens in Stripe, such as a successful invoice payment.
- Stripe sends a webhook event (an HTTP POST with JSON) to an endpoint you control.
- Your endpoint (Mixpanel’s guide uses a Google Cloud Function; AWS Lambda or your own backend works the same way) converts the event and sends it to Mixpanel’s Import API.
Stripe’s own documentation recommends webhooks for subscriptions because most subscription activity happens asynchronously.
Step 1: Create the endpoint (Cloud Function)
In the Google Cloud console:
- Create a new Cloud Function (Cloud Run function).
- Set the trigger to HTTPS.
- Allow unauthenticated invocations, because Stripe calls it directly. (You’ll secure it with Stripe’s signature check in Step 3.)
- Choose a Python runtime.
- Copy the function URL.
Step 2: Mixpanel’s reference code
Mixpanel’s guide maps each Stripe event to a Mixpanel event like this:
| Mixpanel field | Taken from Stripe | Why |
|---|---|---|
event | type (e.g. invoice.payment_succeeded) | Event name |
$insert_id | Event id | Stripe may retry a webhook; this prevents duplicates |
time | created | When it happened in Stripe |
$device_id | data.object.customer | Groups events by Stripe customer (Simplified ID Merge) |
| Other properties | Everything in data.object | Amount, currency, status and so on |
Mixpanel’s sample code reads the project token from a token query parameter on the webhook URL and sends events to /import with strict=1. Its comment notes that projects on Original ID Merge should set distinct_id instead of $device_id.
Step 3: A production-ready version
The reference code is a minimal demo. For production, I recommend four changes:
- Verify Stripe’s signature, as Stripe’s docs advise, so only genuine Stripe events are accepted.
- Keep secrets in environment variables, not in the webhook URL.
- Attach your app’s user ID so billing events land on the same Mixpanel user as product events.
- Send only the events and fields you need, with amounts converted to normal currency units.
# main.py
import os, json
import functions_framework
import requests
import stripe
MP_TOKEN = os.environ['MIXPANEL_TOKEN']
MP_HOST = os.environ.get('MIXPANEL_HOST', 'https://api.mixpanel.com') # api-eu / api-in for other regions
WEBHOOK_SECRET = os.environ['STRIPE_WEBHOOK_SECRET']
stripe.api_key = os.environ['STRIPE_SECRET_KEY']
KEEP = {
'invoice.payment_succeeded': 'subscription_payment_succeeded',
'invoice.payment_failed': 'subscription_payment_failed',
'customer.subscription.created': 'subscription_started',
'customer.subscription.updated': 'subscription_updated',
'customer.subscription.deleted': 'subscription_canceled',
'charge.refunded': 'refund_issued',
'checkout.session.completed': 'checkout_completed',
}
@functions_framework.http
def stripe_to_mixpanel(request):
try:
event = stripe.Webhook.construct_event(
request.get_data(), request.headers.get('Stripe-Signature'), WEBHOOK_SECRET)
except Exception:
return ('invalid signature', 400)
if event['type'] not in KEEP:
return ('ignored', 200)
obj = event['data']['object']
customer_id = obj.get('customer')
user_id = None
if customer_id:
customer = stripe.Customer.retrieve(customer_id)
user_id = (customer.get('metadata') or {}).get('app_user_id')
amount = obj.get('amount_paid') or obj.get('amount_total') or obj.get('amount_refunded')
props = {
'$insert_id': event['id'],
'time': event['created'],
'stripe_event_type': event['type'],
'stripe_customer_id': customer_id,
'currency': (obj.get('currency') or '').upper(),
'amount': amount / 100 if amount is not None else None,
'status': obj.get('status'),
}
if user_id:
props['$user_id'] = user_id
elif customer_id:
props['$device_id'] = customer_id
resp = requests.post(
f'{MP_HOST}/import', params={'strict': '1'},
auth=(MP_TOKEN, ''),
headers={'Content-Type': 'application/json'},
data=json.dumps([{'event': KEEP[event['type']], 'properties': props}]))
return (resp.text, resp.status_code)
# requirements.txt
functions-framework==3.*
requests
stripe
Notes on the code:
- Amounts: Stripe expresses amounts in the smallest currency unit (cents for USD). Dividing by 100 works for most currencies, but zero-decimal currencies such as JPY don’t use subunits. Check Stripe’s currency docs and handle those separately.
- Field names differ by object: invoices use
amount_paid, Checkout Sessions useamount_total, charges useamount_refunded. Map only the objects you keep. - Plan details: for subscription events, add the price ID, product and interval from the subscription items.
- Auth: the reference uses the project token. You can also authenticate
/importwith a service account and project ID (post 31).
Step 4: Link Stripe customers to Mixpanel users
This is the step that makes the data useful. Without it, billing events sit on separate “users” keyed by Stripe customer ID.
The simplest pattern:
- When you create a Stripe customer, store your app’s user ID in the customer’s metadata, e.g.
app_user_id. - Use that same ID in Mixpanel’s
identify()on your site and app (post 2). - In the function, look up the metadata and send it as
$user_id(as above).
If you also send $device_id = Stripe customer ID and $user_id together on the first event, Simplified ID Merge links them into one identity cluster.
Step 5: Create the webhook in Stripe
- In the Stripe Dashboard, go to Developers → Webhooks (Stripe now calls these event destinations in Workbench) and add an endpoint.
- Paste your function URL.
- Select events. Mixpanel’s guide suggests selecting all events for flexibility; with the filtering code above, select the events you map (or all, and let the function ignore the rest).
- Copy the signing secret (
whsec_...) into the function’sSTRIPE_WEBHOOK_SECRETenvironment variable and redeploy.
Step 6: Test
- Use the Stripe CLI to send test events (
stripe trigger invoice.payment_succeeded) or use test mode in the Dashboard. - Check the webhook’s delivery log in Stripe for a 200 response.
- In Mixpanel’s Events view, confirm the event, amount and currency.
- Open the user’s profile and confirm billing events sit next to their product events.
Use a separate Mixpanel dev project with Stripe test mode, and the production project with live mode.
Which Stripe events to keep
| Stripe event | Suggested Mixpanel event | Use |
|---|---|---|
checkout.session.completed | checkout_completed | One-off purchases via Checkout |
customer.subscription.created | subscription_started | New subscriptions, trial starts |
invoice.payment_succeeded | subscription_payment_succeeded | Renewals and revenue |
invoice.payment_failed | subscription_payment_failed | Involuntary churn risk |
customer.subscription.updated | subscription_updated | Upgrades, downgrades, cancellations scheduled |
customer.subscription.deleted | subscription_canceled | Churn |
charge.refunded | refund_issued | Net revenue |
Renaming events to your snake_case convention keeps them consistent with the rest of your tracking plan. Keep the original stripe_event_type as a property for traceability.
Reports to build
- Revenue: property sum of
amountonsubscription_payment_succeeded(plus one-off purchases), minus refunds, with a formula (post 26). - Churn: count of
subscription_canceledby plan, or a retention report on payment events. - Failed payment recovery: funnel from
subscription_payment_failedtosubscription_payment_succeededwithin 14 days. - Revenue by acquisition source: break down revenue by first-touch UTM profile properties.
Historical data and alternatives
- Webhooks only capture events from setup onward. For history, export from Stripe (or Stripe’s Sigma or Data Pipeline to a warehouse) and load it with the Import API (post 31) or Warehouse Connectors (post 20).
- Mixpanel’s docs point to Vendo as a no-code option for Stripe purchase and subscription data.
- Workflow tools like Zapier and Pipedream offer Stripe-to-Mixpanel recipes, useful for simple cases.
- Subscription platforms such as RevenueCat (for app stores) have their own Mixpanel integrations.
Summary
Create an HTTPS endpoint, verify Stripe’s signature, map the Stripe events you need to clearly named Mixpanel events with $insert_id from the Stripe event ID, convert amounts, link customers to your app’s user ID, and send to Mixpanel’s Import API. Then test with Stripe’s CLI and build revenue and churn reports.
[Your CTA and link here.]
Sources
- Mixpanel: Stripe integration
- Stripe: Using webhooks with subscriptions
- Stripe: Check webhook signatures
- Stripe: Currencies and zero-decimal currencies
- Mixpanel API reference: Import Events
- Amplitude: Stripe source (reference for event selection)
GET EXPERT ANALYTICS HELP
Need help getting reliable answers from Mixpanel?
Tell us about your tracking, funnels, retention, or reporting challenge. Optizent can help you implement, audit, and use Mixpanel with confidence.
We will use these details to respond to your request. Please do not include passwords, account access, or customer data.
