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

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

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

import { invoiceOutputSchema } from '../output-schemas';
export const stripeInvoicePaymentFailed = createTrigger({
  auth: stripeAuth,
  name: 'invoice_payment_failed',
  classification: 'READ',
  displayName: 'Invoice Payment Failed',
  description: 'Fires when paying an invoice fails, e.g. a renewal.',
  aiMetadata: {
    description:
      'Fires when a payment against an invoice fails in Stripe (the invoice.payment_failed event), emitting the affected invoice including the finalization error. An optional customer ID filter narrows firing to one customer. Use to react to failed invoice payments, such as starting a dunning or retry flow.',
  },
  props: {
    customer: Property.ShortText({
      displayName: 'Customer ID',
      description: 'Only invoices for this customer. Empty: all.',
      placeholder: 'cus_...',
      required: false,
    }),
  },

  outputSchema: invoiceOutputSchema,
  sampleData: {
    id: 'in_1MtHbELkdIwHu7ixl4OzzPMv',
    object: 'invoice',
    customer: 'cus_NeZwdNtLEOXuvB',
    status: 'open',
    amount_due: 1500,
    amount_paid: 0,
    amount_remaining: 1500,
    attempt_count: 1,
    attempted: true,
    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_...',
    last_finalization_error: {
      code: 'card_declined',
      doc_url: 'https://stripe.com/docs/error-codes/card-declined',
      message: 'Your card was declined.',
      param: '',
      payment_intent: {
        id: 'pi_123',
        object: 'payment_intent',
      },
      type: 'card_error',
    },
    livemode: false,
    next_payment_attempt: 1681251667,
  },
  type: TriggerStrategy.WEBHOOK,

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

  async onDisable(context) {
    const webhookInfo = await context.store.get<StripeWebhookInformation>(
      '_invoice_payment_failed_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: {
        status : 'open',
        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 { customer } = context.propsValue;

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

    return [invoiceObject];
  },
});