> ## Documentation Index
> Fetch the complete documentation index at: https://docs.taap.it/llms.txt
> Use this file to discover all available pages before exploring further.

# Stripe

> Automatic conversion tracking for Stripe payments

import { Steps, Step } from "fumadocs-ui/components/steps";

The Taapit Stripe integration automatically tracks all your Stripe payments as sales conversions. Just install the SDK, connect the app, and pass the tracking ID to Stripe.

## How it works

<Frame>
  <img src="https://mintcdn.com/taapit/XwQ3OGJ9I1yOhz_n/images/stripe/visual_stripe.png?fit=max&auto=format&n=XwQ3OGJ9I1yOhz_n&q=85&s=6a1c649a8da4ac430559a2b8b0b4ad59" alt="Taapit Visual Stripe integration" width="1664" height="822" data-path="images/stripe/visual_stripe.png" />
</Frame>

## Prerequisites

<Warning>
  **Important**: For conversion tracking to work, users must arrive on your
  website via a **Taapit deeplink**. This is how the tracking ID (`ta_tid`) is
  generated and passed to your site.
</Warning>

Before you start:

1. **Create a Taapit deeplink** pointing to your website or landing page
2. **Enable conversion tracking** on your link:
   * Go to your link settings in the Taapit dashboard
   * Enable **Conversion Tracking**
3. **Configure Stripe integration** in [Settings → Conversion](https://taap.it/dashboard/settings/conversion) and select **Stripe Integration**

```mermaid theme={null}
flowchart LR
    A[User clicks Taapit link] --> B[Lands on your site with ta_tid]
    B --> C[SDK stores ta_tid in cookie]
    C --> D[User makes purchase]
    D --> E[ta_tid sent to Stripe]
    E --> F[Taapit tracks conversion]
```

## Installation

<Steps>
  <Step title="Install the Taapit SDK on your website">
    First, add the Taapit SDK to your website to capture the `ta_tid` tracking ID:

    <Tabs>
      <Tab title="NPM Package (React/Next.js)">
        ```bash theme={null}
        npm install taapit-sdk
        ```

        Then add the Analytics component to your root layout:

        ```tsx app/layout.tsx theme={null}
        import { Analytics } from 'taapit-sdk/react';

        export default function RootLayout({ children }) {
          return (
            <html>
              <body>
                {children}
                <Analytics />
              </body>
            </html>
          );
        }
        ```
      </Tab>

      <Tab title="Script Tag (No Build Step)">
        Add this script to your HTML `<head>` or before `</body>`:

        ```html theme={null}
        <script src="https://taap.it/api/sdk"></script>
        ```
      </Tab>
    </Tabs>

    <Warning>
      This step is **required**. Without the SDK, the `ta_tid` won't be captured and conversions can't be tracked.
    </Warning>
  </Step>

  <Step title="Install the Stripe App">
    1. Go to the [Stripe App Marketplace](https://marketplace.stripe.com/)
    2. Search for "Taapit Conversion"
    3. Click **Install**

    Or install directly from your Taapit dashboard:

    1. Go to **Settings** → **Integrations** → **Stripe**
    2. Click **Install Stripe Integration**
  </Step>

  <Step title="Connect your Taapit workspace">
    After installing the app in Stripe:

    **1. Open the Taapit app in your Stripe dashboard and click "Connect workspace"**

    <Frame>
      <img src="https://mintcdn.com/taapit/XwQ3OGJ9I1yOhz_n/images/stripe/stripe_step_1.png?fit=max&auto=format&n=XwQ3OGJ9I1yOhz_n&q=85&s=87165680c99692d69fd0062576cb9535" alt="Taapit Stripe App - Connect workspace button" width="449" height="459" data-path="images/stripe/stripe_step_1.png" />
    </Frame>

    **2. Authorize the connection to your Taapit workspace**

    You will be redirected to the Taapit consent page. Select the workspace you want to connect and click **Authorize**.

    <Frame>
      <img src="https://mintcdn.com/taapit/XwQ3OGJ9I1yOhz_n/images/stripe/stripe_step_2.png?fit=max&auto=format&n=XwQ3OGJ9I1yOhz_n&q=85&s=14184e9557fcf077807847c9c46b6794" alt="Taapit consent page" width="835" height="812" data-path="images/stripe/stripe_step_2.png" />
    </Frame>

    **3. Verify the workspace is connected**

    Once authorized, you will see your workspace connected in the Stripe app.

    <Frame>
      <img src="https://mintcdn.com/taapit/XwQ3OGJ9I1yOhz_n/images/stripe/stripe_step_3.png?fit=max&auto=format&n=XwQ3OGJ9I1yOhz_n&q=85&s=70c0a960fe296ef6daa5b5dee7d43af2" alt="Taapit Stripe App - Workspace connected" width="498" height="226" data-path="images/stripe/stripe_step_3.png" />
    </Frame>
  </Step>

  <Step title="Pass the tracking ID to Stripe">
    Pass the `ta_tid` to Stripe when creating customers, checkout sessions, or payment intents.

    ### 1. Frontend: Get the tracking ID

    First, retrieve the tracking ID from your frontend to pass it to your API:

    <Tabs>
      <Tab title="With Taapit SDK">
        ```typescript theme={null}
        // Using the taapit global object (script tag)
        const trackingId = taapit.getTrackingId();
        ```
      </Tab>

      <Tab title="With React Hook">
        ```tsx theme={null}
        import { useTaapitAnalytics } from 'taapit-sdk/react';

        function CheckoutButton() {
          const { trackingId } = useTaapitAnalytics();

          const handleCheckout = async () => {
            const response = await fetch('/api/create-checkout', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                priceId: 'price_xxx',
                trackingId,
              }),
            });
            const { url } = await response.json();
            window.location.href = url;
          };

          return <button onClick={handleCheckout}>Subscribe</button>;
        }
        ```
      </Tab>

      <Tab title="From Cookie directly">
        ```typescript theme={null}
        // Read directly from cookie
        const trackingId = document.cookie
          .split('; ')
          .find(row => row.startsWith('ta_tid='))
          ?.split('=')[1];
        ```
      </Tab>
    </Tabs>

    <Info>
      The tracking ID can be retrieved from:

      1. **Taapit SDK** - `taapit.getTrackingId()` or `useTaapitAnalytics()` hook
      2. **Cookie** (`ta_tid`) - automatically set by the SDK

      The backend should check both the request body and cookies for maximum compatibility.
    </Info>

    ***

    ### 2. Track Sales: Create a Checkout Session

    When a user makes a purchase, pass the tracking ID in the checkout session metadata.

    <Info>
      **When is `taapitTrackingId` required for Checkout Sessions?**

      * If the customer was **already tracked via a lead event** (using `taapitCustomerExternalId`), the `taapitTrackingId` is **optional** - you only need to pass `taapitCustomerExternalId` to link the sale.
      * If this is a **new customer** (no prior lead), `taapitTrackingId` is **required** to attribute the sale.
    </Info>

    ```typescript app/api/create-checkout/route.ts theme={null}
    import { NextRequest } from 'next/server';
    import Stripe from 'stripe';

    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

    export async function POST(request: NextRequest) {
      const body = await request.json();
      const { priceId, customerExternalId } = body;

      // Get tracking ID from cookie OR from request body
      // Optional if customer already tracked via lead
      const trackingId =
        request.cookies.get('ta_tid')?.value ||
        body.trackingId ||
        '';

      const session = await stripe.checkout.sessions.create({
        mode: 'subscription',
        line_items: [{ price: priceId, quantity: 1 }],
        success_url: 'https://yoursite.com/success',
        cancel_url: 'https://yoursite.com/cancel',
        // Pass tracking ID and customer ID in metadata
        metadata: {
          taapitTrackingId: trackingId, // Optional if customer exists
          taapitCustomerExternalId: customerExternalId, // Required
        },
        // Also in subscription_data for subscriptions
        subscription_data: {
          metadata: {
            taapitTrackingId: trackingId,
            taapitCustomerExternalId: customerExternalId,
          },
        },
      });

      return Response.json({ url: session.url });
    }
    ```

    ***

    ### 3. (Optional) Track Leads: Create a Stripe Customer

    If you want to track leads separately from sales, create a Stripe customer with the tracking ID when a user signs up. Taapit listens to the `customer.created` webhook.

    ```typescript app/api/stripe/create-customer/route.ts theme={null}
    import { NextRequest } from 'next/server';
    import Stripe from 'stripe';

    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

    export async function POST(request: NextRequest) {
      const body = await request.json();
      const { email, name, externalId } = body;

      // Get tracking ID from cookie OR from request body
      const trackingId =
        request.cookies.get('ta_tid')?.value ||
        body.trackingId ||
        '';

      // Create Stripe customer with Taapit metadata
      const customer = await stripe.customers.create({
        email,
        name,
        metadata: {
          taapitTrackingId: trackingId,
          taapitCustomerExternalId: externalId, // Your internal user ID
        },
      });

      return Response.json({ customerId: customer.id });
    }
    ```

    <Info>
      This step is **optional**. Use it if you want to track user signups as leads before they make a purchase.
    </Info>

    ***

    ### 4. (Alternative) Using Stripe Payment Links

    If you're using [Stripe Payment Links](https://stripe.com/docs/payment-links), you can track sales automatically without writing any backend code.

    <Warning>
      With Payment Links, only **sale events** are tracked. Lead webhooks are not created.
    </Warning>

    **How to set it up:**

    1. Get your Stripe Payment Link URL (e.g., `https://buy.stripe.com/xxx`)
    2. Add `?taapit_client_reference_id=1` to the URL:
       ```
       https://buy.stripe.com/xxx?taapit_client_reference_id=1
       ```
    3. Shorten this URL with Taapit

    **How it works:**

    When a user clicks on your Taapit deeplink, Taapit automatically:

    1. Replaces `taapit_client_reference_id=1` with `client_reference_id=taapit_tid_{trackingId}`
    2. Stripe receives the tracking ID as `client_reference_id`
    3. When checkout completes, Taapit attributes the sale to the original click
  </Step>

  <Step title="Verify the connection">
    1. Go to **Settings** → **Integrations** → **Stripe** in Taapit
    2. You should see **Connected** status
    3. Make a test payment
    4. Check the **Analytics** tab for the conversion
  </Step>
</Steps>

## Tracked Events

The Stripe integration automatically tracks these events:

| Stripe Event                 | Taapit Event | Description                             |
| ---------------------------- | ------------ | --------------------------------------- |
| `customer.created`           | Lead         | Customer created with tracking metadata |
| `checkout.session.completed` | Sale         | Checkout session completed              |
| `invoice.paid`               | Sale         | Subscription invoice paid               |

## Metadata Fields

The integration looks for these metadata fields on Stripe objects:

| Field                      | Required  | Description                                |
| -------------------------- | --------- | ------------------------------------------ |
| `taapitTrackingId`         | See below | The tracking ID (`ta_tid` from the cookie) |
| `taapitCustomerExternalId` | Yes       | Your internal user ID                      |

<Info>
  Use `taapitTrackingId` (not `ta_tid`) in Stripe metadata. The `ta_tid` is the
  cookie name, while `taapitTrackingId` is the metadata field name.
</Info>

<Info>
  **When is `taapitTrackingId` required?** - **Lead events**
  (`customer.created`): `taapitTrackingId` is **always required** - **Sale
  events** (`checkout.session.completed`, `invoice.paid`): - If the customer was
  **already tracked via a lead event** (using `taapitCustomerExternalId`), the
  `taapitTrackingId` is **optional** - you only need the
  `taapitCustomerExternalId` - If this is a **new customer** (no prior lead),
  `taapitTrackingId` is **required** to attribute the sale
</Info>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Conversions not appearing">
    1. **Check metadata**: Ensure `taapitTrackingId` is in your Stripe metadata
    2. **Verify webhook delivery**: In Stripe → Developers → Webhooks 3. **Check
       connection**: Settings → Integrations → Stripe should show "Connected"
  </Accordion>

  <Accordion title="Tracking ID missing">
    If the tracking ID is empty, the user either: - Didn't come from a Taapit
    link - Has cookies blocked - Cookie wasn't passed to checkout This is normal
    for organic/direct traffic.
  </Accordion>
</AccordionGroup>

## Security

| Permission              | Purpose                        |
| ----------------------- | ------------------------------ |
| `customer_read`         | Read customer information      |
| `subscription_read`     | Read subscription data         |
| `invoice_read`          | Read invoice amounts           |
| `checkout_session_read` | Read checkout session metadata |
| `webhook_read`          | Receive payment events         |

## FAQ

<AccordionGroup>
  <Accordion title="Do I need to install the SDK?">
    Yes, you need the Taapit SDK on your website to capture the `ta_tid` cookie.
    The Stripe app only handles payment tracking.
  </Accordion>

  {" "}

  <Accordion title="How are subscription renewals handled?">
    Each `invoice.paid` event triggers a sale. The tracking ID from the original
    checkout is used for attribution.
  </Accordion>

  <Accordion title="What about refunds?">
    Currently, refunds are not automatically tracked. We're working on this
    feature.
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Shopify Integration" icon="shopify" href="/conversions/automatic/shopify">
    Set up automatic tracking for Shopify stores.
  </Card>

  <Card title="Manual Integration" icon="code" href="/conversions/manual/server-side">
    For custom payment flows.
  </Card>
</CardGroup>
