.do
DesignBusiness-as-Code

Platform Integration

Connect your Business-as-Code with external services and the .do platform

Learn how to integrate your Business-as-Code with external services, the .do platform components, and build a cohesive business ecosystem.

Platform Components

Database Integration

Connect to the platform's semantic database:

import { db } from 'sdk.do'

// The db primitive integrates with platform's Payload CMS
const businesses = await db.list($.Business, {
  where: { status: 'active' },
  limit: 100,
})

// Relationships are automatically resolved
const brands = await db.related(business, $.owns, $.Brand)
const employees = await db.related(business, $.employs, $.Person)

// Full-text search across collections
const results = await db.search({
  query: 'artificial intelligence',
  collections: [$.Article, $.Product, $.Organization],
})

// Semantic queries using GraphDL patterns
const techCompanies = await db.query({
  pattern: $.Organization.industry.Technology,
  where: { foundedDate: { $gte: new Date('2020-01-01') } },
})

AI Services Integration

Leverage platform AI capabilities:

import { ai } from 'sdk.do'

// Text generation with semantic schemas
const article = await ai.generate({
  prompt: 'Write about Business-as-Code',
  schema: $.BlogPosting,
  model: 'claude-sonnet-4.5',
  context: {
    audience: 'developers',
    tone: 'technical',
    length: 'medium',
  },
})

// Structured data extraction
const entities = await ai.extract({
  text: documentText,
  schema: $.Organization,
  model: 'gpt-5',
})

// Semantic embeddings for search
const embedding = await ai.embed('Autonomous business operations', { model: 'text-embedding-3-large' })

// Batch processing for efficiency
const results = await ai.batch([
  { prompt: 'Summarize Q1 results', schema: $.Report },
  { prompt: 'Generate social posts', schema: $.SocialMediaPosting },
  { prompt: 'Draft email campaign', schema: $.EmailMessage },
])

// Multi-modal capabilities
const analysis = await ai.analyze({
  image: imageUrl,
  prompt: 'Describe this product',
  schema: $.Product,
})

Event System Integration

Integrate with the platform's event bus:

import { on, send } from 'sdk.do'

// Listen to platform events
on($.User.authenticated, async (user) => {
  await send($.Analytics.track, {
    event: 'user_login',
    user: user.id,
  })
})

// Cross-service communication
on($.Order.created.in('ecommerce'), async (order) => {
  // Trigger fulfillment in warehouse service
  await send($.Fulfillment.start.in('warehouse'), { order })

  // Update inventory in inventory service
  await send($.Inventory.reserve.in('inventory'), {
    items: order.items,
  })
})

// Event aggregation patterns
on([$.Payment.completed, $.Shipment.delivered, $.Review.submitted], async (event) => {
  await send($.CustomerScore.update, {
    customer: event.customer,
    eventType: event.$type,
  })
})

Workflow Integration

Connect to platform workflows:

import { workflow } from 'sdk.do'

// Define multi-step workflow
const OnboardingWorkflow = workflow({
  name: 'customer-onboarding',
  steps: [
    {
      name: 'verify-email',
      action: async (customer) => {
        await send($.Email.verify, customer)
        return { verified: true }
      },
    },
    {
      name: 'create-account',
      action: async (data) => {
        return await db.create($.Account, {
          customer: data.customer.id,
          status: 'active',
        })
      },
    },
    {
      name: 'provision-resources',
      action: async (data) => {
        await send($.Resources.provision, {
          account: data.account,
        })
      },
    },
  ],
})

// Execute workflow
await OnboardingWorkflow.run({ customer })

Functions Integration

Use platform serverless functions:

import { functions } from 'sdk.do'

// Deploy function
await functions.deploy({
  name: 'process-order',
  handler: async (order) => {
    // Validate order
    const valid = await validateOrder(order)
    if (!valid) return { error: 'Invalid order' }

    // Process payment
    const payment = await processPayment(order)

    // Create fulfillment
    await send($.Fulfillment.create, { order, payment })

    return { success: true, orderId: order.id }
  },
  triggers: [$.Order.created],
  timeout: 30000,
})

// Invoke function
const result = await functions.invoke('process-order', { order })

External Service Integration

Stripe Integration

Complete payment processing integration:

import { api } from 'sdk.do'

const StripeService = {
  // Initialize
  setup: async () => {
    api.stripe.configure({
      apiKey: process.env.STRIPE_SECRET_KEY,
      webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
    })
  },

  // Create customer
  createCustomer: async (user) => {
    const customer = await api.stripe.customers.create({
      email: user.email,
      name: user.name,
      metadata: {
        userId: user.id,
        $type: $.Person,
      },
    })

    await db.update($.User, user.id, {
      stripeCustomerId: customer.id,
    })

    return customer
  },

  // Create subscription
  subscribe: async (customer, priceId) => {
    const subscription = await api.stripe.subscriptions.create({
      customer: customer.stripeCustomerId,
      items: [{ price: priceId }],
      trial_period_days: 14,
    })

    await db.create($.Subscription, {
      stripeId: subscription.id,
      customer: customer.id,
      status: subscription.status,
    })

    return subscription
  },

  // Handle webhooks
  webhooks: on($.Stripe.webhook, async (event) => {
    switch (event.type) {
      case 'payment_intent.succeeded':
        await send($.Payment.succeeded, event.data.object)
        break
      case 'customer.subscription.updated':
        await send($.Subscription.updated, event.data.object)
        break
      case 'invoice.payment_failed':
        await send($.Payment.failed, event.data.object)
        break
    }
  }),
}

SendGrid/Email Integration

Email delivery and campaigns:

const EmailService = {
  // Send transactional email
  send: on($.Email.send, async ({ to, template, data }) => {
    await api.sendgrid.send({
      to,
      from: '[email protected]',
      templateId: template,
      dynamicTemplateData: data,
    })

    await db.create($.EmailLog, {
      to,
      template,
      sentAt: new Date(),
      status: 'sent',
    })
  }),

  // Campaign management
  campaign: {
    create: async (campaign) => {
      const list = await api.sendgrid.createList({
        name: campaign.name,
      })

      await db.create($.Campaign, {
        name: campaign.name,
        sendgridListId: list.id,
        status: 'draft',
      })
    },

    send: on($.Campaign.send, async (campaign) => {
      const recipients = await db.list($.Person, {
        where: { subscribed: true, segment: campaign.segment },
      })

      await api.sendgrid.campaigns.send({
        listId: campaign.sendgridListId,
        subject: campaign.subject,
        content: campaign.content,
      })

      await db.update($.Campaign, campaign.id, {
        status: 'sent',
        sentAt: new Date(),
        recipientCount: recipients.length,
      })
    }),
  },
}

Slack Integration

Team notifications and collaboration:

const SlackService = {
  // Send notification
  notify: on($.Notification.send, async (notification) => {
    await api.slack.chat.postMessage({
      channel: notification.channel,
      text: notification.message,
      blocks: [
        {
          type: 'section',
          text: {
            type: 'mrkdwn',
            text: notification.message,
          },
        },
        {
          type: 'actions',
          elements: notification.actions?.map((action) => ({
            type: 'button',
            text: { type: 'plain_text', text: action.text },
            url: action.url,
          })),
        },
      ],
    })
  }),

  // Business events to Slack
  events: {
    newCustomer: on($.Customer.registered, async (customer) => {
      await send($.Notification.send, {
        channel: 'sales',
        message: `🎉 New customer: ${customer.name} (${customer.email})`,
      })
    }),

    highValueOrder: on($.Order.created, async (order) => {
      if (order.total > 1000) {
        await send($.Notification.send, {
          channel: 'sales',
          message: `💰 High-value order: $${order.total} from ${order.customer.name}`,
        })
      }
    }),

    churn: on($.Subscription.cancelled, async (subscription) => {
      await send($.Notification.send, {
        channel: 'customer-success',
        message: `⚠️ Churn alert: ${subscription.customer.name} cancelled ${subscription.plan} plan`,
      })
    }),
  },
}

CRM Integration (HubSpot/Salesforce)

Sync customers and deals:

const CRMService = {
  // Sync contact
  syncContact: on($.Customer.registered, async (customer) => {
    const contact = await api.hubspot.contacts.create({
      email: customer.email,
      firstname: customer.firstName,
      lastname: customer.lastName,
      company: customer.company,
      lifecycle_stage: 'customer',
    })

    await db.update($.Customer, customer.id, {
      hubspotId: contact.id,
    })
  }),

  // Sync deal
  syncDeal: on($.Order.created, async (order) => {
    const deal = await api.hubspot.deals.create({
      dealname: `Order #${order.id}`,
      amount: order.total,
      dealstage: 'closedwon',
      pipeline: 'default',
      associations: {
        contacts: [order.customer.hubspotId],
      },
    })

    await db.update($.Order, order.id, {
      hubspotDealId: deal.id,
    })
  }),

  // Bi-directional sync
  webhooks: on($.HubSpot.webhook, async (event) => {
    if (event.type === 'contact.propertyChange') {
      const contact = await api.hubspot.contacts.get(event.objectId)

      await db.update(
        $.Customer,
        {
          where: { hubspotId: contact.id },
        },
        {
          email: contact.properties.email,
          phone: contact.properties.phone,
        }
      )
    }
  }),
}

Analytics Integration (Mixpanel/Amplitude)

Track user behavior and product analytics:

const AnalyticsService = {
  // Track event
  track: on($.Analytics.track, async (event) => {
    await api.mixpanel.track({
      event: event.name,
      distinct_id: event.user.id,
      properties: {
        ...event.properties,
        timestamp: new Date(),
        platform: 'web',
      },
    })
  }),

  // User properties
  identify: on($.User.updated, async (user) => {
    await api.mixpanel.people.set(user.id, {
      $email: user.email,
      $name: user.name,
      plan: user.account?.plan,
      signupDate: user.createdAt,
    })
  }),

  // Business metrics
  metrics: {
    // Track conversion
    conversion: on($.Subscription.created, async (subscription) => {
      await send($.Analytics.track, {
        name: 'subscription_started',
        user: subscription.customer,
        properties: {
          plan: subscription.plan,
          amount: subscription.amount,
          trial: subscription.trialDays > 0,
        },
      })
    }),

    // Track revenue
    revenue: on($.Invoice.paid, async (invoice) => {
      await api.mixpanel.people.track_charge(invoice.customer.id, invoice.total, {
        $time: new Date(),
        plan: invoice.subscription?.plan,
      })
    }),
  },
}

Cloud Storage (S3/Cloudflare R2)

File storage and CDN:

const StorageService = {
  // Upload file
  upload: on($.File.upload, async (file) => {
    const key = `${file.userId}/${Date.now()}-${file.name}`

    await api.r2.putObject({
      Bucket: 'user-uploads',
      Key: key,
      Body: file.buffer,
      ContentType: file.mimeType,
    })

    const url = `https://cdn.example.com/${key}`

    await db.create($.File, {
      key,
      url,
      name: file.name,
      size: file.size,
      mimeType: file.mimeType,
      user: file.userId,
    })

    return { url, key }
  }),

  // Generate signed URL
  getSignedUrl: async (file, expiresIn = 3600) => {
    return await api.r2.getSignedUrl({
      Bucket: 'user-uploads',
      Key: file.key,
      Expires: expiresIn,
    })
  },

  // Delete file
  delete: on($.File.delete, async (file) => {
    await api.r2.deleteObject({
      Bucket: 'user-uploads',
      Key: file.key,
    })

    await db.delete($.File, file.id)
  }),
}

OAuth & Authentication

Integrate third-party authentication:

const AuthService = {
  // OAuth providers
  providers: {
    github: {
      authorize: async () => {
        const url = api.oauth.getAuthUrl({
          provider: 'github',
          scopes: ['user:email', 'repo'],
          redirectUri: 'https://example.com/auth/github/callback',
        })
        return url
      },

      callback: on($.OAuth.callback.github, async (code) => {
        const token = await api.oauth.getToken({
          provider: 'github',
          code,
        })

        const user = await api.github.getUser(token.access_token)

        // Create or update user
        const localUser = await db.upsert(
          $.User,
          {
            where: { email: user.email },
          },
          {
            email: user.email,
            name: user.name,
            githubId: user.id,
            avatar: user.avatar_url,
          }
        )

        return { user: localUser, token }
      }),
    },

    google: {
      authorize: async () => {
        return api.oauth.getAuthUrl({
          provider: 'google',
          scopes: ['email', 'profile'],
          redirectUri: 'https://example.com/auth/google/callback',
        })
      },

      callback: on($.OAuth.callback.google, async (code) => {
        const token = await api.oauth.getToken({
          provider: 'google',
          code,
        })

        const user = await api.google.getUserInfo(token.access_token)

        const localUser = await db.upsert(
          $.User,
          {
            where: { email: user.email },
          },
          {
            email: user.email,
            name: user.name,
            googleId: user.sub,
            avatar: user.picture,
          }
        )

        return { user: localUser, token }
      }),
    },
  },
}

Monitoring & Observability

Integrate monitoring and logging:

const MonitoringService = {
  // Error tracking (Sentry)
  errors: {
    capture: on($.Error.occurred, async (error) => {
      await api.sentry.captureException(error, {
        user: error.user,
        tags: {
          environment: process.env.NODE_ENV,
          service: error.service
        },
        extra: error.context
      })
    }),

    track: async (error, context) => {
      await send($.Error.occurred, {
        error,
        context,
        timestamp: new Date()
      })
    }
  },

  // Logging (Datadog/LogDNA)
  logging: {
    log: async (level, message, metadata) => {
      await api.datadog.log({
        level,
        message,
        metadata,
        service: 'business-as-code',
        timestamp: new Date()
      })
    },

    business: on($.*.*, async (event) => {
      // Log all business events
      await MonitoringService.logging.log('info', 'Business event', {
        event: event.$type,
        data: event
      })
    })
  },

  // Metrics (Prometheus/Grafana)
  metrics: {
    counter: async (name, value = 1, labels = {}) => {
      await api.prometheus.inc(name, value, labels)
    },

    gauge: async (name, value, labels = {}) => {
      await api.prometheus.set(name, value, labels)
    },

    histogram: async (name, value, labels = {}) => {
      await api.prometheus.observe(name, value, labels)
    }
  },

  // Business metrics
  track: {
    revenue: on($.Invoice.paid, async (invoice) => {
      await MonitoringService.metrics.counter('revenue_total', invoice.total, {
        plan: invoice.subscription?.plan
      })
    }),

    signups: on($.Customer.registered, async (customer) => {
      await MonitoringService.metrics.counter('signups_total', 1, {
        source: customer.source
      })
    }),

    apiCalls: on($.API.called, async (request) => {
      await MonitoringService.metrics.histogram('api_duration_seconds', request.duration, {
        endpoint: request.endpoint,
        status: request.status
      })
    })
  }
}

Multi-Service Architecture

Coordinate between multiple services:

const ServiceOrchestration = {
  // Saga pattern for distributed transactions
  orderSaga: on($.Order.created, async (order) => {
    try {
      // Step 1: Reserve inventory
      const inventory = await send($.Inventory.reserve.in('inventory'), {
        items: order.items,
      })

      // Step 2: Process payment
      const payment = await send($.Payment.process.in('payments'), {
        order,
        amount: order.total,
      })

      // Step 3: Create shipment
      const shipment = await send($.Shipment.create.in('fulfillment'), {
        order,
        inventory,
      })

      // Success - confirm order
      await send($.Order.confirm, {
        order,
        inventory,
        payment,
        shipment,
      })
    } catch (error) {
      // Rollback on failure
      await send($.Inventory.release.in('inventory'), { order })
      await send($.Payment.refund.in('payments'), { order })
      await send($.Order.cancel, { order, reason: error.message })
    }
  }),

  // Event sourcing
  eventStore: {
    append: async (stream, event) => {
      await db.create($.Event, {
        stream,
        type: event.$type,
        data: event,
        timestamp: new Date(),
      })

      await send(event.$type, event)
    },

    replay: async (stream) => {
      const events = await db.list($.Event, {
        where: { stream },
        sort: 'timestamp',
      })

      for (const event of events) {
        await send(event.type, event.data)
      }
    },
  },
}

Next Steps


Documentation Status: This documentation describes the planned API design for the .do platform. Code examples represent the intended interface and may not reflect the current implementation state.