Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

4.3 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
  Property,
} from '@activepieces/pieces-framework';
import { stripeCommon } from '../common';
import { StripeWebhookInformation } from '../common/types';
import { stripeAuth } from '../..';
import { isEmpty } from '@activepieces/pieces-framework';
import { httpClient, HttpMethod } from '@activepieces/pieces-common';

type StripeWebhookPayload = {
  data: {
    object: {
      [key: string]: unknown;
    };
  };
};

import { invoiceOutputSchema } from '../output-schemas';
export const stripeNewInvoice = createTrigger({
  auth: stripeAuth,
  name: 'new_invoice',
  classification: 'READ',
  displayName: 'New Invoice',
  description: 'Fires when an invoice is created.',
  aiMetadata: {
    description:
      'Fires when an invoice is created in Stripe (the invoice.created event), emitting the new invoice. Optional filters narrow firing to a specific status, customer ID, or subscription ID. Use to react to newly issued invoices, for example to record or forward them.',
  },
  propertyGroups: [
    {
      key: 'filters',
      display: 'section',
      label: 'Filters',
      icon: 'filter',
      props: ['status', 'customer', 'subscription'],
    },
  ],
  props: {
    status: Property.StaticDropdown({
      displayName: 'Status',
      description: 'Only invoices with this status. Empty: all.',
      required: false,
      options: {
        options: [
          { label: 'Draft', value: 'draft' },
          { label: 'Open', value: 'open' },
          { label: 'Paid', value: 'paid' },
          { label: 'Uncollectible', value: 'uncollectible' },
          { label: 'Void', value: 'void' },
        ],
      },
    }),
    customer: Property.ShortText({
      displayName: 'Customer ID',
      description: 'Only invoices for this customer. Empty: all.',
      placeholder: 'cus_...',
      required: false,
    }),
    subscription: Property.ShortText({
      displayName: 'Subscription ID',
      description: 'Only invoices for this subscription. Empty: all.',
      placeholder: 'sub_...',
      required: false,
    }),
  },
  outputSchema: invoiceOutputSchema,
  sampleData: {
    id: 'in_1MtHbELkdIwHu7ixl4OzzPMv',
    object: 'invoice',
    customer: 'cus_NeZwdNtLEOXuvB',
    subscription: 'sub_12345ABC',
    status: 'paid',
    amount_due: 999,
    amount_paid: 999,
    amount_remaining: 0,
    billing_reason: 'subscription_cycle',
    collection_method: 'charge_automatically',
    created: 1680644467,
    currency: 'usd',
    customer_email: '[email protected]',
    customer_name: 'Jenny Rosen',
    hosted_invoice_url: 'https://invoice.stripe.com/i/acct_...',
    invoice_pdf: 'https://pay.stripe.com/invoice/acct_.../pdf',
    livemode: false,
    number: 'ABC-123-456',
  },
  type: TriggerStrategy.WEBHOOK,

  async onEnable(context) {
    const webhook = await stripeCommon.subscribeWebhook(
      'invoice.created',
      context.webhookUrl,
      context.auth.secret_text
    );
    await context.store.put<StripeWebhookInformation>('_new_invoice_trigger', {
      webhookId: webhook.id,
    });
  },

  async onDisable(context) {
    const webhookInfo = await context.store.get<StripeWebhookInformation>(
      '_new_invoice_trigger'
    );
    if (webhookInfo !== null && webhookInfo !== undefined) {
      await stripeCommon.unsubscribeWebhook(
        webhookInfo.webhookId,
        context.auth.secret_text
      );
    }
  },
  async test(context) {
    const response = await httpClient.sendRequest<{ data: { id: string }[] }>({
      method: HttpMethod.GET,
      url: 'https://api.stripe.com/v1/invoices',
      headers: {
        Authorization: 'Bearer ' + context.auth.secret_text,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      queryParams: {
        limit: '5',
      },
    });

    if (isEmpty(response.body) || isEmpty(response.body.data)) return [];

    return response.body.data;
  },
  async run(context) {
    const payloadBody = context.payload.body as StripeWebhookPayload;
    const invoiceObject = payloadBody.data.object;
    const { status, customer, subscription } = context.propsValue;

    if (status && invoiceObject['status'] !== status) {
      return [];
    }
    if (customer && invoiceObject['customer'] !== customer) {
      return [];
    }
    if (subscription && invoiceObject['subscription'] !== subscription) {
      return [];
    }

    return [invoiceObject];
  },
});