Guides & Tutorials10 min read

Build Stripe to CRM Revenue Attribution with OpenClaw workflow automation

By Alex Moran

TL;DR

This guide shows how to connect Stripe events to your CRM using OpenClaw workflow automation so finance and sales share a single source of truth for revenue. You will build a resilient server side pipeline that ingests webhooks, maps fields, upserts contacts and deals, and handles retries with a dead letter queue. The tutorial includes an end to end playbook with typed schemas, idempotency, and an approval gate for production cutover. If you follow the steps, you can go from a test charge to a linked CRM opportunity in under an hour.

What you will build

You will assemble a practical automation workflow that listens to Stripe webhooks, transforms them into normalized transaction records, and writes those records to either HubSpot or Salesforce using one shared playbook. The pipeline supports idempotent upserts, configurable product to SKU mapping, and optional attribution to campaigns when UTM parameters are present.

The tutorial assumes familiarity with OpenClaw basics. If you want an overview of what the product offers, see the page that summarizes the AI marketing automation features. You can also learn more about ButterGrow as the hosted OpenClaw assistant if you prefer a managed setup.

Prerequisites

  • An active Stripe account with test mode enabled.
  • Access to either a HubSpot sandbox or a Salesforce developer org.
  • OpenClaw workspace with permission to create connectors and playbooks.
  • The CLI or UI access to configure secrets and deploy runners.
  • Optional but recommended: a campaign parameter capture that you can pipe into this build. For a primer, review the related server side UTM attribution guide.

If you are brand new to the platform, walk through get started in minutes to set up your first agent and runner. The onboarding flow covers basic environment and secret management.

Architecture at a glance

The flow is simple.

  • Stripe emits a webhook for payment and subscription lifecycle events.
  • An OpenClaw HTTP listener receives the event, validates the signature, and canonicalizes the payload into a Transaction object.
  • The playbook enriches the record with product metadata and optional UTM context.
  • The pipeline upserts a Contact and a Deal or Opportunity in your CRM, then links them.
  • Retries are controlled with exponential backoff. Irrecoverable failures go to a DLQ for manual replay.

Here is the minimal schema we will use during transforms.

# schemas/Transaction.yaml
name: Transaction
version: 1
fields:
  - name: event_id
    type: string
  - name: customer_email
    type: string
  - name: stripe_customer_id
    type: string
  - name: amount_cents
    type: integer
  - name: currency
    type: string
  - name: product_code
    type: string
  - name: livemode
    type: boolean
  - name: utm
    type: object
  - name: occurred_at
    type: datetime

A small mapping table will help us route events.

Stripe event When to process Notes
payment_intent.succeeded One time payments Use to create or move wins to Closed Won.
invoice.paid Subscription invoices Update recurring revenue, roll up to latest period.
customer.subscription.created New subscriptions Open a new opportunity at qualification.

Configure connectors and secrets

We will declare three connectors. One is the Stripe webhook listener, the others are the CRM writers. Secrets are read from environment variables or the OpenClaw secret vault.

# connectors/stripe-listener.yaml
kind: connector
name: stripe_webhook
spec:
  type: http
  path: /webhooks/stripe
  auth:
    type: stripe_signature
    header: Stripe-Signature
    secret: ${STRIPE_SIGNING_SECRET}
# connectors/hubspot.yaml
kind: connector
name: hubspot
spec:
  type: hubspot
  auth:
    type: oauth2
    secret: ${HUBSPOT_OAUTH_SECRET}
# connectors/salesforce.yaml
kind: connector
name: salesforce
spec:
  type: salesforce
  auth:
    type: oauth2
    secret: ${SALESFORCE_OAUTH_SECRET}

Keep sandbox and production secrets separate. Route based on the livemode flag from Stripe to avoid accidental writes.

The playbook

We will define a typed playbook with preflight checks, policy gates, and explicit error handling.

# playbooks/stripe_to_crm.yaml
kind: playbook
name: stripe_to_crm
vars:
  crm_target: "hubspot"   # hubspot or salesforce
  allow_test_mode: true
sources:
  - from: connector.stripe_webhook
    as: stripe_event
preflight:
  - name: signature_present
    check: $.headers['Stripe-Signature'] != null
  - name: livemode_allowed
    check: $.body.livemode == true || vars.allow_test_mode == true
steps:
  - name: canonicalize
    run: transform
    input:
      event: $.body
    code: |
      function canonicalize(event) {
        const base = {
          event_id: event.id,
          customer_email: event.data?.object?.customer_email || event.data?.object?.customer_details?.email || event.data?.object?.email,
          stripe_customer_id: event.data?.object?.customer || null,
          amount_cents: event.data?.object?.amount_received || event.data?.object?.amount_paid || 0,
          currency: event.data?.object?.currency || 'usd',
          product_code: event.data?.object?.metadata?.product_code || 'unknown',
          livemode: event.livemode === true,
          utm: event.data?.object?.metadata?.utm ? JSON.parse(event.data.object.metadata.utm) : {},
          occurred_at: event.created ? new Date(event.created * 1000).toISOString() : new Date().toISOString()
        };
        return base;
      }
      output = canonicalize(input.event);
  - name: route_crm
    when: vars.crm_target == 'hubspot'
    run: call
    input:
      connector: connector.hubspot
      function: upsert
      payload: ${steps.canonicalize.output}
  - name: route_crm_sf
    when: vars.crm_target == 'salesforce'
    run: call
    input:
      connector: connector.salesforce
      function: upsert
      payload: ${steps.canonicalize.output}
  - name: link_entities
    run: transform
    input:
      record: ${steps.canonicalize.output}
    code: |
      // This step can call either CRM to attach the deal to the contact
      output = input.record;
retry:
  policy:
    type: exponential
    base_ms: 500
    max_attempts: 6
    max_ms: 30000
  idempotency_key: ${steps.canonicalize.output.event_id}
  dlq:
    name: stripe_to_crm_dlq
    retention_days: 14
approvals:
  - name: production_cutover
    when: $.vars.allow_test_mode == false
    required: true

This playbook uses a single transform to output our Transaction schema and a branching step that calls the appropriate CRM connector. The idempotency_key ensures that reprocessing an already handled event does not create duplicates. The approval gate prevents accidental production writes until you flip the variable.

Mapping fields to HubSpot and Salesforce

We will implement thin adapters that translate the Transaction object to each CRM. Here are reference mappings.

HubSpot contact and deal mappings

# adapters/hubspot.yaml
contact:
  match:
    - property: email
      value: $.customer_email
  upsert:
    email: $.customer_email
    lifecyclestage: "customer"
    stripe_customer_id: $.stripe_customer_id
    last_payment_at: $.occurred_at

deal:
  match:
    - property: hs_unique_id
      value: $.event_id
  upsert:
    dealname: "Stripe payment ${$.event_id}"
    amount: ${$.amount_cents / 100}
    currency: $.currency
    closedate: $.occurred_at
    pipeline: "Sales Pipeline"
    dealstage: "closedwon"
    hs_unique_id: $.event_id
    product_code: $.product_code
    utm_source: $.utm.source
    utm_campaign: $.utm.campaign
link:
  contact_to_deal:
    association_type: "deal_to_contact"

Salesforce contact and opportunity mappings

# adapters/salesforce.yaml
contact:
  match:
    - field: Email
      value: $.customer_email
  upsert:
    Email: $.customer_email
    Stripe_Customer_ID__c: $.stripe_customer_id
    Last_Payment_At__c: $.occurred_at

opportunity:
  match:
    - field: External_Id__c
      value: $.event_id
  upsert:
    Name: "Stripe payment ${$.event_id}"
    Amount: ${$.amount_cents / 100}
    CloseDate: $.occurred_at
    StageName: "Closed Won"
    CurrencyIsoCode: $.currency.toUpperCase()
    External_Id__c: $.event_id
    Product_Code__c: $.product_code
    UTM_Source__c: $.utm.source
    UTM_Campaign__c: $.utm.campaign
link:
  contact_to_opportunity:
    field: Primary_Contact__c

These adapters are expressed as YAML for readability. In production you can implement them as small functions or templates in whichever language you deploy inside OpenClaw.

Handle idempotency and duplicates

Stripe guarantees that a webhook can be delivered more than once. Use the Stripe event id as your idempotency key. The playbook configuration already applies it to retries. Your adapters should also set a unique property on the CRM object, such as hs_unique_id on HubSpot deals or an External_Id__c field on Salesforce opportunities, so that an upsert is matched deterministically.

Step 1Create a Stripe webhook endpoint

Create a webhook in Stripe that points to the listener path you configured. Choose the relevant events for your use case. For one time charges, select payment_intent.succeeded. For subscriptions, add invoice.paid and customer.subscription.created.

Use the CLI to test locally.

stripe listen --forward-to localhost:8080/webhooks/stripe
stripe trigger payment_intent.succeeded

Set the signing secret as STRIPE_SIGNING_SECRET in your OpenClaw environment. This is required to verify incoming payloads.

Step 2Validate and canonicalize payloads

Add a lightweight validator so only the expected events make it through. The transform in the playbook emits a compact Transaction record with only the fields that your CRM needs. This reduces downstream coupling and simplifies testing.

If you want deeper safety, add a JSON Schema check.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Transaction",
  "type": "object",
  "required": ["event_id", "amount_cents", "currency"],
  "properties": {
    "event_id": {"type": "string"},
    "amount_cents": {"type": "integer", "minimum": 0},
    "currency": {"type": "string"}
  }
}

Step 3Branch to the selected CRM

Parameterize the target CRM with a playbook variable. In non production builds, start with HubSpot for convenience. The branching steps in the playbook call the right connector and pass the same Transaction payload to the adapter.

Step 4Upsert contact then deal or opportunity

Always upsert the person record first so later reporting can join revenue to a known identity. Use the email from Stripe events if available. If the email is missing and you only have a customer id, you may need to query Stripe for the customer object before continuing. Attach deals or opportunities to the contact using the association patterns provided by the CRM.

Step 5Add product metadata

Stripe events often carry custom metadata. A simple metadata field like product_code lets you drive CRM picklists without extra lookups. For more elaborate catalogs, maintain a small mapping file checked into your repo.

# config/product-codes.yaml
BGROW_STARTER: { price: 2900, name: "ButterGrow Starter" }
BGROW_PRO: { price: 9900, name: "ButterGrow Pro" }
BGROW_ENTERPRISE: { price: 24900, name: "ButterGrow Enterprise" }

Step 6Capture campaign context

If your site stores UTM parameters on checkout, pass them into Stripe metadata. The adapter then moves them into CRM fields so you can build reports that show which campaign drove revenue. For a deeper walkthrough of capturing parameters in your backend, see our server side UTM attribution guide.

Step 7Implement retries with a DLQ

Transient failures happen. Enable exponential backoff in the playbook and send exhausted messages to a named DLQ. Build a small replay tool that pops a record by event id, revalidates the signature and schema, then re enqueues it to the listener.

// tools/replay.js
import fs from 'node:fs'
import { enqueue } from './queue.js'
const id = process.argv[2]
const rec = JSON.parse(fs.readFileSync(`dlq/${id}.json`, 'utf8'))
await enqueue('/webhooks/stripe', rec)
console.log(`Replayed ${id}`)

Guard the replay with access controls and audit logs. Only allow on call operators to run it.

Step 8Approvals and cutover

Before you write to production, add a simple approval gate. The provided playbook pauses when allow_test_mode is false and waits for a human to approve the change. Use this to confirm field mappings and pipeline readiness.

Step 9Test the entire flow

Use Stripe test mode to simulate realistic payment flows. Here is a minimal checkout to trigger the flow end to end. This example is deliberately small so you can drop it into a sandbox.

// server.js
import express from 'express'
import Stripe from 'stripe'
const app = express()
app.use(express.json())
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)
app.post('/pay', async (req, res) => {
  const pi = await stripe.paymentIntents.create({
    amount: 2000,
    currency: 'usd',
    metadata: {
      product_code: 'BGROW_STARTER',
      utm: JSON.stringify({ source: 'newsletter', campaign: 'november-launch' })
    }
  })
  res.json({ client_secret: pi.client_secret })
})
app.listen(3000)

Trigger the webhook using the Stripe CLI. Confirm that a contact and deal or opportunity are created and associated in your CRM. Verify that the unique id fields are present so future retries do not create duplicates.

Step 10Monitoring and alerts

Add basic counters and traces so you can answer three questions within seconds. How many events arrived, how many succeeded, and which ones failed last. A simple dashboard fed by logs from each playbook step is enough for day one. Over time you can add latency percentiles per step and a policy that pages on sustained failure rates.

Cost and limits

Watch the API quotas in your CRM and plan for bursts. Salesforce has per user and per org caps. HubSpot has per app limits. Stripe will resend a webhook until it receives a 2xx response. Your listeners should return quickly and push heavy transforms to background steps if you start to see timeouts.

Troubleshooting checklist

  • A payment event arrived but no CRM objects were created. Check preflight checks and confirm that the livemode rule allowed the event. Confirm that the signature header matches your secret.
  • Duplicate deals appeared. Ensure the external id fields are set and that your upsert matches include them. Verify that idempotency keys are applied in both the playbook and the adapter layer.
  • Events with missing emails fail. Use the Stripe API to fetch the customer object and retrieve contact information, then retry from the DLQ.

A broader tour of capabilities is available in the page that outlines the feature set. If you need more patterns, browse more from the ButterGrow blog and follow the sections that cover integrations and reliability.

A final note on future extensions. You can expand the same agentic workflow to include refunds, disputes, and subscription cancellations. You can also add budget guardrails that stop writing to the CRM if error rates spike. You may eventually route high value invoices to an approval stage in Slack before closing a deal.

Use this tutorial as a base and integrate it with your broader automation pipeline.

ButterGrow can host this build for you as a managed OpenClaw deployment. If you want the quickest path from a Stripe test charge to a CRM record, use the onboarding flow to get started in minutes and then connect the Stripe, HubSpot, or Salesforce modules in the same workspace.

References

Frequently Asked Questions

How do I map Stripe events to HubSpot deals without duplicates?+

Use the Stripe event id as the idempotency key and store it in a custom property on the HubSpot deal. Upserts should match on that property to prevent creating multiple deals for the same payment event.

What is the safest way to retry failed CRM writes from OpenClaw?+

Enable exponential backoff with a capped retry count and a dead letter queue. Persist the last successful step to allow partial replays, and expose a manual replay action that reprocesses a single event from the DLQ.

How can I test the pipeline without hitting production CRM data?+

Create a sandbox workspace in your CRM and use Stripe test mode. Use separate OpenClaw secrets for the sandbox and add a routing rule that directs test webhooks to the sandbox connectors based on the Stripe livemode flag.

How do I link a Stripe customer to an existing CRM contact?+

First try a lookup by customer email captured from the Stripe event. If multiple contacts match, prefer the one with the most recent activity. If no contact is found, create a new contact with a source field set to Stripe and store the Stripe customer id for future joins.

What Stripe events are best for revenue attribution to opportunities?+

For one time payments use payment_intent.succeeded and charge.succeeded to confirm settled revenue. For subscriptions use invoice.paid and customer.subscription.created to open and then update opportunity stages as invoices post.

How do I support both HubSpot and Salesforce from one playbook?+

Parameterize the CRM target in a playbook variable and branch on that value inside the mapping step. Keep shared transforms in a single function and define thin adapters that call the right CRM connector with the proper field names.

Ready to try ButterGrow?

See how ButterGrow can supercharge your growth with a quick demo.

Book a Demo