# Amplitude
Source: https://superwall.com/docs/integrations/amplitude
The Amplitude integration automatically sends Superwall subscription and payment events to your Amplitude project. Track subscription lifecycle events, analyze revenue metrics, and understand user behavior with automatic event mapping and revenue tracking.
In the **Analytics** section within **Integrations**, you can connect your Amplitude account to Superwall:

### Required fields
Fill out the following fields and **click** the **Enable Amplitude** button at the bottom right to save your changes:

* **Region:** Data residency region for your Amplitude project.
* **Api Key:** Your Amplitude API key.
* **Sandbox Api Key:** Optional API key for sandbox events (leave blank to opt out).
* **Sales Reporting:** Which revenue value to report in Amplitude. Choose between **Proceeds** (after store taxes & fees) or **Revenue**.
### Features
* **Automatic Event Mapping**: Converts Superwall events to Amplitude-friendly format
* **Revenue Tracking**: Automatic revenue attribution with LTV tracking
* **Multi-Region Support**: Works with US and EU data residency
* **Sandbox Isolation**: Separate tracking for production and sandbox events
* **Human-Readable Events**: Events prefixed with `[Superwall]` for easy identification
* **Session Tracking**: Automatic session ID generation
* **Platform Attribution**: Tracks which store (App Store, Play Store, Stripe) generated revenue
### Configuration
#### Required settings
| Field | Description | Example |
| ----------------- | ---------------------------- | --------------------------- |
| `integration_id` | Must be set to `"amplitude"` | `"amplitude"` |
| `region` | Data residency region | `"US (Default)"` or `"EU"` |
| `api_key` | Your Amplitude API key | `"abc123def456..."` |
| `sales_reporting` | Which value to report | `"Revenue"` or `"Proceeds"` |
#### Optional settings
| Field | Description | Example |
| ----------------- | ------------------------------------------------ | ------------- |
| `sandbox_api_key` | API key for sandbox events (leave blank to skip) | `"xyz789..."` |
#### Example configuration
```json
{
"integration_id": "amplitude",
"region": "US (Default)",
"api_key": "your_production_api_key_here",
"sandbox_api_key": "your_sandbox_api_key_here",
"sales_reporting": "Revenue"
}
```
### Event mapping
Superwall events are transformed into human-readable Amplitude events:
#### Event name format
All events are prefixed with `[Superwall]` followed by a descriptive name:
* Example: `[Superwall] Trial Start`
* Example: `[Superwall] Subscription Renewal`
#### Complete event mapping
| Superwall Event | Amplitude Event | Description |
| ---------------------------- | ----------------------------------------- | ------------------------- |
| `initial_purchase` + TRIAL | `[Superwall] Trial Start` | Trial begins |
| `initial_purchase` + INTRO | `[Superwall] Intro Offer Start` | Intro offer begins |
| `initial_purchase` + NORMAL | `[Superwall] Subscription Start` | Paid subscription begins |
| `renewal` + trial conversion | `[Superwall] Trial Conversion` | Trial converts to paid |
| `renewal` + INTRO | `[Superwall] Intro Offer Conversion` | Intro converts to regular |
| `renewal` + NORMAL | `[Superwall] Subscription Renewal` | Regular renewal |
| `cancellation` + TRIAL | `[Superwall] Trial Cancellation` | Trial cancelled |
| `cancellation` + INTRO | `[Superwall] Intro Offer Cancellation` | Intro cancelled |
| `cancellation` + NORMAL | `[Superwall] Subscription Cancellation` | Subscription cancelled |
| `uncancellation` + TRIAL | `[Superwall] Trial Uncancellation` | Trial reactivated |
| `uncancellation` + INTRO | `[Superwall] Intro Offer Uncancellation` | Intro reactivated |
| `uncancellation` + NORMAL | `[Superwall] Subscription Uncancellation` | Subscription reactivated |
| `expiration` + TRIAL | `[Superwall] Trial Expiration` | Trial ended |
| `expiration` + INTRO | `[Superwall] Intro Offer Expiration` | Intro ended |
| `expiration` + NORMAL | `[Superwall] Subscription Expiration` | Subscription ended |
| `billing_issue` | `[Superwall] Billing Issue` | Payment failed |
| `subscription_paused` | `[Superwall] Subscription Paused` | Subscription paused |
| `product_change` | `[Superwall] Product Change` | Plan changed |
| `non_renewing_purchase` | `[Superwall] Non-Renewing Purchase` | One-time purchase |
| Any with `price < 0` | `[Superwall] Refund` | Refund processed |
### Event properties
Every Amplitude event includes comprehensive properties:
#### Core Amplitude fields
* `user_id`: User identifier (uses `originalAppUserId` or `originalTransactionId`)
* `event_type`: Human-readable event name with `[Superwall]` prefix
* `time`: Event timestamp (milliseconds)
* `session_id`: Same as timestamp (groups related events)
* `platform`: Store name (APP\_STORE, PLAY\_STORE, STRIPE, PADDLE)
* `insert_id`: Unique event ID prefixed with `sw_`
#### Revenue fields (when applicable)
* `revenue`: Transaction amount (based on sales\_reporting setting)
* `price`: Same as revenue
* `quantity`: Always 1
* `productId`: Product identifier
* `revenueType`: Same as event type (for revenue categorization)
#### Event properties object
All Superwall webhook data fields are included:
* `id`, `name`, `cancelReason`, `exchangeRate`
* `isSmallBusiness`, `periodType`, `countryCode`
* `price`, `proceeds`, `priceInPurchasedCurrency`
* `taxPercentage`, `commissionPercentage`, `takehomePercentage`
* `offerCode`, `isFamilyShare`, `expirationAt`
* `transactionId`, `originalTransactionId`, `originalAppUserId`
* `store`, `purchasedAt`, `currencyCode`, `productId`
* `environment`, `isTrialConversion`, `newProductId`
* `bundleId`, `ts`
### Revenue tracking
#### Automatic revenue attribution
Revenue is automatically tracked for events with non-zero amounts:
* **Positive revenue**: Purchases, renewals, conversions
* **Negative revenue**: Refunds (automatically deducted)
* **Zero revenue**: Cancellations, expirations, billing issues
#### Revenue reporting options
The `sales_reporting` setting determines which value is used:
| Setting | Value Used | Description |
| ------------ | ---------- | ------------------------------- |
| `"Revenue"` | `price` | Gross revenue before store fees |
| `"Proceeds"` | `proceeds` | Net revenue after store fees |
#### Revenue examples
**Initial Purchase ($9.99):**
```json
{
"event_type": "[Superwall] Subscription Start",
"revenue": 9.99,
"price": 9.99,
"productId": "com.example.premium",
"revenueType": "[Superwall] Subscription Start"
}
```
**Refund (-$9.99):**
```json
{
"event_type": "[Superwall] Refund",
"revenue": -9.99,
"price": -9.99,
"productId": "com.example.premium",
"revenueType": "[Superwall] Refund"
}
```
### User identification
The integration uses this hierarchy for user identification:
1. **Primary**: `originalAppUserId` (if available)
2. **Fallback**: `originalTransactionId` (always present)
This ensures consistent user tracking across:
* Multiple devices
* App reinstalls
* Legacy users without app user IDs
#### Platform tracking
The `platform` field identifies the payment source:
* `APP_STORE`: iOS App Store
* `PLAY_STORE`: Google Play Store
* `STRIPE`: Stripe web payments
* `PADDLE`: Paddle payments (coming soon)
This helps analyze:
* Revenue by platform
* Platform-specific retention
* Cross-platform users
### Sandbox handling
#### With sandbox API key
If `sandbox_api_key` is configured:
* Production events → Production project
* Sandbox events → Sandbox project
#### Without sandbox API key
If `sandbox_api_key` is empty:
* Production events → Production project
* Sandbox events → **Skipped** (not sent)
This prevents test data from polluting production analytics.
### Data residency
Amplitude supports two data residency regions:
| Region | API Endpoint | Use Case |
| -------------- | -------------------- | --------------- |
| `US (Default)` | api2.amplitude.com | Global, default |
| `EU` | api.eu.amplitude.com | GDPR compliance |
Choose based on:
* Your data privacy requirements
* User location
* Compliance needs
### Session management
Sessions are automatically managed:
* `session_id` = Event timestamp
* Groups rapid events together
* New session for each subscription action
* Helps track user journey
### Testing the integration
#### 1. Trigger sandbox events
* iOS: Use TestFlight with a sandbox Apple ID. StoreKit Configuration files do not generate App Store Server Notifications, so webhooks and downstream integrations won't fire.
* Google Play: Use license test accounts to perform sandbox purchases.
* Stripe: Use Stripe Test Mode to create sandbox transactions.
#### 2. Verify in Amplitude
Check your Amplitude project:
1. **User Lookup**: Find test user by ID
2. **Event Stream**: Verify events arriving
3. **Revenue Chart**: Confirm revenue tracking
4. **User Properties**: Check LTV calculation
#### 3. Test different scenarios
* Purchase event → Positive revenue
* Refund event → Negative revenue
* Cancellation → No revenue
* Trial start → Event without revenue
### Best practices
1. **Consistent User IDs**: Send user IDs to app stores for better tracking
2. **Separate Environments**: Use sandbox API key for testing
3. **Revenue Model**: Choose gross vs net consistently
4. **Event Naming**: Use `[Superwall]` prefix to identify source
5. **Platform Analysis**: Segment by platform for insights
6. **Cohort Analysis**: Use trial conversion events for cohorts
### Common use cases
#### Revenue analytics
```
Events: [Superwall] Subscription Start, [Superwall] Subscription Renewal
Metric: Sum of revenue
Segment by: platform, productId, countryCode
```
#### Conversion funnel
```
1. [Superwall] Trial Start
2. [Superwall] Trial Conversion
Conversion Rate: Step 2 / Step 1
```
#### Churn analysis
```
Events: [Superwall] Subscription Cancellation
Segment by: cancelReason, periodType, price tier
```
#### LTV calculation
```
Revenue Events: All [Superwall] events with revenue > 0
Group by: user_id
Calculate: Sum of revenue per user
```
### Troubleshooting
#### Events not appearing
1. **Check API Key**: Verify key is correct for your project
2. **Check Region**: Ensure region matches your Amplitude project
3. **Check Environment**: Sandbox events need sandbox API key
4. **Check User ID**: Must have valid identifier
#### Revenue not tracking
1. **Check Amount**: Only non-zero amounts create revenue
2. **Check Event Type**: Revenue fields only for purchase/renewal events
3. **Check Settings**: Verify Revenue vs Proceeds selection
4. **Check Refunds**: Negative amounts should decrease revenue
#### Duplicate events
The integration uses `insert_id` to prevent duplicates:
* Format: `sw_eventId-eventName`
* Amplitude automatically deduplicates by `insert_id`
#### User attribution issues
1. **Check User ID**: Verify originalAppUserId is being sent
2. **Check Fallback**: originalTransactionId should always exist
3. **Platform Mismatch**: Ensure platform field is correct
### Rate limits
Amplitude HTTP API v2 limits:
* **Events per batch**: 1000 (we send 1 at a time)
* **Request size**: 1MB (well within limit)
* **Rate limit**: 1000 events/second per device
* **Daily limit**: Based on your plan
### Integration with Amplitude features
#### User properties
While this integration sends events, consider:
* Setting user properties separately
* Using Identify API for user traits
* Enriching profiles with app data
#### Revenue verification
Amplitude's revenue verification requires:
* Receipt data (not included in webhooks)
* Direct integration with app stores
* This integration complements but doesn't replace revenue verification
#### Predictive analytics
Use Superwall events for:
* Churn prediction models
* LTV forecasting
* Conversion probability scoring
### Data privacy
* **User IDs**: Pseudonymous by default
* **GDPR**: Use EU region for European users
* **Data Retention**: Follows Amplitude project settings
* **Deletion**: Handle via Amplitude's User Privacy API
* **PII**: Avoid sending PII in event properties
---
# Apple Search Ads
Source: https://superwall.com/docs/integrations/apple-search-ads
Integrate Apple Search Ads with Superwall. View details on users acquired via search ads, visualize conversions from Apple Search Ads in charts, and create powerful campaign filters to target users using search ad data. Search ad integration requires 3.12.0 of the Superwall SDK or higher.
In the **Apple Search Ads** section within **Integrations**, you can the enable Apple Search Ads integration with Superwall:

Apple offers two different search ad services, "Basic" and "Advanced" tiers. Superwall supports
both of them, though more data is available with the Advanced ads.
### Basic search ads setup
If you're only using basic search ads, **click** the toggle next to **Basic Apple Search Ads** to enable the integration:

That's it, you're all set. With basic Apple Search Ads enabled, you'll be to see users acquired via search ads in the [users page](/overview-users).
To see what you can do with advanced search ads data, skip down to the [use cases](#use-cases) section.
### Advanced search ads setup
Advanced search ads takes a few more steps since it requires the [Campaign Management API](https://searchads.apple.com/help/campaigns/0022-use-the-campaign-management-api). The overview is as follows, with more details about each step below them:
* First, you'll need to create a user in Apple Search Ads **using a different Apple Account** than your primary Apple Account.
* This new user will need to be set up with either the API Account Manager or API Account Read Only role.
* Then, you'll generate three things by pasting in a public key from Superwall: a client ID, team ID and key ID.
* Finally, you'll enter those three values into Superwall.
**Step One: Invite a new user**
1. Go to [searchads.apple.com](https://searchads.apple.com) and click **Sign In -> Advanced**.

2. Locate your account name in the top right corner and click **Account Name -> Settings**.

3. Under User Management, click **Invite Users**.

4. Grant the user appropriate permissions and enter in the rest of the details. The email address here is the one you'll want to use to create a new user in Apple Search Ads:

**Step Two: Accept the invitation**
Open the email and follow Apple's instructions to set up a new user with Apple Search ads. The email will look similar to this:

Once you've accepted the invitation using the invited Apple Account:
1. Once again, go to [searchads.apple.com](https://searchads.apple.com) and click **Sign In -> Advanced**.

2. Locate your account name in the top right corner and click **Account Name -> Settings**.

3. Over in Superwall, go to the **Settings -> Apple Search Ads -> click copy** under the public key:

4. Back in Apple Search Ads, paste the public key under **Public Key** and click **Generate API Client**:

**Step Three: Generate the client ID, team ID and key ID**
Now, you should see three values that have been generated by Apple Search Ads, a client ID, team ID and key ID.
1. Copy each generated value.

2. In Superwall, paste each value in and click "Update ASA Configuration."

3. Finally, click on "Check Configuration" and confirm everything is set up properly.

### Use cases
Once you've enabled Apple Search Ads, you can use the data in a few ways. First, users who've been acquired from a search ad will display that information in the users page under "Apple Search Ads." This is available with either the basic or advanced search ads. This can be useful for understanding the quality of users acquired from search ads.
If you're using advanced search ads, you get significantly more capabilities:
* You can leverage search ad data in your campaigns. This opens up the ability to do things like showing a specific paywall to a user who was acquired via a search ad, tailor messaging from the keyword that was used, and more.
* You can view search ads data in charts, breaking down metrics by campaign name and more.
#### Viewing users acquired via Apple Search Ads
If any user was acquired via a search ad, you'll see that data in the [users page](/overview-users). This can be useful for understanding the quality of users acquired from search ads:

Here's a breakdown of the attributes you'll see:
| Attribute | Example | Description |
| ----------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Ad Group Id | 1684936422 | The identifier for the ad group. Use Get Ad Group-Level Reports to correlate your attribution response by adGroupId. |
| Ad Group Name | Primary Ad Group | The name of the ad group for organizational and reporting purposes. |
| Ad Id | -1 | The identifier representing the assignment relationship between an ad object and an ad group. Applies to devices running iOS 15.2 and later. |
| Attribution | true | A Boolean value indicating if the attribution was successful. Returns true if a user clicks an ad up to 30 days before downloading your app. |
| Bid Amount | 0.25 | The cost-per-click (CPC) bid amount placed for this ad group. |
| Bid Currency | GBP | The currency used for the bid amount. |
| Campaign Id | 1633810596 | The unique identifier for the campaign. Use Get Campaign-Level Reports to correlate your attribution response by campaignId. |
| Campaign Name | Primary Campaign (US) | The name of the campaign, useful for tracking and organizational purposes. |
| Conversion Type | Download | The type of conversion, either Download or Redownload. |
| Country Or Region | US | The country or region for the campaign. |
| Keyword Id | 1685193881 | The identifier for the keyword. |
| Keyword Name | baskeball app | The specific keyword that triggered the ad. |
| Match Type | EXACT | The keyword matching type used to trigger the ad (e.g., EXACT, BROAD, or PHRASE). |
| Org Id | 3621140 | The identifier of the organization that owns the campaign. This is the same as your account in the Apple Search Ads UI. |
#### Using search ad data in campaigns
Using the table above, you can turn around and use any of those values to create [campaign filters](/campaigns-audience#filters):

There is a delay from the moment a user downloads your app via a search ad to the time that event
is sent to Superwall from Apple's servers. For that reason, using search ad data as a filter on
events like an app's launch is discouraged.
#### Charts
Use data from Apple Search Ads in our [charts](/charts) as a breakdown and filter:

Apple Search Ads data can be used in the following charts:
* **Proceeds**
* **Sales**
* **Conversions**
* **New Subscriptions**
* **New Trials**
* **Trial Conversions**
* **Refund Rate**
As far as search ads data, you can create breakdowns using the following:
* **Ad Group Name**
* **Campaign Name**
* **Keywords Match Name**
* **Match Type**
Some common use cases here are:
* Attributing new trials from a search campaign.
* Seeing which keywords generate the most revenue.
* Understanding the quality of users acquired from a search ad.
* etc.
---
# Integrations
Source: https://superwall.com/docs/integrations/index
Use webhooks to get real-time notifications about your app's subscription and payment events. Integrate Superwall with other services.
The integrations page is where you can manage your webhooks and other integrations with Superwall:

## Webhooks
Superwall sends webhooks to notify your application about important subscription and payment events in real-time. These webhooks are designed to closely match App Store and other revenue provider events, minimizing migration difficulty.
**Important Design Principle**: Webhook events are structured so that summing `proceeds` or `price` across all events (without filtering) accurately represents total revenue net of refunds. To calculate gross revenue, filter out events with negative proceeds.
### Webhook Payload Structure
Every webhook sent by Superwall contains the following structure:
```json
{
"object": "event",
"type": "renewal",
"projectId": 3827,
"applicationId": 1,
"timestamp": 1754067715103,
"data": {
"id": "42fc6339-dc28-470b-a0fa-0d13c92d8b61:renewal",
"name": "renewal",
"cancelReason": null,
"exchangeRate": 1.0,
"isSmallBusiness": false,
"periodType": "NORMAL",
"countryCode": "US",
"price": 9.99,
"proceeds": 6.99,
"priceInPurchasedCurrency": 9.99,
"taxPercentage": 0,
"commissionPercentage": 0.3,
"takehomePercentage": 0.7,
"offerCode": null,
"isFamilyShare": false,
"expirationAt": 1756659704000,
"transactionId": "700002054157982",
"originalTransactionId": "700002050981465",
"originalAppUserId": "$SuperwallAlias:7152E89E-60A6-4B2E-9C67-D7ED8F5BE372",
"store": "APP_STORE",
"purchasedAt": 1754067704000,
"currencyCode": "USD",
"productId": "com.example.premium.monthly",
"environment": "PRODUCTION",
"isTrialConversion": false,
"newProductId": null,
"bundleId": "com.example.app",
"ts": 1754067710106
}
}
```
### Webhook Payload Fields
| Field | Type | Description |
| --------------- | ------ | --------------------------------------------------------------------- |
| `object` | string | Always "event" |
| `type` | string | The event type (e.g., "initial\_purchase", "renewal", "cancellation") |
| `projectId` | number | Your Superwall project ID |
| `applicationId` | number | Your Superwall application ID |
| `timestamp` | number | Event timestamp in milliseconds since epoch |
| `data` | object | Event-specific data (see below) |
## Event Data Object
The `data` field contains detailed information about the subscription or payment event:
### Event Data Fields
| Field | Type | Description |
| -------------------------- | ----------------- | --------------------------------------------------------------------------------------------- |
| `id` | string | Unique identifier for this event |
| `name` | string | Event name (see [Event Names](#event-names)) |
| `cancelReason` | string or null | Reason for cancellation (see [Cancel Reasons](#cancelexpiration-reasons)) |
| `exchangeRate` | number | Exchange rate used to convert to USD |
| `isSmallBusiness` | boolean | Small business program participant |
| `periodType` | string | Period type: `TRIAL`, `INTRO`, or `NORMAL` |
| `countryCode` | string | ISO country code (e.g., "US") |
| `price` | number | Transaction price in USD (negative for refunds) |
| `proceeds` | number | Net proceeds in USD after taxes and fees |
| `priceInPurchasedCurrency` | number | Price in original currency |
| `taxPercentage` | number or null | Tax percentage applied |
| `commissionPercentage` | number | Store commission percentage |
| `takehomePercentage` | number | Your percentage after commission |
| `offerCode` | string or null | Promotional offer code used |
| `isFamilyShare` | boolean | Family sharing purchase |
| `expirationAt` | number or null | Expiration timestamp (milliseconds) |
| `transactionId` | string | Current transaction ID |
| `originalTransactionId` | string | Original transaction ID (subscription ID) |
| `originalAppUserId` | string or null | Original app user ID — requires SDK v4.5.2+ (see [details](#understanding-originalappuserid)) |
| `store` | string | Store: `APP_STORE`, `PLAY_STORE`, `STRIPE`, or `PADDLE` (see note below) |
| `purchasedAt` | number | Purchase timestamp (milliseconds) |
| `currencyCode` | string | ISO currency code for priceInPurchasedCurrency |
| `productId` | string | Product identifier |
| `environment` | string | `PRODUCTION` or `SANDBOX` |
| `isTrialConversion` | boolean | Trial to paid conversion |
| `newProductId` | string or null | New product ID (for product changes) |
| `bundleId` | string | App bundle identifier |
| `ts` | number | Event timestamp (milliseconds) |
| `expirationReason` | string (optional) | Reason for expiration (see [Cancel Reasons](#cancelexpiration-reasons)) |
| `checkoutContext` | object (optional) | Stripe-specific checkout context |
**Note on Store field:** iOS and Android apps can receive events from any payment provider. For example, an iOS app can receive `STRIPE` or `PADDLE` events when users purchase through Superwall's App2Web features, which allow web-based checkout flows within mobile apps. The `store` field indicates where the payment was processed, not which platform the app runs on.
## Event Names
| Event Name | Value | Description |
| --------------------- | ----------------------- | ----------------------------------- |
| Initial Purchase | `initial_purchase` | First-time subscription or purchase |
| Renewal | `renewal` | Subscription renewal |
| Cancellation | `cancellation` | Subscription cancelled |
| Uncancellation | `uncancellation` | Subscription reactivated |
| Expiration | `expiration` | Subscription expired |
| Billing Issue | `billing_issue` | Payment processing failed |
| Product Change | `product_change` | User changed subscription tier |
| Subscription Paused | `subscription_paused` | Subscription temporarily paused |
| Non-Renewing Purchase | `non_renewing_purchase` | One-time purchase |
## Period Types
| Period Type | Value | Description |
| ----------- | -------- | ------------------------------------------- |
| Trial | `TRIAL` | Free trial period |
| Intro | `INTRO` | Introductory offer period (discounted rate) |
| Normal | `NORMAL` | Regular subscription period (full price) |
## Stores
| Store | Value | Description |
| ---------- | ------------ | ----------------------------- |
| App Store | `APP_STORE` | Apple App Store |
| Play Store | `PLAY_STORE` | Google Play Store |
| Stripe | `STRIPE` | Stripe payments |
| Paddle | `PADDLE` | Paddle payments (coming soon) |
## Environments
| Environment | Value | Description |
| ----------- | ------------ | ------------------------------------- |
| Production | `PRODUCTION` | Live production transactions |
| Sandbox | `SANDBOX` | Sandbox transactions (not real money) |
## Cancel/Expiration Reasons
| Reason | Value | Description |
| ------------------- | --------------------- | ----------------------------- |
| Billing Error | `BILLING_ERROR` | Payment method failed |
| Customer Support | `CUSTOMER_SUPPORT` | Cancelled via support |
| Unsubscribe | `UNSUBSCRIBE` | User-initiated cancellation |
| Price Increase | `PRICE_INCREASE` | Cancelled due to price change |
| Developer Initiated | `DEVELOPER_INITIATED` | Cancelled programmatically |
| Unknown | `UNKNOWN` | Reason not specified |
## Common Use Cases
### Detecting Trial Starts
```javascript
if (
event.data.periodType === "TRIAL" &&
event.data.name === "initial_purchase"
) {
// New trial started
}
```
### Detecting Trial Conversions
```javascript
if (
event.data.name === "renewal" &&
(event.data.isTrialConversion ||
event.data.periodType === "TRIAL" ||
event.data.periodType === "INTRO")
) {
// Trial or intro offer converted to paid subscription
}
```
### Detecting Trial Cancellations
```javascript
if (event.data.periodType === "TRIAL" && event.data.name === "cancellation") {
// Trial cancelled
}
```
### Detecting Trial Uncancellations (Reactivations)
```javascript
if (event.data.periodType === "TRIAL" && event.data.name === "uncancellation") {
// Trial reactivated after cancellation
}
```
### Detecting Trial Expirations
```javascript
if (event.data.periodType === "TRIAL" && event.data.name === "expiration") {
// Trial expired
}
```
### Detecting Intro Offer Starts
```javascript
if (
event.data.periodType === "INTRO" &&
event.data.name === "initial_purchase"
) {
// Intro offer started
}
```
### Detecting Intro Offer Cancellations
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "cancellation") {
// Intro offer cancelled
}
```
### Detecting Intro Offer Uncancellations
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "uncancellation") {
// Intro offer reactivated
}
```
### Detecting Intro Offer Expirations
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "expiration") {
// Intro offer expired
}
```
### Detecting Intro Offer Conversions
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "renewal") {
// Intro offer converted to regular subscription
}
```
### Detecting Subscription Starts
```javascript
if (
event.data.periodType === "NORMAL" &&
event.data.name === "initial_purchase"
) {
// New paid subscription started
}
```
### Detecting Renewals
```javascript
if (
event.data.name === "renewal" &&
event.data.periodType === "NORMAL" &&
!event.data.isTrialConversion
) {
// Regular subscription renewal
}
```
### Detecting Refunds
```javascript
if (event.data.price < 0) {
// Refund processed
const refundAmount = Math.abs(event.data.price);
}
```
### Detecting Cancellations
```javascript
if (event.data.name === "cancellation") {
// Subscription cancelled
// Check cancelReason for details
const reason = event.data.cancelReason;
}
```
### Detecting Subscription Expirations
```javascript
if (event.data.name === "expiration") {
// Subscription expired
// Check expirationReason for details
}
```
### Detecting Billing Issues
```javascript
if (event.data.name === "billing_issue") {
// Payment failed - subscription at risk
}
```
### Detecting Subscription Pauses
```javascript
if (event.data.name === "subscription_paused") {
// Subscription has been paused
}
```
### Detecting Product Changes
```javascript
if (event.data.name === "product_change") {
// User changed subscription plan
const oldProduct = event.data.productId;
const newProduct = event.data.newProductId;
}
```
### Detecting Subscription Reactivations
```javascript
if (event.data.name === "uncancellation") {
// Previously cancelled subscription was reactivated
}
```
### Detecting Non-Renewing Purchases
```javascript
if (event.data.name === "non_renewing_purchase") {
// One-time purchase completed
}
```
### Detecting Revenue Events
```javascript
if (event.data.price !== 0 || event.data.name === "non_renewing_purchase") {
// This event involves revenue (positive or negative)
}
```
## Revenue Calculation
### Total Net Revenue (Including Refunds)
```javascript
// Sum all proceeds - automatically accounts for refunds
const netRevenue = events.reduce((sum, event) => sum + event.data.proceeds, 0);
```
### Gross Revenue (Excluding Refunds)
```javascript
// Only sum positive proceeds
const grossRevenue = events.reduce(
(sum, event) => (event.data.proceeds > 0 ? sum + event.data.proceeds : sum),
0
);
```
### Refund Total
```javascript
// Sum negative proceeds
const refunds = events.reduce(
(sum, event) =>
event.data.proceeds < 0 ? sum + Math.abs(event.data.proceeds) : sum,
0
);
```
### Revenue by Product
```javascript
const revenueByProduct = {};
events.forEach((event) => {
const productId = event.data.productId;
if (!revenueByProduct[productId]) {
revenueByProduct[productId] = 0;
}
revenueByProduct[productId] += event.data.proceeds;
});
```
## Testing Webhooks
To test webhooks, trigger real events in sandbox:
* iOS: Use TestFlight with a sandbox Apple ID (StoreKit Configuration files do not trigger webhooks).
* Google Play: Use license test accounts for sandbox purchases.
* Stripe: Use Stripe Test Mode to create sandbox transactions.
Note: We do not support sending arbitrary "test" webhooks.
## Best Practices
1. **Handle duplicate events** - Use `event.id` for idempotency
2. **Process webhooks asynchronously** - Return 200 immediately, then process
3. **Store raw webhook data** for debugging and reconciliation
4. **Handle all event types** - Even if you don't process them immediately
5. **Monitor webhook failures** - Implement retry logic for critical events
6. **Use timestamps** - All timestamps are in milliseconds since epoch
## Store-Specific Behaviors
### Commission Rates by Store
**APP\_STORE:**
* Standard rate: 30%
* Small Business Program rate: 15% (for eligible developers)
* Clean, predictable commission structure
**PLAY\_STORE:**
* Variable rates from 11.8% to 15%
* Most common rate: 15%
* Rates can vary based on region and other factors
**STRIPE:**
* Variable rates from 0% to \~7.2%
* Generally lower than mobile app stores
* Depends on Stripe pricing plan and transaction type
### Price = 0 Events
Events commonly have `price = 0` for non-revenue scenarios:
* `billing_issue` - Payment failed, no money collected
* `cancellation` - Subscription cancelled, no charge
* `expiration` - Subscription expired, no charge
* `uncancellation` - Reactivation, no immediate charge
* `product_change` - Plan change notification
* `subscription_paused` - Pause event, no charge
Revenue events (initial\_purchase, renewal, non\_renewing\_purchase) typically have non-zero prices unless:
* Family sharing scenario (some cases)
* Special promotional offers
* Test transactions
### Cancel/Expiration Reasons by Store
**APP\_STORE:**
* `CUSTOMER_SUPPORT` - Cancelled via Apple support
* `UNSUBSCRIBE` - User-initiated cancellation
* `BILLING_ERROR` - Payment failure
**PLAY\_STORE:**
* All APP\_STORE reasons plus:
* `UNKNOWN` - Reason not specified or unavailable
**STRIPE:**
* `UNKNOWN` - Stripe typically doesn't provide detailed cancellation reasons
### Trial Conversions
**Expected behavior:** `isTrialConversion` should only be `true` for `renewal` events
### Offer Codes Support
| Store | Support | Notes |
| ----------- | --------------- | -------------------------------------------------------------- |
| APP\_STORE | ✅ Supported | Rarely used (1.3% of events), typically for win-back campaigns |
| PLAY\_STORE | ✅ Supported | Heavily used (72.1% of events), complex promotional system |
| STRIPE | ❌ Not supported | Offer codes not available in webhook data |
| PADDLE | 🔜 Coming soon | Support planned |
### Environment Field
All stores support both PRODUCTION and SANDBOX environments:
* **PRODUCTION**: Live, real-money transactions
* **SANDBOX**: Test transactions (TestFlight on iOS, test mode on Stripe, test purchases on Play Store)
The environment field helps you filter out test transactions from production analytics.
## Store Event Compatibility Matrix
Not all events are available for all stores. This table shows which events you can expect from each store based on real webhook data:
### Event Support by Store
| Event Name | APP\_STORE | PLAY\_STORE | STRIPE | PADDLE |
| ----------------------- | ---------- | ----------- | ------ | ------ |
| `billing_issue` | ✅ | ✅ | ✅ | 🔜 |
| `cancellation` | ✅ | ✅ | ✅ | 🔜 |
| `expiration` | ✅ | ✅ | ✅ | 🔜 |
| `initial_purchase` | ✅ | ✅ | ✅ | 🔜 |
| `non_renewing_purchase` | ✅ | ✅ | ❌ | 🔜 |
| `product_change` | ✅ | ✅ | ❌ | 🔜 |
| `renewal` | ✅ | ✅ | ✅ | 🔜 |
| `subscription_paused` | ❌ | ✅ | ❌ | 🔜 |
| `uncancellation` | ✅ | ✅ | ✅ | 🔜 |
✅ = Supported | ❌ = Not supported | 🔜 = Coming soon
### Period Type Availability by Store
Different stores support different period types for events:
#### APP\_STORE
* Supports all period types (TRIAL, INTRO, NORMAL) for most events
* `non_renewing_purchase` only occurs with NORMAL period type
#### PLAY\_STORE
* Supports all period types (TRIAL, INTRO, NORMAL) for most events
* `renewal` only occurs with NORMAL period type
* `subscription_paused` only occurs with INTRO and NORMAL period types
* **Unique**: Only store that supports `subscription_paused` events
#### STRIPE
* Limited period type support compared to mobile app stores
* No INTRO period type support observed
* `expiration` and `renewal` only occur with NORMAL period type
* Does not support `non_renewing_purchase` or `product_change` events
#### PADDLE
* Coming soon - full support planned!
### Store-Specific Considerations
**Universal Events** (available across APP\_STORE, PLAY\_STORE, and STRIPE):
* `billing_issue`
* `cancellation`
* `expiration`
* `initial_purchase`
* `renewal`
* `uncancellation`
**Store-Specific Events**:
* `subscription_paused` - Only available from PLAY\_STORE
* `non_renewing_purchase` - Not available from STRIPE
* `product_change` - Not available from STRIPE
### Understanding originalAppUserId
The `originalAppUserId` field represents the first app user ID associated with a subscription. This field has specific behavior depending on your integration:
This field is only set correctly for events generated by users on SDK v4.5.2+.
Events from older SDK versions may omit this field or populate it inconsistently.
### Key Points:
* **What it represents**: The first user ID we saw associated with this subscription (originalTransactionId)
* **Cross-account subscriptions**: Since subscriptions are tied to Apple/Google accounts (not app accounts), users can create multiple accounts in your app while using the same subscription
* **We only store the first one**: If a user creates multiple accounts, we only track the original user ID
### When this field is populated:
* **iOS/App Store**:
* If your user ID has been sent to the stores on-device (via StoreKit)
* If your user IDs are UUIDv4 format
* This field will be consistently present for these cases
* **Stripe**: Always populated (we create one for you if not provided)
* **Play Store**: Depends on the integration and user tracking
### When this field is null:
* **Legacy users**: Users on old SDK versions
* **Pre-Superwall purchases**: Users who purchased before integrating Superwall
* **No user ID sent**: If user ID was never sent to the store
### Understanding originalTransactionId
The `originalTransactionId` is Apple's terminology that acts like a subscription ID. For simplicity and consistency with iOS and other revenue tracking platforms, we use this nomenclature and populate it accordingly for all platforms (Play Store, Stripe, Paddle, etc.).
* **One per subscription group**: Each user subscription gets one `originalTransactionId`
* **Persists across renewals**: The same `originalTransactionId` is used for all renewals in that subscription
* **Multiple IDs per user**: A single user can have multiple `originalTransactionId` if they:
* Subscribe to products in different subscription groups
* Let a subscription fully expire and re-subscribe later
* **Cross-platform consistency**: While originally an Apple concept, we generate and maintain equivalent IDs for all payment providers to ensure consistent subscription tracking
### Notes
* **Currency handling**:
* `price` and `proceeds` are always in USD
* `priceInPurchasedCurrency` is in the currency specified by `currencyCode`
* `exchangeRate` was used to convert from original currency to USD
* **Family Sharing** (App Store only):
* When `isFamilyShare` is true with `price > 0`: These are events for the **family organizer** who pays for the subscription (initial\_purchase, renewal, non\_renewing\_purchase)
* When `isFamilyShare` is true with `price = 0`: These are events for **family members** who use the shared subscription without paying (renewal, uncancellation, billing\_issue, etc.)
* **Refunds**: Negative values in `price`, `proceeds`, or `priceInPurchasedCurrency` indicate refunds
* **Transaction IDs**:
* `transactionId`: Unique ID for this specific transaction
* `originalTransactionId`: Subscription ID (first transaction in the subscription group)
* Commission and tax percentages help you understand the revenue breakdown
* **Timestamps**:
* `timestamp` (root level): When the webhook was created
* `ts` (in data): When the actual event occurred
* `purchasedAt`: When the transaction was originally purchased
## Integrations
Currently, we support the following integrations:
* **Mixpanel**: Track events and user properties in Mixpanel.
* **Slack**: Send notifications to Slack channels.
* **Amplitude**: Product analytics for your app.
To set up any of these, click on them and fill in the required fields:

Once you've done that, **click** the **Enable** button at the bottom right to save your changes.
### Mixpanel Integration - Required Fields
The following fields are required to configure the Mixpanel integration:
#### Region \*
* **Description**: Data residency region for your Mixpanel project
* **Type**: Dropdown selection
* **Required**: Yes
#### Project Token \*
* **Description**: Your Mixpanel project token
* **Type**: Text input
* **Required**: Yes
* **Location**: Mixpanel → Settings → Project Settings → Project Token
#### Total Spend Property \*
* **Description**: The name of the user property to track cumulative spend
* **Type**: Text input
* **Required**: Yes
#### Sales Reporting \*
* **Description**: Whether to report Proceeds after store taxes & fees or Revenue
* **Type**: Dropdown selection
* **Required**: Yes
* **Options**:
* Proceeds (after store taxes & fees)
* Revenue
### Optional Configuration
#### Sandbox Project Token
* **Description**: Optional project token for sandbox events
* **Type**: Text input
* **Required**: No
* **Note**: Leave blank to opt out of sandbox event tracking
### Slack Integration - Required Fields
The following fields are required to configure the Slack integration:
#### Required Configuration
**Webhook Url** \*
* **Description**: Your Slack webhook URL for sending messages to a channel
* **Type**: Text input
* **Required**: Yes
#### Optional Configuration
**Include Sandbox**
* **Description**: Whether to include sandbox events in Slack notifications
* **Type**: Dropdown selection
* **Required**: No
**Event Type**
* **Description**: Type of events to send: revenue only or all lifecycle (includes trials, cancellations)
* **Type**: Dropdown selection
* **Required**: No
* **Options**:
* Revenue only
* All lifecycle (includes trials, cancellations)
### Amplitude Integration - Required Fields
The following fields are required to configure the Amplitude integration:
#### Required Configuration
**Region** \*
* **Description**: Data residency region for your Amplitude project
* **Type**: Dropdown selection
* **Required**: Yes
**Api Key** \*
* **Description**: Your Amplitude API key
* **Type**: Text input
* **Required**: Yes
**Sales Reporting** \*
* **Description**: Which revenue value to report in Amplitude
* **Type**: Dropdown selection
* **Required**: Yes
#### Optional Configuration
**Sandbox Api Key**
* **Description**: Optional API key for sandbox events
* **Type**: Text input
* **Required**: No
* **Note**: Leave blank to opt out of sandbox event tracking
---
# Mixpanel
Source: https://superwall.com/docs/integrations/mixpanel
The Mixpanel integration allows you to automatically send Superwall subscription and payment events to your Mixpanel project.
In the **Analytics** section within **Integrations**, you can connect your Mixpanel account to Superwall:

This integration provides two-way data flow:
1. **Event Tracking**: Sends detailed subscription lifecycle events to Mixpanel.
2. **User Profile Updates**: Updates user profiles with revenue data and transaction history.
### Required Fields
Fill out the following fields and **click** the **Enable Mixpanel** button at the bottom right to save your changes:

* **Region:** Data residency region for your Mixpanel project.
* **Project Token:** Your Mixpanel project token (Mixpanel → Settings → Project Settings → Project Token).
* **Total Spend Property:** The name of the user property to track cumulative spend.
* **Sales Reporting:** Whether to report Proceeds after store taxes & fees or Revenue. Choose between **Proceeds** (after store taxes & fees) or **Revenue**.
### Features
* **Automatic Event Mapping**: Converts Superwall events to Mixpanel-friendly event names
* **Revenue Tracking**: Tracks both price (gross) and proceeds (net after fees)
* **User Profile Enrichment**: Maintains cumulative spend and transaction history
* **Multi-Region Support**: Works with US, EU, and IN data residency regions
* **Sandbox Isolation**: Separate tracking for production and sandbox events
* **Refund Handling**: Automatically adjusts revenue metrics for refunds
## Configuration
### Required Settings
| Field | Description | Example |
| ---------------------- | --------------------------------------- | --------------------------- |
| `integration_id` | Must be set to `"mixpanel"` | `"mixpanel"` |
| `region` | Data residency region | `"US"`, `"EU"`, or `"IN"` |
| `project_token` | Your Mixpanel project token | `"abc123def456..."` |
| `total_spend_property` | User property name for cumulative spend | `"lifetime_revenue"` |
| `sales_reporting` | Which value to report | `"Revenue"` or `"Proceeds"` |
### Optional Settings
| Field | Description | Example |
| ----------------------- | ---------------------------------------------- | ------------- |
| `sandbox_project_token` | Token for sandbox events (leave blank to skip) | `"xyz789..."` |
### Example Configuration
```json
{
"integration_id": "mixpanel",
"region": "US",
"project_token": "your_production_token_here",
"sandbox_project_token": "your_sandbox_token_here",
"total_spend_property": "lifetime_revenue",
"sales_reporting": "Proceeds"
}
```
## Event Mapping
Superwall events are transformed into standardized Mixpanel events with the `sw_` prefix:
### Trial Events
| Superwall Event | Mixpanel Event | Description |
| ---------------------------------------- | ---------------------- | ----------------------- |
| `initial_purchase` + `periodType: TRIAL` | `sw_trial_start` | Trial period begins |
| `cancellation` + `periodType: TRIAL` | `sw_trial_cancelled` | Trial cancelled |
| `uncancellation` + `periodType: TRIAL` | `sw_trial_uncancelled` | Trial reactivated |
| `expiration` + `periodType: TRIAL` | `sw_trial_expired` | Trial ended |
| `renewal` + `isTrialConversion: true` | `sw_trial_converted` | Trial converted to paid |
### Intro Offer Events
| Superwall Event | Mixpanel Event | Description |
| ---------------------------------------- | ---------------------------- | -------------------------- |
| `initial_purchase` + `periodType: INTRO` | `sw_intro_offer_start` | Intro offer begins |
| `cancellation` + `periodType: INTRO` | `sw_intro_offer_cancelled` | Intro offer cancelled |
| `uncancellation` + `periodType: INTRO` | `sw_intro_offer_uncancelled` | Intro offer reactivated |
| `expiration` + `periodType: INTRO` | `sw_intro_offer_expired` | Intro offer ended |
| `renewal` + `periodType: INTRO` | `sw_intro_offer_converted` | Intro converted to regular |
### Subscription Events
| Superwall Event | Mixpanel Event | Description |
| ----------------------------------------- | ----------------------------- | ------------------------ |
| `initial_purchase` + `periodType: NORMAL` | `sw_subscription_start` | Subscription begins |
| `renewal` + `periodType: NORMAL` | `sw_renewal` | Subscription renewed |
| `cancellation` + `periodType: NORMAL` | `sw_subscription_cancelled` | Subscription cancelled |
| `uncancellation` + `periodType: NORMAL` | `sw_subscription_uncancelled` | Subscription reactivated |
| `expiration` + `periodType: NORMAL` | `sw_subscription_expired` | Subscription ended |
| `subscription_paused` | `sw_subscription_paused` | Subscription paused |
| `billing_issue` | `sw_billing_issue` | Payment failed |
### Other Events
| Superwall Event | Mixpanel Event | Description |
| -------------------------- | -------------------------- | ----------------- |
| `product_change` | `sw_product_change` | Plan changed |
| `non_renewing_purchase` | `sw_non_renewing_purchase` | One-time purchase |
| Any event with `price < 0` | `sw_refund` | Refund processed |
## Event Properties
Every Mixpanel event includes all fields from the Superwall webhook data object as properties:
### Core Properties
* `distinct_id`: User identifier (uses `originalAppUserId` or falls back to `originalTransactionId`)
* `time`: Unix timestamp in seconds
* `$insert_id`: Unique event ID (prevents duplicates)
* `token`: Your Mixpanel project token
### Webhook Data Properties
All fields from the webhook are included:
* `id`, `name`, `cancelReason`, `exchangeRate`
* `isSmallBusiness`, `periodType`, `countryCode`
* `price`, `proceeds`, `priceInPurchasedCurrency`
* `taxPercentage`, `commissionPercentage`, `takehomePercentage`
* `offerCode`, `isFamilyShare`, `expirationAt`
* `transactionId`, `originalTransactionId`, `originalAppUserId`
* `store`, `purchasedAt`, `currencyCode`, `productId`
* `environment`, `isTrialConversion`, `newProductId`
* `bundleId`, `ts`
## User Profile Updates
The integration performs two profile updates for revenue events:
### 1. Transaction History
Appends transaction details to the `$transactions` array:
```json
{
"$transactions": {
"$amount": 9.99,
"$time": "2025-01-01T12:00:00.000Z",
// Plus all webhook data fields
}
}
```
### 2. Cumulative Spend
Updates the total spend property (configurable):
```json
{
"lifetime_revenue": 129.99 // Incremented by transaction amount
}
```
## Revenue Reporting Options
### Price vs Proceeds
The `sales_reporting` setting determines which value is used for revenue:
| Setting | Value Used | Description |
| ------------ | ---------- | ----------------------------------------- |
| `"Revenue"` | `price` | Gross revenue before store fees and taxes |
| `"Proceeds"` | `proceeds` | Net revenue after store fees and taxes |
### Examples
**Gross Revenue (Price):**
* Transaction price: $9.99
* Store commission (30%): $3.00
* Your proceeds: $6.99
* Reported to Mixpanel: **$9.99**
**Net Revenue (Proceeds):**
* Transaction price: $9.99
* Store commission (30%): $3.00
* Your proceeds: $6.99
* Reported to Mixpanel: **$6.99**
## Sandbox Handling
### With Sandbox Token
If `sandbox_project_token` is configured:
* Production events → Production project
* Sandbox events → Sandbox project
### Without Sandbox Token
If `sandbox_project_token` is empty:
* Production events → Production project
* Sandbox events → **Skipped** (not sent to Mixpanel)
## Refund Handling
Refunds are automatically detected when `price < 0`:
* Event type: `sw_refund`
* Transaction amount: Negative value
* Cumulative spend: Decremented by refund amount
Example:
* Original purchase: +$9.99
* Refund event: -$9.99
* Net effect on lifetime revenue: $0.00
## Data Residency
Mixpanel supports three data residency regions:
| Region | API Endpoint | Use Case |
| ------ | ------------------- | -------------------- |
| `US` | api.mixpanel.com | Default, global |
| `EU` | api-eu.mixpanel.com | GDPR compliance |
| `IN` | api-in.mixpanel.com | India data residency |
## User Identification
The integration uses the following hierarchy for user identification:
1. **Primary**: `originalAppUserId` (if available)
2. **Fallback**: `originalTransactionId` (always present)
This ensures consistent user tracking even for:
* Legacy users without app user IDs
* Family sharing scenarios
* Cross-platform subscriptions
## Testing the Integration
### 1. Trigger Sandbox Events
* iOS: Use TestFlight with a sandbox Apple ID. StoreKit Configuration files do not generate App Store Server Notifications, so webhooks and downstream integrations won't fire.
* Google Play: Use license test accounts to perform sandbox purchases.
* Stripe: Use Stripe Test Mode to create sandbox transactions.
### 2. Verify in Mixpanel
Check your Mixpanel project:
1. Live View → Verify events arriving
2. Users → Check profile updates
3. Reports → Confirm revenue tracking
## Troubleshooting
### Events Not Appearing
1. **Check Token**: Verify project token is correct
2. **Check Region**: Ensure region matches your Mixpanel project
3. **Check Environment**: Sandbox events need sandbox token
4. **Check Distinct ID**: User must have valid identifier
### Revenue Not Tracking
1. **Check Sales Reporting**: Verify Price vs Proceeds setting
2. **Check Property Name**: Confirm `total_spend_property` exists
3. **Check Event Type**: Only revenue events update spend
4. **Check Refunds**: Negative amounts decrease total
### Duplicate Events
The integration uses `$insert_id` to prevent duplicates:
* Format: `eventId-eventName`
* Example: `abc123-renewal`
Mixpanel automatically deduplicates events with the same `$insert_id`.
## Best Practices
1. **Use Consistent User IDs**: Send user IDs to app stores for better tracking
2. **Set Up Both Tokens**: Configure sandbox token for complete testing
3. **Choose Revenue Model**: Decide between gross (Price) vs net (Proceeds)
4. **Monitor Both Projects**: Check production and sandbox regularly
5. **Handle Refunds**: Ensure your analytics account for negative revenue
## Rate Limits
Mixpanel has the following limits:
* **Events**: 2,000 requests/second
* **Profile Updates**: 2,000 requests/second
* **Batch Size**: 2MB per request
The integration sends events individually, well within these limits.
## Data Privacy
* **PII Handling**: User IDs are pseudonymous by default
* **GDPR Compliance**: Use EU region for European users
* **Data Retention**: Follows your Mixpanel project settings
* **Deletion Requests**: Handle via Mixpanel's privacy tools
---
# Slack
Source: https://superwall.com/docs/integrations/slack
The Slack integration sends real-time notifications about subscription events to your Slack channels. Get instant updates about new subscribers, cancellations, renewals, and revenue changes with rich, color-coded messages and contextual emojis.
In the **Communication** section within **Integrations**, you can connect your Slack account to Superwall:

### Required Fields
Fill out the following fields and **click** the **Enable Slack** button at the bottom right to save your changes:

* **Webhook Url:** Your Slack webhook URL for sending messages to a channel.
* **Include Sandbox:** Whether to include sandbox events in Slack notifications.
* **Event Type:** Type of events to send: revenue only or all lifecycle (includes trials, cancellations).
### Features
* **Real-time Notifications**: Instant Slack messages for subscription events
* **Smart Filtering**: Choose between revenue events only or all subscription lifecycle events
* **Visual Design**: Color-coded messages with contextual emojis for quick scanning
* **Revenue Insights**: See price, proceeds, and currency information at a glance
* **Sandbox Control**: Optional inclusion of sandbox events
* **Rich Context**: Includes user ID, product, country, and transaction details
## Configuration
### Required Settings
| Field | Description | Example |
| ----------------- | --------------------------------- | ------------------------------------------------------ |
| `integration_id` | Must be set to `"slack"` | `"slack"` |
| `webhook_url` | Your Slack incoming webhook URL | `"https://hooks.slack.com/services/..."` |
| `include_sandbox` | Whether to include sandbox events | `"Production Only"` or `"Production & Sandbox"` |
| `event_type` | Types of events to send | `"Revenue Events Only"` or `"All Subscription Events"` |
### Example Configuration
```json
{
"integration_id": "slack",
"webhook_url": "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX",
"include_sandbox": "Production Only",
"event_type": "Revenue Events Only"
}
```
## Setting Up Slack Webhooks
1. **Create Incoming Webhook**:
* Go to [api.slack.com/apps](https://api.slack.com/apps)
* Create a new app or select existing
* Enable "Incoming Webhooks"
* Add new webhook to workspace
* Select target channel
2. **Copy Webhook URL**:
* Format: `https://hooks.slack.com/services/T.../B.../...`
* Keep this URL secure
3. **Verify Connection**:
* Trigger a real sandbox transaction (see Testing section below)
* Verify a message appears in your selected channel
## Event Filtering
### Revenue Events Only
Sends notifications for events with monetary impact:
* ✅ Initial purchases (paid)
* ✅ Renewals
* ✅ Refunds (negative amounts)
* ✅ Trial/intro conversions (when paid)
* ❌ Cancellations (no immediate revenue impact)
* ❌ Expirations
* ❌ Billing issues
### All Subscription Events
Sends notifications for all lifecycle events:
* ✅ All revenue events (above)
* ✅ Trial starts
* ✅ Cancellations
* ✅ Uncancellations
* ✅ Expirations
* ✅ Billing issues
* ✅ Product changes
* ✅ Subscription pauses
## Message Format
### Visual Indicators
Messages use colors and emojis for quick scanning:
#### Colors
* 🟢 **Green** (#36a64f): Positive events (purchases, renewals, uncancellations)
* 🔴 **Red** (#FA6A6A): Negative events (cancellations, expirations, refunds)
* ⚫ **Gray** (#666666): Neutral events (product changes, pauses)
#### Emojis by Event Type
**Trial Events:**
* 🤩 Trial start
* 💰 Trial conversion
* 😞 Trial cancelled
* 😞 Trial expired
* 🤩 Trial uncancelled
* 🤬 Trial refunded
**Intro Offer Events:**
* 💰/🤩 Intro offer start
* 💰 Intro offer conversion
* 😞 Intro offer cancelled
* 😞 Intro offer expired
* 🤩 Intro offer uncancelled
* 🤬 Intro offer refunded
**Subscription Events:**
* 💰 New subscriber
* 💰 Renewal
* 😞 Subscription cancelled
* 😞 Subscription expired
* 🤩 Subscription uncancelled
* 🤬 Subscription refunded
**Special Events:**
* 😵💫 Product change
* 🫠 Billing issue
* ⏸️ Subscription paused
* 💸 Non-renewing purchase
### Message Structure
Each Slack message includes:
```
[Emoji] [Event Description]
━━━━━━━━━━━━━━━━━━━━━
💵 $9.99 USD (Proceeds: $6.99)
📦 com.example.premium.monthly
🌍 United States
👤 User123
🏪 APP_STORE
🔗 Transaction: 700001234567890
```
### Field Descriptions
| Field | Description | Example |
| --------------- | --------------------- | --------------------------- |
| **Header** | Event type with emoji | "💰 renewal" |
| **Price** | Transaction amount | "$9.99 USD" |
| **Proceeds** | Net after fees | "Proceeds: $6.99" |
| **Product** | Product identifier | "com.example.premium" |
| **Country** | User's country | "United States" |
| **User** | User identifier | "User123" or transaction ID |
| **Store** | Payment provider | "APP\_STORE" |
| **Transaction** | Transaction ID | "700001234567890" |
## Sandbox Handling
### Production Only
* Production events → Sent to Slack
* Sandbox events → **Skipped**
### Production & Sandbox
* Production events → Sent to Slack
* Sandbox events → Sent to Slack with 🧪 indicator
Sandbox events include a note in the message to differentiate from production.
## Special Event Handling
### Refunds
Identified by negative price values:
* Header changes to "refunded \[type]"
* Emoji changes to 🤬
* Color remains red
* Shows negative amount
### Family Sharing
Events with `isFamilyShare: true`:
* Shows shared subscription indicator
* Price may be $0 for family members
* Original purchaser shows full price
### Trial Conversions
Renewals with `isTrialConversion: true`:
* Header shows "trial conversion"
* Indicates successful trial-to-paid transition
* Always green/positive color
### Product Changes
Shows when users switch plans:
* Displays old and new product IDs
* Neutral gray color
* May have $0 price
## Use Cases
### Revenue Monitoring
Track real-time revenue with "Revenue Events Only":
* Monitor daily subscription revenue
* Get alerts for high-value purchases
* Track refund activity
* Celebrate trial conversions
### Customer Success
Track lifecycle with "All Subscription Events":
* Monitor cancellation trends
* Identify billing issues quickly
* Track trial-to-paid conversion
* Spot at-risk subscribers
### Team Celebrations
Share wins with your team:
* New subscriber notifications
* Trial conversion celebrations
* Renewal milestones
* Recovery from cancellations
## Best Practices
1. **Dedicated Channels**: Create specific channels for different event types
2. **Filter Appropriately**: Use "Revenue Only" for finance, "All Events" for customer success
3. **Include Context**: User IDs help connect events to support tickets
4. **Monitor Patterns**: Watch for unusual cancellation or refund spikes
5. **Sandbox Separation**: Consider separate webhooks for production vs testing
## Troubleshooting
### Messages Not Appearing
1. **Check Webhook URL**: Ensure URL is valid and not revoked
2. **Check Channel**: Verify bot has access to target channel
3. **Check Filters**: Confirm event type and sandbox settings
4. **Check Slack Limits**: Webhook rate limits (1 per second)
### Incorrect Information
1. **Check Timezone**: Timestamps are in UTC
2. **Check Currency**: Amounts in USD, original currency shown
3. **Check User ID**: Falls back to transaction ID if not available
### Verify the Integration
1. Trigger a sandbox transaction in your app:
* iOS: Use TestFlight with a sandbox Apple ID. StoreKit Configuration files do not generate App Store Server Notifications, so webhooks and downstream integrations won't fire.
* Google Play: Use license test accounts to perform sandbox purchases.
* Stripe: Use Stripe Test Mode to create sandbox transactions.
2. Confirm the message arrives in the configured Slack channel.
3. If you enabled Production & Sandbox, sandbox messages include an 🧪 indicator.
## Rate Limits
Slack incoming webhooks have a rate limit of 1 message per second. The integration sends events individually as they occur, typically well within this limit.
## Security Considerations
* **Webhook URLs are sensitive**: Treat like passwords
* **Rotate if compromised**: Generate new webhook URL if leaked
* **Channel permissions**: Ensure appropriate team members have access
* **PII considerations**: User IDs may be visible to channel members
## Advanced Configuration
### Multiple Channels
Set up multiple integrations for different channels:
* Revenue events → #revenue-alerts
* Cancellations → #customer-success
* All events → #subscription-monitoring
### Custom Filtering
While the integration offers two preset filters, you can:
* Use Slack workflows for additional filtering
* Set up multiple integrations with different settings
* Use Slack's notification preferences per channel
## Message Examples
### New Paid Subscription
```
💰 new subscriber
━━━━━━━━━━━━━━━━━━━━━
💵 $49.99 USD (Proceeds: $34.99)
📦 com.example.premium.yearly
🌍 United States
👤 user_abc123
🏪 APP_STORE
🔗 Transaction: 700001234567890
```
### Trial Start
```
🤩 Trial start
━━━━━━━━━━━━━━━━━━━━━
💵 $0.00 USD
📦 com.example.premium.monthly
🌍 Germany
👤 user_xyz789
🏪 PLAY_STORE
🔗 Transaction: GPA.1234-5678-9012
```
### Refund
```
🤬 refunded subscription
━━━━━━━━━━━━━━━━━━━━━
💵 -$9.99 USD (Proceeds: -$6.99)
📦 com.example.premium.monthly
🌍 United Kingdom
👤 user_def456
🏪 STRIPE
🔗 Transaction: sub_1234567890
```
### Billing Issue
```
🫠 Billing issue
━━━━━━━━━━━━━━━━━━━━━
💵 $0.00 USD
📦 com.example.premium.monthly
🌍 Canada
👤 user_ghi789
🏪 APP_STORE
🔗 Transaction: 700009876543210
❗ Payment failed - subscription at risk
```
---
# Statsig
Source: https://superwall.com/docs/integrations/statsig
The Statsig integration allows you to automatically send Superwall subscription and payment events to your Statsig project. This integration provides comprehensive event tracking with user properties for experimentation and analytics.
In the **Analytics** section within **Integrations**, you can connect your Statsig account to Superwall:

### Required fields
Fill out the following fields and **click** the **Enable Statsig** button at the bottom right to save your changes:

* **Client SDK Key:** Your Statsig client SDK key from Statsig → Project Settings → Keys & Environments.
* **Environment:** Which environments to send events from.
* **Sales Reporting:** Whether to report Proceeds after store taxes & fees or Revenue. Choose between **Proceeds** (after store taxes & fees) or **Revenue**.
### Features
* **Automatic Event Mapping**: Converts Superwall events to Statsig-friendly event names with `sw_` prefix
* **Revenue Tracking**: Tracks both price (gross) and proceeds (net after fees)
* **User Property Enrichment**: Attaches store, product, and transaction metadata to user objects
* **Environment Tier Separation**: Uses Statsig's tier system to separate production and staging data
* **Sandbox Isolation**: Separate tracking for sandbox events
* **Transaction ID Tracking**: Maintains transaction IDs as custom IDs for reconciliation
* **Custom Event Metadata**: Includes all Superwall event data as metadata for deep analysis
### Configuration
#### Required settings
| Field | Description | Example |
| ----------------- | -------------------------------------- | ------------------------------------------ |
| `client_sdk_key` | Your Statsig client SDK key | `"client-abc123def456..."` |
| `environment` | Which environments to send events from | `"Production"` or `"Production & Sandbox"` |
| `sales_reporting` | Which value to report | `"Revenue"` or `"Proceeds"` |
### Event mapping
Superwall events are transformed into standardized Statsig events with the `sw_` prefix:
#### Trial events
| Superwall Event | Statsig Event | Description |
| ---------------------------------------- | ---------------------- | ----------------------- |
| `initial_purchase` + `periodType: TRIAL` | `sw_trial_start` | Trial period begins |
| `cancellation` + `periodType: TRIAL` | `sw_trial_cancelled` | Trial cancelled |
| `uncancellation` + `periodType: TRIAL` | `sw_trial_uncancelled` | Trial reactivated |
| `expiration` + `periodType: TRIAL` | `sw_trial_expired` | Trial ended |
| `renewal` + `isTrialConversion: true` | `sw_trial_converted` | Trial converted to paid |
#### Intro offer events
| Superwall Event | Statsig Event | Description |
| ---------------------------------------- | ---------------------------- | -------------------------- |
| `initial_purchase` + `periodType: INTRO` | `sw_intro_offer_start` | Intro offer begins |
| `cancellation` + `periodType: INTRO` | `sw_intro_offer_cancelled` | Intro offer cancelled |
| `uncancellation` + `periodType: INTRO` | `sw_intro_offer_uncancelled` | Intro offer reactivated |
| `expiration` + `periodType: INTRO` | `sw_intro_offer_expired` | Intro offer ended |
| `renewal` + `periodType: INTRO` | `sw_intro_offer_converted` | Intro converted to regular |
#### Subscription events
| Superwall Event | Statsig Event | Description |
| ----------------------------------------- | ----------------------------- | ------------------------ |
| `initial_purchase` + `periodType: NORMAL` | `sw_subscription_start` | Subscription begins |
| `renewal` + `periodType: NORMAL` | `sw_renewal` | Subscription renewed |
| `cancellation` + `periodType: NORMAL` | `sw_subscription_cancelled` | Subscription cancelled |
| `uncancellation` + `periodType: NORMAL` | `sw_subscription_uncancelled` | Subscription reactivated |
| `expiration` + `periodType: NORMAL` | `sw_subscription_expired` | Subscription ended |
| `subscription_paused` | `sw_subscription_paused` | Subscription paused |
| `billing_issue` | `sw_billing_issue` | Payment failed |
#### Other events
| Superwall Event | Statsig Event | Description |
| -------------------------- | -------------------------- | ----------------- |
| `product_change` | `sw_product_change` | Plan changed |
| `non_renewing_purchase` | `sw_non_renewing_purchase` | One-time purchase |
| Any event with `price < 0` | `sw_refund` | Refund processed |
### Event properties
Every Statsig event includes the following structure:
#### Core event fields
* `eventName`: The mapped event name with `sw_` prefix
* `value`: Revenue amount (when applicable)
* `time`: Unix timestamp in milliseconds
* `user`: User object with identity and properties
* `metadata`: All webhook data fields
#### User object
The user object contains:
* **userID**: User identifier (uses `originalAppUserId` or falls back to `originalTransactionId`)
* **country**: Two-letter country code (e.g., "US", "GB")
* **custom**: Transaction properties attached to the user
* `isFamilyShare`: Whether the latest transaction is a family share
* `store`: The store of the latest transaction (APP\_STORE, PLAY\_STORE, STRIPE, PADDLE)
* `productId`: The product ID of the latest transaction
* `bundleId`: The bundle ID of the latest transaction
* **customIDs**: Additional identifiers
* `originalTransactionId`: Store transaction ID (when available)
* **statsigEnvironment**: Environment tier configuration
* `tier: "production"` for production events
* `tier: "staging"` for sandbox events
#### Event metadata
All fields from the webhook are included as metadata:
* `id`, `name`, `cancelReason`, `exchangeRate`
* `isSmallBusiness`, `periodType`, `countryCode`
* `price`, `proceeds`, `priceInPurchasedCurrency`
* `taxPercentage`, `commissionPercentage`, `takehomePercentage`
* `offerCode`, `isFamilyShare`, `expirationAt`
* `transactionId`, `originalTransactionId`, `originalAppUserId`
* `store`, `purchasedAt`, `currencyCode`, `productId`
* `environment`, `isTrialConversion`, `newProductId`
* `bundleId`, `ts`
### Revenue reporting options
#### Price vs proceeds
The `sales_reporting` setting determines which value is used for the `value` field:
| Setting | Value Used | Description |
| ------------ | ---------- | ----------------------------------------- |
| `"Revenue"` | `price` | Gross revenue before store fees and taxes |
| `"Proceeds"` | `proceeds` | Net revenue after store fees and taxes |
#### Examples
**Gross Revenue (Price):**
* Transaction price: $9.99
* Store commission (30%): $3.00
* Your proceeds: $6.99
* Reported to Statsig: **$9.99**
**Net Revenue (Proceeds):**
* Transaction price: $9.99
* Store commission (30%): $3.00
* Your proceeds: $6.99
* Reported to Statsig: **$6.99**
### Sandbox handling
#### With sandbox enabled
If `environment` is set to `"Production & Sandbox"`:
* Production events → Tagged with `tier: "production"`
* Sandbox events → Tagged with `tier: "staging"`
#### Without sandbox enabled
If `environment` is set to `"Production"`:
* Production events → Tagged with `tier: "production"`
* Sandbox events → **Skipped** (not sent to Statsig)
This allows you to:
* Filter events by environment tier in Statsig dashboards
* Create separate metrics for production vs. sandbox
* Validate integration without polluting production data
### Refund handling
Refunds are automatically detected when `price < 0`:
* Event type: `sw_refund`
* Value field: Negative amount
* All metadata preserved for analysis
Example:
* Original purchase: +$9.99
* Refund event: -$9.99
* Net effect on metrics: $0.00
### User identification
The integration uses the following hierarchy for user identification:
1. **Primary**: `originalAppUserId` (if available)
2. **Fallback**: `originalTransactionId` (always present)
This ensures consistent user tracking even for:
* Legacy users without app user IDs
* Family sharing scenarios
* Cross-platform subscriptions
### Testing the integration
#### 1. Trigger sandbox events
* iOS: Use TestFlight with a sandbox Apple ID. StoreKit Configuration files do not generate App Store Server Notifications, so webhooks and downstream integrations won't fire.
* Google Play: Use license test accounts to perform test purchases in sandbox.
* Stripe: Use Stripe Test Mode to create sandbox transactions.
#### 2. Verify in Statsig
Check your Statsig project:
1. Navigate to **Metrics** → **Events Stream**
2. Look for events with `sw_` prefix
3. Click on an event to view properties and metadata
4. Verify the `statsigEnvironment.tier` matches your configuration
### Troubleshooting
#### Events not appearing
1. **Check API Key**: Ensure you're using the client SDK key (starts with "client-")
2. **Check Environment**: Confirm sandbox events are enabled if testing with sandbox data
3. **Check Events Stream**: Look in Metrics → Events Stream, not just dashboards
4. **Wait for Processing**: Events may take a few seconds to appear
#### Authentication errors
* **Invalid Key Format**: Client SDK keys must start with "client-"
* **Wrong Project**: Verify the key belongs to the correct Statsig project
* **Key Permissions**: Ensure the key has event logging permissions
#### Missing or incorrect data
* **Check Event Properties**: Use Statsig's Events Stream to inspect raw event data
* **Verify User ID**: Ensure `originalAppUserId` is being set in your app
* **Environment Mismatch**: Production events won't appear if filtered for staging tier
### Best practices
1. **Use Consistent User IDs**: Send the same user IDs to both Superwall and Statsig for proper correlation
2. **Choose Revenue Model**: Decide between gross (Revenue) vs net (Proceeds) and use consistently
3. **Set Up Environment Tiers**: Use staging tier for testing without affecting production metrics
4. **Monitor Events Stream**: Regularly check the Events Stream for data quality
5. **Create Custom Metrics**: Build metrics based on subscription events for experimentation
6. **Handle Refunds**: Account for negative revenue events in your analysis
### Rate limits
Statsig has the following limits:
* **Events**: 10,000 requests/second per project
* **Batch Size**: 500 events per batch (this integration sends one at a time)
* **Request Size**: 1MB maximum per request
The integration sends events individually, well within these limits.
### Data privacy
* **PII Handling**: User IDs are pseudonymous by default
* **HTTPS Only**: All events sent over encrypted connections
* **Data Retention**: Follows your Statsig project settings
* **Deletion Requests**: Handle via Statsig's privacy tools
---
# Webhooks
Source: https://superwall.com/docs/integrations/webhooks/index
Use webhooks to get real-time notifications about your app's subscription and payment events.
In the **Webhooks** section within **Integrations**, you can manage your webhooks with Superwall:

## Webhooks
Superwall sends webhooks to notify your application about important subscription and payment events in real-time. These webhooks are designed to closely match App Store and other revenue provider events, minimizing migration difficulty.
**Important Design Principle**: Webhook events are structured so that summing `proceeds` or `price` across all events (without filtering) accurately represents total revenue net of refunds. To calculate gross revenue, filter out events with negative proceeds.
### Webhook Payload Structure
Every webhook sent by Superwall contains the following structure:
```json
{
"object": "event",
"type": "renewal",
"projectId": 3827,
"applicationId": 1,
"timestamp": 1754067715103,
"data": {
"id": "42fc6339-dc28-470b-a0fa-0d13c92d8b61:renewal",
"name": "renewal",
"cancelReason": null,
"exchangeRate": 1.0,
"isSmallBusiness": false,
"periodType": "NORMAL",
"countryCode": "US",
"price": 9.99,
"proceeds": 6.99,
"priceInPurchasedCurrency": 9.99,
"taxPercentage": 0,
"commissionPercentage": 0.3,
"takehomePercentage": 0.7,
"offerCode": null,
"isFamilyShare": false,
"expirationAt": 1756659704000,
"transactionId": "700002054157982",
"originalTransactionId": "700002050981465",
"originalAppUserId": "$SuperwallAlias:7152E89E-60A6-4B2E-9C67-D7ED8F5BE372",
"store": "APP_STORE",
"purchasedAt": 1754067704000,
"currencyCode": "USD",
"productId": "com.example.premium.monthly",
"environment": "PRODUCTION",
"isTrialConversion": false,
"newProductId": null,
"bundleId": "com.example.app",
"ts": 1754067710106
}
}
```
### Webhook Payload Fields
| Field | Type | Description |
| --------------- | ------ | --------------------------------------------------------------------- |
| `object` | string | Always "event" |
| `type` | string | The event type (e.g., "initial\_purchase", "renewal", "cancellation") |
| `projectId` | number | Your Superwall project ID |
| `applicationId` | number | Your Superwall application ID |
| `timestamp` | number | Event timestamp in milliseconds since epoch |
| `data` | object | Event-specific data (see below) |
## Event Data Object
The `data` field contains detailed information about the subscription or payment event:
### Event Data Fields
| Field | Type | Description |
| -------------------------- | ----------------- | --------------------------------------------------------------------------------------------- |
| `id` | string | Unique identifier for this event |
| `name` | string | Event name (see [Event Names](#event-names)) |
| `cancelReason` | string or null | Reason for cancellation (see [Cancel Reasons](#cancelexpiration-reasons)) |
| `exchangeRate` | number | Exchange rate used to convert to USD |
| `isSmallBusiness` | boolean | Small business program participant |
| `periodType` | string | Period type: `TRIAL`, `INTRO`, or `NORMAL` |
| `countryCode` | string | ISO country code (e.g., "US") |
| `price` | number | Transaction price in USD (negative for refunds) |
| `proceeds` | number | Net proceeds in USD after taxes and fees |
| `priceInPurchasedCurrency` | number | Price in original currency |
| `taxPercentage` | number or null | Tax percentage applied |
| `commissionPercentage` | number | Store commission percentage |
| `takehomePercentage` | number | Your percentage after commission |
| `offerCode` | string or null | Promotional offer code used |
| `isFamilyShare` | boolean | Family sharing purchase |
| `expirationAt` | number or null | Expiration timestamp (milliseconds) |
| `transactionId` | string | Current transaction ID |
| `originalTransactionId` | string | Original transaction ID (subscription ID) |
| `originalAppUserId` | string or null | Original app user ID — requires SDK v4.5.2+ (see [details](#understanding-originalappuserid)) |
| `store` | string | Store: `APP_STORE`, `PLAY_STORE`, `STRIPE`, or `PADDLE` (see note below) |
| `purchasedAt` | number | Purchase timestamp (milliseconds) |
| `currencyCode` | string | ISO currency code for priceInPurchasedCurrency |
| `productId` | string | Product identifier |
| `environment` | string | `PRODUCTION` or `SANDBOX` |
| `isTrialConversion` | boolean | Trial to paid conversion |
| `newProductId` | string or null | New product ID (for product changes) |
| `bundleId` | string | App bundle identifier |
| `ts` | number | Event timestamp (milliseconds) |
| `expirationReason` | string (optional) | Reason for expiration (see [Cancel Reasons](#cancelexpiration-reasons)) |
| `checkoutContext` | object (optional) | Stripe-specific checkout context |
**Note on Store field:** iOS and Android apps can receive events from any payment provider. For example, an iOS app can receive `STRIPE` or `PADDLE` events when users purchase through Superwall's App2Web features, which allow web-based checkout flows within mobile apps. The `store` field indicates where the payment was processed, not which platform the app runs on.
## Event Names
| Event Name | Value | Description |
| --------------------- | ----------------------- | ----------------------------------- |
| Initial Purchase | `initial_purchase` | First-time subscription or purchase |
| Renewal | `renewal` | Subscription renewal |
| Cancellation | `cancellation` | Subscription cancelled |
| Uncancellation | `uncancellation` | Subscription reactivated |
| Expiration | `expiration` | Subscription expired |
| Billing Issue | `billing_issue` | Payment processing failed |
| Product Change | `product_change` | User changed subscription tier |
| Subscription Paused | `subscription_paused` | Subscription temporarily paused |
| Non-Renewing Purchase | `non_renewing_purchase` | One-time purchase |
## Period Types
| Period Type | Value | Description |
| ----------- | -------- | ------------------------------------------- |
| Trial | `TRIAL` | Free trial period |
| Intro | `INTRO` | Introductory offer period (discounted rate) |
| Normal | `NORMAL` | Regular subscription period (full price) |
## Stores
| Store | Value | Description |
| ---------- | ------------ | ----------------------------- |
| App Store | `APP_STORE` | Apple App Store |
| Play Store | `PLAY_STORE` | Google Play Store |
| Stripe | `STRIPE` | Stripe payments |
| Paddle | `PADDLE` | Paddle payments (coming soon) |
## Environments
| Environment | Value | Description |
| ----------- | ------------ | ------------------------------------- |
| Production | `PRODUCTION` | Live production transactions |
| Sandbox | `SANDBOX` | Sandbox transactions (not real money) |
## Cancel/Expiration Reasons
| Reason | Value | Description |
| ------------------- | --------------------- | ----------------------------- |
| Billing Error | `BILLING_ERROR` | Payment method failed |
| Customer Support | `CUSTOMER_SUPPORT` | Cancelled via support |
| Unsubscribe | `UNSUBSCRIBE` | User-initiated cancellation |
| Price Increase | `PRICE_INCREASE` | Cancelled due to price change |
| Developer Initiated | `DEVELOPER_INITIATED` | Cancelled programmatically |
| Unknown | `UNKNOWN` | Reason not specified |
## Common Use Cases
### Detecting Trial Starts
```javascript
if (
event.data.periodType === "TRIAL" &&
event.data.name === "initial_purchase"
) {
// New trial started
}
```
### Detecting Trial Conversions
```javascript
if (
event.data.name === "renewal" &&
(event.data.isTrialConversion ||
event.data.periodType === "TRIAL" ||
event.data.periodType === "INTRO")
) {
// Trial or intro offer converted to paid subscription
}
```
### Detecting Trial Cancellations
```javascript
if (event.data.periodType === "TRIAL" && event.data.name === "cancellation") {
// Trial cancelled
}
```
### Detecting Trial Uncancellations (Reactivations)
```javascript
if (event.data.periodType === "TRIAL" && event.data.name === "uncancellation") {
// Trial reactivated after cancellation
}
```
### Detecting Trial Expirations
```javascript
if (event.data.periodType === "TRIAL" && event.data.name === "expiration") {
// Trial expired
}
```
### Detecting Intro Offer Starts
```javascript
if (
event.data.periodType === "INTRO" &&
event.data.name === "initial_purchase"
) {
// Intro offer started
}
```
### Detecting Intro Offer Cancellations
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "cancellation") {
// Intro offer cancelled
}
```
### Detecting Intro Offer Uncancellations
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "uncancellation") {
// Intro offer reactivated
}
```
### Detecting Intro Offer Expirations
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "expiration") {
// Intro offer expired
}
```
### Detecting Intro Offer Conversions
```javascript
if (event.data.periodType === "INTRO" && event.data.name === "renewal") {
// Intro offer converted to regular subscription
}
```
### Detecting Subscription Starts
```javascript
if (
event.data.periodType === "NORMAL" &&
event.data.name === "initial_purchase"
) {
// New paid subscription started
}
```
### Detecting Renewals
```javascript
if (
event.data.name === "renewal" &&
event.data.periodType === "NORMAL" &&
!event.data.isTrialConversion
) {
// Regular subscription renewal
}
```
### Detecting Refunds
```javascript
if (event.data.price < 0) {
// Refund processed
const refundAmount = Math.abs(event.data.price);
}
```
### Detecting Cancellations
```javascript
if (event.data.name === "cancellation") {
// Subscription cancelled
// Check cancelReason for details
const reason = event.data.cancelReason;
}
```
### Detecting Subscription Expirations
```javascript
if (event.data.name === "expiration") {
// Subscription expired
// Check expirationReason for details
}
```
### Detecting Billing Issues
```javascript
if (event.data.name === "billing_issue") {
// Payment failed - subscription at risk
}
```
### Detecting Subscription Pauses
```javascript
if (event.data.name === "subscription_paused") {
// Subscription has been paused
}
```
### Detecting Product Changes
```javascript
if (event.data.name === "product_change") {
// User changed subscription plan
const oldProduct = event.data.productId;
const newProduct = event.data.newProductId;
}
```
### Detecting Subscription Reactivations
```javascript
if (event.data.name === "uncancellation") {
// Previously cancelled subscription was reactivated
}
```
### Detecting Non-Renewing Purchases
```javascript
if (event.data.name === "non_renewing_purchase") {
// One-time purchase completed
}
```
### Detecting Revenue Events
```javascript
if (event.data.price !== 0 || event.data.name === "non_renewing_purchase") {
// This event involves revenue (positive or negative)
}
```
## Revenue Calculation
### Total Net Revenue (Including Refunds)
```javascript
// Sum all proceeds - automatically accounts for refunds
const netRevenue = events.reduce((sum, event) => sum + event.data.proceeds, 0);
```
### Gross Revenue (Excluding Refunds)
```javascript
// Only sum positive proceeds
const grossRevenue = events.reduce(
(sum, event) => (event.data.proceeds > 0 ? sum + event.data.proceeds : sum),
0
);
```
### Refund Total
```javascript
// Sum negative proceeds
const refunds = events.reduce(
(sum, event) =>
event.data.proceeds < 0 ? sum + Math.abs(event.data.proceeds) : sum,
0
);
```
### Revenue by Product
```javascript
const revenueByProduct = {};
events.forEach((event) => {
const productId = event.data.productId;
if (!revenueByProduct[productId]) {
revenueByProduct[productId] = 0;
}
revenueByProduct[productId] += event.data.proceeds;
});
```
## Testing Webhooks
iOS local StoreKit transactions (using a StoreKit Configuration file or StoreKitTest
in Xcode) do not generate App Store Server Notifications. As a result, Superwall
webhooks will not fire for these local test purchases. To verify webhook delivery on iOS,
use Sandbox via TestFlight with a sandbox Apple ID.
To test webhooks, trigger real events in sandbox:
* iOS: Use TestFlight with a sandbox Apple ID (StoreKit Configuration files do not trigger webhooks).
* Google Play: Use license test accounts for sandbox purchases.
* Stripe: Use Stripe Test Mode to create sandbox transactions.
Note: We do not support sending arbitrary "test" webhooks.
## Best Practices
1. **Handle duplicate events** - Use `event.id` for idempotency
2. **Process webhooks asynchronously** - Return 200 immediately, then process
3. **Store raw webhook data** for debugging and reconciliation
4. **Handle all event types** - Even if you don't process them immediately
5. **Monitor webhook failures** - Implement retry logic for critical events
6. **Use timestamps** - All timestamps are in milliseconds since epoch
## Store-Specific Behaviors
### Commission Rates by Store
**APP\_STORE:**
* Standard rate: 30%
* Small Business Program rate: 15% (for eligible developers)
* Clean, predictable commission structure
**PLAY\_STORE:**
* Variable rates from 11.8% to 15%
* Most common rate: 15%
* Rates can vary based on region and other factors
**STRIPE:**
* Variable rates from 0% to \~7.2%
* Generally lower than mobile app stores
* Depends on Stripe pricing plan and transaction type
### Price = 0 Events
Events commonly have `price = 0` for non-revenue scenarios:
* `billing_issue` - Payment failed, no money collected
* `cancellation` - Subscription cancelled, no charge
* `expiration` - Subscription expired, no charge
* `uncancellation` - Reactivation, no immediate charge
* `product_change` - Plan change notification
* `subscription_paused` - Pause event, no charge
Revenue events (initial\_purchase, renewal, non\_renewing\_purchase) typically have non-zero prices unless:
* Family sharing scenario (some cases)
* Special promotional offers
### Cancel/Expiration Reasons by Store
**APP\_STORE:**
* `CUSTOMER_SUPPORT` - Cancelled via Apple support
* `UNSUBSCRIBE` - User-initiated cancellation
* `BILLING_ERROR` - Payment failure
**PLAY\_STORE:**
* All APP\_STORE reasons plus:
* `UNKNOWN` - Reason not specified or unavailable
**STRIPE:**
* `UNKNOWN` - Stripe typically doesn't provide detailed cancellation reasons
### Trial Conversions
**Expected behavior:** `isTrialConversion` should only be `true` for `renewal` events
### Offer Codes Support
| Store | Support | Notes |
| ----------- | --------------- | -------------------------------------------------------------- |
| APP\_STORE | ✅ Supported | Rarely used (1.3% of events), typically for win-back campaigns |
| PLAY\_STORE | ✅ Supported | Heavily used (72.1% of events), complex promotional system |
| STRIPE | ❌ Not supported | Offer codes not available in webhook data |
| PADDLE | 🔜 Coming soon | Support planned |
### Environment Field
All stores support both PRODUCTION and SANDBOX environments:
* **PRODUCTION**: Live, real-money transactions
* **SANDBOX**: Sandbox transactions (TestFlight on iOS, Stripe Test Mode, Play Store test purchases)
The environment field helps you filter out sandbox transactions from production analytics.
## Store Event Compatibility Matrix
Not all events are available for all stores. This table shows which events you can expect from each store based on real webhook data:
### Event Support by Store
| Event Name | APP\_STORE | PLAY\_STORE | STRIPE | PADDLE |
| ----------------------- | ---------- | ----------- | ------ | ------ |
| `billing_issue` | ✅ | ✅ | ✅ | 🔜 |
| `cancellation` | ✅ | ✅ | ✅ | 🔜 |
| `expiration` | ✅ | ✅ | ✅ | 🔜 |
| `initial_purchase` | ✅ | ✅ | ✅ | 🔜 |
| `non_renewing_purchase` | ✅ | ✅ | ❌ | 🔜 |
| `product_change` | ✅ | ✅ | ❌ | 🔜 |
| `renewal` | ✅ | ✅ | ✅ | 🔜 |
| `subscription_paused` | ❌ | ✅ | ❌ | 🔜 |
| `uncancellation` | ✅ | ✅ | ✅ | 🔜 |
✅ = Supported | ❌ = Not supported | 🔜 = Coming soon
### Period Type Availability by Store
Different stores support different period types for events:
#### APP\_STORE
* Supports all period types (TRIAL, INTRO, NORMAL) for most events
* `non_renewing_purchase` only occurs with NORMAL period type
#### PLAY\_STORE
* Supports all period types (TRIAL, INTRO, NORMAL) for most events
* `renewal` only occurs with NORMAL period type
* `subscription_paused` only occurs with INTRO and NORMAL period types
* **Unique**: Only store that supports `subscription_paused` events
#### STRIPE
* Limited period type support compared to mobile app stores
* No INTRO period type support observed
* `expiration` and `renewal` only occur with NORMAL period type
* Does not support `non_renewing_purchase` or `product_change` events
#### PADDLE
* Coming soon - full support planned!
### Store-Specific Considerations
**Universal Events** (available across APP\_STORE, PLAY\_STORE, and STRIPE):
* `billing_issue`
* `cancellation`
* `expiration`
* `initial_purchase`
* `renewal`
* `uncancellation`
**Store-Specific Events**:
* `subscription_paused` - Only available from PLAY\_STORE
* `non_renewing_purchase` - Not available from STRIPE
* `product_change` - Not available from STRIPE
### Understanding originalAppUserId
The `originalAppUserId` field represents the first app user ID associated with a subscription. This field has specific behavior depending on your integration:
This field is only set correctly for events generated by users on SDK v4.5.2+.
Events from older SDK versions may omit this field or populate it inconsistently.
### Key Points:
* **What it represents**: The first user ID we saw associated with this subscription (originalTransactionId)
* **Cross-account subscriptions**: Since subscriptions are tied to Apple/Google accounts (not app accounts), users can create multiple accounts in your app while using the same subscription
* **We only store the first one**: If a user creates multiple accounts, we only track the original user ID
### When this field is populated:
* **iOS/App Store**:
* If your user ID has been sent to the stores on-device (via StoreKit)
* If your user IDs are UUIDv4 format
* This field will be consistently present for these cases
* **Stripe**: Always populated (we create one for you if not provided)
* **Play Store**: Depends on the integration and user tracking
### When this field is null:
* **Legacy users**: Users on old SDK versions
* **Pre-Superwall purchases**: Users who purchased before integrating Superwall
* **No user ID sent**: If user ID was never sent to the store
### Understanding originalTransactionId
The `originalTransactionId` is Apple's terminology that acts like a subscription ID. For simplicity and consistency with iOS and other revenue tracking platforms, we use this nomenclature and populate it accordingly for all platforms (Play Store, Stripe, Paddle, etc.).
* **One per subscription group**: Each user subscription gets one `originalTransactionId`
* **Persists across renewals**: The same `originalTransactionId` is used for all renewals in that subscription
* **Multiple IDs per user**: A single user can have multiple `originalTransactionId` if they:
* Subscribe to products in different subscription groups
* Let a subscription fully expire and re-subscribe later
* **Cross-platform consistency**: While originally an Apple concept, we generate and maintain equivalent IDs for all payment providers to ensure consistent subscription tracking
### Notes
* **Currency handling**:
* `price` and `proceeds` are always in USD
* `priceInPurchasedCurrency` is in the currency specified by `currencyCode`
* `exchangeRate` was used to convert from original currency to USD
* **Family Sharing** (App Store only):
* When `isFamilyShare` is true with `price > 0`: These are events for the **family organizer** who pays for the subscription (initial\_purchase, renewal, non\_renewing\_purchase)
* When `isFamilyShare` is true with `price = 0`: These are events for **family members** who use the shared subscription without paying (renewal, uncancellation, billing\_issue, etc.)
* **Refunds**: Negative values in `price`, `proceeds`, or `priceInPurchasedCurrency` indicate refunds
* **Transaction IDs**:
* `transactionId`: Unique ID for this specific transaction
* `originalTransactionId`: Subscription ID (first transaction in the subscription group)
* Commission and tax percentages help you understand the revenue breakdown
* **Timestamps**:
* `timestamp` (root level): When the webhook was created
* `ts` (in data): When the actual event occurred
* `purchasedAt`: When the transaction was originally purchased
---
# Verify Webhook Requests
Source: https://superwall.com/docs/integrations/webhooks/verify
Learn how to verify webhook requests using the signing secret to ensure authenticity and security.
## Why Verify Webhooks?
Verifying webhook requests is crucial for security. It ensures that:
* Requests are actually coming from Superwall's servers
* The payload hasn't been tampered with in transit
* Replay attacks are prevented through timestamp validation
Without verification, malicious actors could send fake webhook events to your endpoint.
## Getting Your Signing Secret
Every webhook endpoint has a unique signing secret that's used to verify requests. You can find this secret in your webhook details:

Click the **Copy Secret** button to copy your webhook's signing secret to your clipboard.
Keep your signing secret secure. Never commit it to version control or expose it in client-side code. Store it as an environment variable like `SUPERWALL_WEBHOOK_SECRET`.
## Verification Methods
### Option 1: Using Svix Library (Recommended)
Superwall uses [Svix](https://svix.com) for webhook delivery, which provides robust verification libraries for multiple languages.
Install the Svix library:
```bash
npm install svix
# or
yarn add svix
# or
pnpm add svix
```
Verify incoming requests:
```javascript
import { Webhook } from 'svix';
export async function POST(request) {
// Get the raw body as a string
const payload = await request.text();
// Get the Svix headers
const headers = {
'svix-id': request.headers.get('svix-id'),
'svix-timestamp': request.headers.get('svix-timestamp'),
'svix-signature': request.headers.get('svix-signature'),
};
// Create a new Webhook instance with your secret
const wh = new Webhook(process.env.SUPERWALL_WEBHOOK_SECRET);
let event;
try {
// Verify the webhook
event = wh.verify(payload, headers);
} catch (err) {
console.error('Webhook verification failed:', err.message);
return new Response('Webhook verification failed', { status: 400 });
}
// Webhook is verified - process the event
console.log('Verified event:', event);
// Process your event here
// ...
return new Response('Success', { status: 200 });
}
```
### Option 2: Manual Verification
If you prefer not to use the Svix library, you can manually verify webhooks using the HMAC signature:
```javascript
import crypto from 'crypto';
function verifyWebhook(payload, headers, secret) {
const msgId = headers['svix-id'];
const msgTimestamp = headers['svix-timestamp'];
const msgSignature = headers['svix-signature'];
// Verify timestamp to prevent replay attacks
const timestamp = parseInt(msgTimestamp, 10);
const now = Math.floor(Date.now() / 1000);
if (now - timestamp > 300) { // 5 minutes
throw new Error('Webhook timestamp too old');
}
// Create the signed content
const signedContent = `${msgId}.${msgTimestamp}.${payload}`;
// Compute the expected signature
const secretBytes = Buffer.from(secret.split('_')[1], 'base64');
const signature = crypto
.createHmac('sha256', secretBytes)
.update(signedContent)
.digest('base64');
// Compare signatures
const expectedSignature = `v1,${signature}`;
// Extract all signatures from the header
const passedSignatures = msgSignature.split(' ');
// Check if any signature matches
const signatureMatch = passedSignatures.some(sig =>
crypto.timingSafeEqual(
Buffer.from(sig),
Buffer.from(expectedSignature)
)
);
if (!signatureMatch) {
throw new Error('Webhook signature verification failed');
}
return JSON.parse(payload);
}
```
## Important Implementation Notes
### Use Raw Request Body
The signature is computed against the **raw request body**. Do not parse or modify the body before verification:
```javascript
// ✅ Correct - use raw body
const payload = await request.text();
const event = wh.verify(payload, headers);
// ❌ Wrong - parsing changes the body
const payload = await request.json();
const event = wh.verify(JSON.stringify(payload), headers); // Will fail!
```
### Required Headers
Three headers are required for verification:
| Header | Description |
| ---------------- | ---------------------------------------- |
| `svix-id` | Unique message ID |
| `svix-timestamp` | Unix timestamp when the webhook was sent |
| `svix-signature` | HMAC signature(s) of the message |
### Framework-Specific Examples
#### Next.js (App Router)
```javascript
// app/api/webhooks/route.js
import { Webhook } from 'svix';
export async function POST(request) {
const payload = await request.text();
const headers = {
'svix-id': request.headers.get('svix-id'),
'svix-timestamp': request.headers.get('svix-timestamp'),
'svix-signature': request.headers.get('svix-signature'),
};
const wh = new Webhook(process.env.SUPERWALL_WEBHOOK_SECRET);
try {
const event = wh.verify(payload, headers);
// Handle the event
switch (event.type) {
case 'initial_purchase':
// Handle initial purchase
break;
case 'renewal':
// Handle renewal
break;
// ... other event types
}
return new Response('Success', { status: 200 });
} catch (err) {
return new Response('Webhook verification failed', { status: 400 });
}
}
```
#### Express
```javascript
import express from 'express';
import { Webhook } from 'svix';
const app = express();
// Important: Use raw body for webhook verification
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
const payload = req.body.toString();
const headers = {
'svix-id': req.headers['svix-id'],
'svix-timestamp': req.headers['svix-timestamp'],
'svix-signature': req.headers['svix-signature'],
};
const wh = new Webhook(process.env.SUPERWALL_WEBHOOK_SECRET);
try {
const event = wh.verify(payload, headers);
// Handle the event
console.log('Verified event:', event);
res.status(200).send('Success');
} catch (err) {
console.error('Webhook verification failed:', err.message);
res.status(400).send('Verification failed');
}
});
```
#### Python (FastAPI)
```python
from fastapi import FastAPI, Request, HTTPException
from svix.webhooks import Webhook, WebhookVerificationError
import os
app = FastAPI()
@app.post("/webhooks")
async def handle_webhook(request: Request):
payload = await request.body()
headers = {
"svix-id": request.headers.get("svix-id"),
"svix-timestamp": request.headers.get("svix-timestamp"),
"svix-signature": request.headers.get("svix-signature"),
}
wh = Webhook(os.environ["SUPERWALL_WEBHOOK_SECRET"])
try:
event = wh.verify(payload, headers)
# Handle the event
print(f"Verified event: {event}")
return {"status": "success"}
except WebhookVerificationError as e:
print(f"Webhook verification failed: {e}")
raise HTTPException(status_code=400, detail="Verification failed")
```
## Testing Webhook Verification
During development, you can test webhook verification:
1. **Use the actual signing secret** from your webhook endpoint
2. **Capture real webhook payloads** by temporarily logging them
3. **Test with valid and invalid signatures** to ensure your verification works
Never test with production webhooks in a development environment without proper safeguards. Consider creating a separate webhook endpoint for testing.
## Security Best Practices
1. **Always verify webhooks** - Never process unverified webhook data
2. **Use environment variables** - Store your signing secret securely
3. **Check timestamps** - Reject old webhooks to prevent replay attacks (Svix does this automatically)
4. **Return 200 quickly** - Acknowledge receipt immediately, then process asynchronously
5. **Log verification failures** - Monitor for potential attacks or configuration issues
6. **Rotate secrets periodically** - Update your signing secret if it's ever compromised
## Troubleshooting
### Verification Always Fails
* Ensure you're using the **raw request body**, not a parsed/stringified version
* Check that all three required headers are present
* Verify you're using the correct signing secret for this webhook endpoint
* Make sure your secret includes the full value (it should start with `whsec_`)
### "Timestamp too old" Errors
* Your server's clock may be out of sync - verify your server time
* Network delays may be too high - check your server's response time
* The webhook may be a replay attack - this is working as intended
## Advanced Usage
For advanced webhook verification scenarios, including signature rotation and custom verification logic, see the [Svix documentation](https://docs.svix.com/receiving/verifying-payloads/how).
***
## Webhooks Reference
For information about webhook events, payload structure, and handling different event types, see the main [Webhooks documentation](/docs/integrations/webhooks).
In the **Webhooks** section within **Integrations**, you can manage your webhooks with Superwall:
---
# Verify Webhook Requests
Source: https://superwall.com/docs/integrations/webhooks-verify
Learn how to verify webhook requests using the signing secret to ensure authenticity and security.
## Why Verify Webhooks?
Verifying webhook requests is crucial for security. It ensures that:
* Requests are actually coming from Superwall's servers
* The payload hasn't been tampered with in transit
* Replay attacks are prevented through timestamp validation
Without verification, malicious actors could send fake webhook events to your endpoint.
## Getting Your Signing Secret
Every webhook endpoint has a unique signing secret that's used to verify requests. You can find this secret in your webhook details:

Click the **Copy Secret** button to copy your webhook's signing secret to your clipboard.
Keep your signing secret secure. Never commit it to version control or expose it in client-side code. Store it as an environment variable like `SUPERWALL_WEBHOOK_SECRET`.
## Verification Methods
### Option 1: Using Svix Library (Recommended)
Superwall uses [Svix](https://svix.com) for webhook delivery, which provides robust verification libraries for multiple languages.
Install the Svix library:
```bash
npm install svix
# or
yarn add svix
# or
pnpm add svix
```
Verify incoming requests:
```javascript
import { Webhook } from 'svix';
export async function POST(request) {
// Get the raw body as a string
const payload = await request.text();
// Get the Svix headers
const headers = {
'svix-id': request.headers.get('svix-id'),
'svix-timestamp': request.headers.get('svix-timestamp'),
'svix-signature': request.headers.get('svix-signature'),
};
// Create a new Webhook instance with your secret
const wh = new Webhook(process.env.SUPERWALL_WEBHOOK_SECRET);
let event;
try {
// Verify the webhook
event = wh.verify(payload, headers);
} catch (err) {
console.error('Webhook verification failed:', err.message);
return new Response('Webhook verification failed', { status: 400 });
}
// Webhook is verified - process the event
console.log('Verified event:', event);
// Process your event here
// ...
return new Response('Success', { status: 200 });
}
```
### Option 2: Manual Verification
If you prefer not to use the Svix library, you can manually verify webhooks using the HMAC signature:
```javascript
import crypto from 'crypto';
function verifyWebhook(payload, headers, secret) {
const msgId = headers['svix-id'];
const msgTimestamp = headers['svix-timestamp'];
const msgSignature = headers['svix-signature'];
// Verify timestamp to prevent replay attacks
const timestamp = parseInt(msgTimestamp, 10);
const now = Math.floor(Date.now() / 1000);
if (now - timestamp > 300) { // 5 minutes
throw new Error('Webhook timestamp too old');
}
// Create the signed content
const signedContent = `${msgId}.${msgTimestamp}.${payload}`;
// Compute the expected signature
const secretBytes = Buffer.from(secret.split('_')[1], 'base64');
const signature = crypto
.createHmac('sha256', secretBytes)
.update(signedContent)
.digest('base64');
// Compare signatures
const expectedSignature = `v1,${signature}`;
// Extract all signatures from the header
const passedSignatures = msgSignature.split(' ');
// Check if any signature matches
const signatureMatch = passedSignatures.some(sig =>
crypto.timingSafeEqual(
Buffer.from(sig),
Buffer.from(expectedSignature)
)
);
if (!signatureMatch) {
throw new Error('Webhook signature verification failed');
}
return JSON.parse(payload);
}
```
## Important Implementation Notes
### Use Raw Request Body
The signature is computed against the **raw request body**. Do not parse or modify the body before verification:
```javascript
// ✅ Correct - use raw body
const payload = await request.text();
const event = wh.verify(payload, headers);
// ❌ Wrong - parsing changes the body
const payload = await request.json();
const event = wh.verify(JSON.stringify(payload), headers); // Will fail!
```
### Required Headers
Three headers are required for verification:
| Header | Description |
| ---------------- | ---------------------------------------- |
| `svix-id` | Unique message ID |
| `svix-timestamp` | Unix timestamp when the webhook was sent |
| `svix-signature` | HMAC signature(s) of the message |
### Framework-Specific Examples
#### Next.js (App Router)
```javascript
// app/api/webhooks/route.js
import { Webhook } from 'svix';
export async function POST(request) {
const payload = await request.text();
const headers = {
'svix-id': request.headers.get('svix-id'),
'svix-timestamp': request.headers.get('svix-timestamp'),
'svix-signature': request.headers.get('svix-signature'),
};
const wh = new Webhook(process.env.SUPERWALL_WEBHOOK_SECRET);
try {
const event = wh.verify(payload, headers);
// Handle the event
switch (event.type) {
case 'initial_purchase':
// Handle initial purchase
break;
case 'renewal':
// Handle renewal
break;
// ... other event types
}
return new Response('Success', { status: 200 });
} catch (err) {
return new Response('Webhook verification failed', { status: 400 });
}
}
```
#### Express
```javascript
import express from 'express';
import { Webhook } from 'svix';
const app = express();
// Important: Use raw body for webhook verification
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
const payload = req.body.toString();
const headers = {
'svix-id': req.headers['svix-id'],
'svix-timestamp': req.headers['svix-timestamp'],
'svix-signature': req.headers['svix-signature'],
};
const wh = new Webhook(process.env.SUPERWALL_WEBHOOK_SECRET);
try {
const event = wh.verify(payload, headers);
// Handle the event
console.log('Verified event:', event);
res.status(200).send('Success');
} catch (err) {
console.error('Webhook verification failed:', err.message);
res.status(400).send('Verification failed');
}
});
```
#### Python (FastAPI)
```python
from fastapi import FastAPI, Request, HTTPException
from svix.webhooks import Webhook, WebhookVerificationError
import os
app = FastAPI()
@app.post("/webhooks")
async def handle_webhook(request: Request):
payload = await request.body()
headers = {
"svix-id": request.headers.get("svix-id"),
"svix-timestamp": request.headers.get("svix-timestamp"),
"svix-signature": request.headers.get("svix-signature"),
}
wh = Webhook(os.environ["SUPERWALL_WEBHOOK_SECRET"])
try:
event = wh.verify(payload, headers)
# Handle the event
print(f"Verified event: {event}")
return {"status": "success"}
except WebhookVerificationError as e:
print(f"Webhook verification failed: {e}")
raise HTTPException(status_code=400, detail="Verification failed")
```
## Testing Webhook Verification
During development, you can test webhook verification:
1. **Use the actual signing secret** from your webhook endpoint
2. **Capture real webhook payloads** by temporarily logging them
3. **Test with valid and invalid signatures** to ensure your verification works
Never test with production webhooks in a development environment without proper safeguards. Consider creating a separate webhook endpoint for testing.
## Security Best Practices
1. **Always verify webhooks** - Never process unverified webhook data
2. **Use environment variables** - Store your signing secret securely
3. **Check timestamps** - Reject old webhooks to prevent replay attacks (Svix does this automatically)
4. **Return 200 quickly** - Acknowledge receipt immediately, then process asynchronously
5. **Log verification failures** - Monitor for potential attacks or configuration issues
6. **Rotate secrets periodically** - Update your signing secret if it's ever compromised
## Troubleshooting
### Verification Always Fails
* Ensure you're using the **raw request body**, not a parsed/stringified version
* Check that all three required headers are present
* Verify you're using the correct signing secret for this webhook endpoint
* Make sure your secret includes the full value (it should start with `whsec_`)
### "Timestamp too old" Errors
* Your server's clock may be out of sync - verify your server time
* Network delays may be too high - check your server's response time
* The webhook may be a replay attack - this is working as intended
## Advanced Usage
For advanced webhook verification scenarios, including signature rotation and custom verification logic, see the [Svix documentation](https://docs.svix.com/receiving/verifying-payloads/how).