---
title: "Functions"
description: "A non-technical overview of Functions in RevCent, focused on how hosted JavaScript code can run from account events, schedules, URLs, webhooks, Email Templates, AI Assistants, AI Voice Agents, and Payment Profile flows to support custom automation and integrations."
type: "feature"
company: "RevCent"
canonical: "https://revcent.com/documentation/markdown/ecosystem/feature/Function.md"
relationships:
  - name: "Event"
    url: "https://revcent.com/documentation/markdown/ecosystem/feature/Event.md"
  - name: "Email Template"
    url: "https://revcent.com/documentation/markdown/ecosystem/feature/EmailTemplate.md"
  - name: "AI Assistant"
    url: "https://revcent.com/documentation/markdown/ecosystem/feature/AIAssistant.md"
  - name: "AI Voice Agent"
    url: "https://revcent.com/documentation/markdown/ecosystem/feature/AIVoiceAgent.md"
technical_links:
  web_app: "https://kb.revcent.com/en/integrations/functions"
  api:
    section: "https://revcent.com/docs/api/v2#section-functions"
    operations:
      - name: "Get Functions"
        operation_id: "GetFunctions"
        operation: "https://revcent.com/docs/api/v2#operation-GetFunctions"
        schema: "https://revcent.com/documentation/files/api/operation/GetFunctions.json"
      - name: "Create A Function"
        operation_id: "CreateFunction"
        operation: "https://revcent.com/docs/api/v2#operation-CreateFunction"
        schema: "https://revcent.com/documentation/files/api/operation/CreateFunction.json"
      - name: "Get A Function"
        operation_id: "GetFunction"
        operation: "https://revcent.com/docs/api/v2#operation-GetFunction"
        schema: "https://revcent.com/documentation/files/api/operation/GetFunction.json"
      - name: "Edit A Function"
        operation_id: "EditFunction"
        operation: "https://revcent.com/docs/api/v2#operation-EditFunction"
        schema: "https://revcent.com/documentation/files/api/operation/EditFunction.json"
      - name: "Trigger A Function"
        operation_id: "TriggerFunction"
        operation: "https://revcent.com/docs/api/v2#operation-TriggerFunction"
        schema: "https://revcent.com/documentation/files/api/operation/TriggerFunction.json"
      - name: "Delete A Function"
        operation_id: "DeleteFunction"
        operation: "https://revcent.com/docs/api/v2#operation-DeleteFunction"
        schema: "https://revcent.com/documentation/files/api/operation/DeleteFunction.json"
  mcp:
    overview: "https://revcent.com/documentation/markdown/mcp/operation/OverviewFunction.md"
    operations:
      - name: "Get Functions"
        operation_id: "GetFunctions"
        markdown: "https://revcent.com/documentation/markdown/mcp/operation/GetFunctions.md"
        available_via_ai: true
      - name: "Create A Function"
        operation_id: "CreateFunction"
        markdown: "https://revcent.com/documentation/markdown/mcp/operation/CreateFunction.md"
        available_via_ai: true
      - name: "Get A Function"
        operation_id: "GetFunction"
        markdown: "https://revcent.com/documentation/markdown/mcp/operation/GetFunction.md"
        available_via_ai: true
      - name: "Edit A Function"
        operation_id: "EditFunction"
        markdown: "https://revcent.com/documentation/markdown/mcp/operation/EditFunction.md"
        available_via_ai: true
      - name: "Trigger A Function"
        operation_id: "TriggerFunction"
        markdown: "https://revcent.com/documentation/markdown/mcp/operation/TriggerFunction.md"
        available_via_ai: true
      - name: "Delete A Function"
        operation_id: "DeleteFunction"
        markdown: "https://revcent.com/documentation/markdown/mcp/operation/DeleteFunction.md"
        available_via_ai: true
---

# Functions

Functions are RevCent's hosted custom-code layer for commerce operations.

They let a business add its own logic directly inside the RevCent ecosystem. When something happens, RevCent can run custom JavaScript written for that business: send data to another system, enrich an email, decide whether an AI workflow should continue, receive a partner webhook, run a scheduled job, or influence a payment flow.

The simplest way to think about Functions:

```text
Trigger = the moment something should happen
Function = the custom logic that runs
Event data = the RevCent record, request, or context the Function receives
Completion = how the Function returns a result or error
```

Functions make RevCent programmable. Instead of waiting for every unique workflow to become a product setting, a business can create its own behavior around its own data, partners, policies, and customer experience.

---

## Technical Links

| Area | Link |
|---|---|
| Web App | `https://kb.revcent.com/en/integrations/functions` |
| API | `https://revcent.com/docs/api/v2#section-functions` |
| MCP | `https://revcent.com/documentation/markdown/mcp/operation/OverviewFunction.md` |

---

## Why Functions Matter

Every ecommerce business eventually has rules that are too specific for generic software.

Examples:

- "When a high-value paid sale is created, send a formatted alert to the finance Slack channel."
- "Before an AI Voice Agent calls a customer, check whether the customer is still eligible."
- "When a receipt email is generated, add loyalty details from our rewards system."
- "When a warehouse posts a shipment update, validate it and attach the result to the customer workflow."
- "Every morning, send yesterday's failed-renewal summary to the retention team."
- "During payment processing, ask a risk service whether the transaction should continue."

Functions are the bridge between RevCent's built-in commerce system and the business's own operating reality.

They are powerful because they can connect:

- RevCent records,
- customer events,
- fulfillment and warehouse tools,
- CRMs and helpdesks,
- analytics and reporting systems,
- AI Assistants,
- AI Voice Agents,
- Email Templates,
- Payment Profile flows,
- internal business APIs,
- partner webhooks,
- scheduled operations.

That makes Functions one of the most flexible extension points in RevCent.

---

## What A Function Can Do

A Function can:

- react to account events,
- send data to third-party systems,
- receive inbound requests from external systems,
- run on a schedule,
- generate custom Email Template data,
- act as an AI System Tool,
- decide whether an AI Assistant should run,
- decide whether an AI Voice Agent should call,
- generate AI Voice Agent pre-agent context,
- run inside a Payment Profile flow,
- transform payloads,
- validate requests,
- read environment variables,
- use installable dependencies,
- return structured responses.

Functions are account-level automation components. They are not sales, customers, transactions, or shipping records themselves. Instead, they run in response to those records and help the account take action.

---

## How Functions Are Created

A Function can be created in the RevCent web app or through API/MCP operations.

At first, a Function only needs a name. After it is created, the user configures:

- what triggers it,
- whether it is enabled,
- what code it runs,
- which dependencies it needs,
- which environment variables it can read,
- which trigger-specific settings apply,
- what result it should return.

Good Function names describe the business workflow:

```text
Account Event - Slack Alert - Chargeback Created
Schedule - Daily Report - Failed Renewals
API Direct - Customer Summary Tool
AI Filter - Sale Eligibility - Voice Agent
Email Template - Custom Data - Receipt Footer
Payment Profile - Risk Check - Gateway Routing
Function URL - Partner Lookup - Customer Status
```

New Functions need time to provision before they are ready for their first configuration update. Use `GetFunction` to check the Function's `status`; when `status` is `"READY"`, the Function can be updated with code, dependencies, environment variables, and trigger settings.

---

## Function Status

Functions can be enabled or disabled.

Disabled is the right state while building, reviewing, or testing. Enabled means the Function can run when its trigger occurs.

Best practice:

```text
Create important Functions disabled.
Configure code, dependencies, variables, and trigger behavior.
Test with realistic data.
Enable only when the workflow is ready.
```

---

## Trigger Types

The trigger decides when the Function runs and what data it receives.

| Trigger | What It Enables |
|---|---|
| Account Event | Run custom logic when RevCent events happen. |
| Schedule | Run recurring jobs using a cron schedule. |
| Function URL | Create a URL that runs custom logic and returns a response. |
| Webhook | Receive POSTs from outside systems and acknowledge them. |
| Email Template | Generate custom data while an email is compiled. |
| API/AI | Run directly by API/MCP or by RevCent AI systems. |
| Payment Profile | Run custom logic during an existing payment flow. |

Each trigger gives the Function a different kind of `event.data`.

---

## Account Event Functions

Account Event Functions run automatically when selected RevCent events happen.

They are ideal for operational automation:

- sale created,
- customer created or updated,
- customer card added,
- subscription renewed,
- subscription renewal failed,
- trial expired,
- shipment shipped,
- chargeback created,
- fraud detection created,
- transaction created,
- pending refund created,
- note created,
- PayPal dispute created.

Account Event Functions receive event details and the related RevCent item.

Common data includes:

```javascript
event.data.event_date
event.data.event_id
event.data.event_trigger
event.data.item_type
event.data.item_id
event.data.item_details
```

The `item_details` object is the detailed RevCent record related to the event.

---

## Schedule Functions

Schedule Functions run on a recurring schedule.

Use them for work that should happen every few minutes, daily, weekly, or on another recurring cadence:

- daily reports,
- order syncs,
- cleanup jobs,
- monitoring checks,
- customer segmentation refreshes,
- inventory reminders,
- external API polling.

Schedule Functions receive an empty string in `event.data`.

Schedule notes:

- Cron expressions use five parts: minute, hour, day of month, month, day of week.
- Intervals cannot be less than 10 minutes apart.
- Scheduled Functions are checked every 10 minutes, so exact timing may vary.
- Shortcut syntax such as `@daily` is not supported.
- A timezone can be selected for the schedule.

---

## Function URL And Webhook Functions

Function URLs and webhooks let outside systems talk to RevCent.

Use a Function URL when the caller needs a custom response from the Function.

Use a webhook when the outside system only needs to POST data and receive a basic acknowledgement.

Common inbound uses:

- fulfillment providers posting shipment events,
- CRMs sending customer status changes,
- custom storefronts sending checkout data,
- partner systems requesting a computed response,
- third-party services sending notifications.

For inbound requests:

- `event.data` contains the request body as a string,
- `context.source.method` identifies the request method,
- `context.source.content_type` helps decide how to parse the body,
- `context.source.headers` can be used for shared secrets or signatures,
- `context.source.url_params` can be used for URL parameters,
- `context.source.ip_address` can be used for request review or restriction logic.

Public URLs and webhooks are security-sensitive. Validate the caller before trusting the data or returning sensitive information.

Common validation patterns include:

- shared secret headers,
- HMAC signatures,
- bearer tokens,
- timestamp checks,
- IP restrictions,
- request body validation,
- idempotency keys.

---

## Email Template Functions

Email Template Functions run while an Email Template is being compiled.

They return a JSON object that becomes available as `custom_data` in the template.

This is useful for:

- custom receipt content,
- customer-specific support details,
- loyalty information,
- product recommendations,
- conditional messaging,
- external data enrichment,
- computed template values.

Correct Email Template response:

```javascript
return {
  support_email: "support@example.com",
  customer_message: "Thank you for your order."
};
```

The template can then use:

```handlebars
{{custom_data.support_email}}
```

Email Template Functions should return a JSON object, not a plain string.

---

## API And AI Functions

API/AI Functions can run on demand.

They can be triggered directly by API/MCP, or they can be used by RevCent AI systems.

API/AI Functions can act as:

- direct API-triggered workflows,
- direct MCP-triggered workflows,
- AI Assistant system tools,
- AI Voice Agent system tools,
- AI Assistant filters,
- AI Voice Agent filters,
- AI Voice Agent pre-agent Functions.

Normal AI tool Functions perform custom work inside an AI workflow. Filter Functions decide whether the AI workflow should run at all. Pre-agent Functions generate context before a voice call begins.

Those uses are related, but they are not the same.

---

## AI Assistant Functions

AI Assistants can use Functions in two major ways.

First, an AI Assistant can trigger a Function during a step. This allows the assistant to run approved custom logic, retrieve data, transform a payload, or call an external system.

Second, an AI Assistant can use a Function as a filter before running. This prevents unnecessary or inappropriate AI processing.

Examples:

- summarize customer history before an AI response,
- create a ticket in a helpdesk,
- send an alert to a team,
- normalize input before the assistant continues,
- block an AI workflow for customers who do not meet eligibility rules.

---

## AI Voice Agent Functions

AI Voice Agents can use Functions in three ways.

First, a voice agent can trigger a Function as a normal tool during a call.

Second, a Function can filter whether a call should proceed.

Third, a pre-agent Function can run before the call and return custom data for voice-agent instructions.

Pre-agent output becomes available in the AI Voice Agent instruction context:

```handlebars
{{pre_agent_function.response.property_name}}
```

This lets a business personalize voice calls with fresh context, product details, customer history, offer rules, or external data.

---

## Filter Functions

A filter Function returns whether an AI Assistant or AI Voice Agent should proceed.

Filter Functions usually receive item context:

```javascript
event.data.item_type
event.data.item_id
event.data.item_details
```

They return exactly one of two values:

```javascript
return "pass";
```

or:

```javascript
return "fail";
```

`pass` allows the AI workflow to continue. `fail` stops it for that item.

Use filter Functions for eligibility rules, suppression rules, do-not-contact logic, campaign constraints, customer status checks, and similar gatekeeping decisions.

---

## Payment Profile Functions

Payment Profile Functions run during an existing Payment Profile flow.

They are advanced because they can influence payment behavior.

A Payment Profile Function can:

- call an external risk system,
- parse a payment response,
- choose a next flow output,
- route to a connected node,
- set a gateway,
- return a custom error.

Because this affects active payment processing, Payment Profile Functions should be small, fast, tested, and paired with safe fallback routing.

---

## Function Code Basics

Functions are written in JavaScript and run in Node.js 22.x.

Every Function must include its own handler. RevCent does not add the handler automatically.

The handler receives:

| Argument | Meaning |
|---|---|
| `event` | Trigger-specific data, usually in `event.data`. |
| `context` | Details about the source, Function, run, request, or AI context. |
| `callback` | Optional callback-style completion function. Functions can also return a value or throw an error. |

Basic structure:

```javascript
exports.handler = async function(event, context) {
  return {
    success: true
  };
};
```

The handler must be part of the submitted Function code.

---

## Completion

Functions can complete by returning a value, throwing an error, or calling `callback(error, response)`.

Return success:

```javascript
return {
  success: true
};
```

Throw an error:

```javascript
throw new Error("Something went wrong.");
```

Callback style is also supported:

```javascript
exports.handler = async function(event, context, callback) {
  callback(null, {
    success: true
  });
};
```

When code should stop after a callback, return immediately:

```javascript
exports.handler = async function(event, context, callback) {
  if (!event.data) {
    callback(null, {
      skipped: true
    });
    return;
  }
};
```

---

## Dependencies

Functions can use dependencies.

Dependencies are configured with a package name and version, then loaded in code with `require()`.

Example:

```javascript
const axios = require("axios");

exports.handler = async function(event, context) {
  try {
    const response = await axios.get("https://api.example.com/data");
    return response.data;
  } catch (error) {
    throw error;
  }
};
```

Dependency rules:

- Any dependency can be used if it installs successfully.
- The package name and version must be valid.
- `"latest"` is allowed.
- If a dependency or version cannot be installed, the Function cannot be provisioned successfully and will error.
- After dependency changes, allow up to 5 minutes for provisioning.
- Dependencies must be loaded with `require()`.
- ESM `import` syntax is not supported.

---

## Function Readiness

After a Function is created or edited, RevCent may need time to provision the runtime, install dependencies, and prepare the updated environment.

Use `GetFunction` to check the Function's `status`.

When `status` is `"READY"`, a newly created Function is ready for its first configuration update. After an edit, `READY` is useful when another edit will be made shortly afterward.

Do not treat `READY` as a required preflight for every isolated Function operation. It is mainly a provisioning signal for create-then-edit and edit-then-edit workflows.

---

## Environment Variables

Environment variables let Functions use configuration and secrets without hardcoding them.

Use them for:

- API keys,
- private tokens,
- webhook secrets,
- external endpoint credentials,
- per-Function configuration,
- sensitive integration values.

Access them with:

```javascript
process.env["EXTERNAL_API_TOKEN"]
```

Do not hardcode secrets in Function code. Do not log secrets. Do not return secrets in Function responses, emails, AI messages, or public URL responses.

---

## External Integrations

Functions can connect RevCent to virtually any external system that exposes an API, accepts HTTP requests, or sends webhooks.

There are two main integration directions:

```text
Outbound integration = RevCent runs a Function that calls another system
Inbound integration = another system calls a RevCent Function URL or webhook
```

Common external targets include:

- CRMs,
- fulfillment platforms,
- warehouses,
- helpdesks,
- SMS and email providers,
- Slack or internal chat systems,
- fraud and risk platforms,
- accounting systems,
- analytics tools,
- internal business APIs,
- external databases.

Example outbound integration:

```javascript
const axios = require("axios");

exports.handler = async function(event, context, callback) {
  const payload = {
    item_type: event.data.item_type,
    item_id: event.data.item_id,
    item_details: event.data.item_details
  };

  try {
    const response = await axios.post("https://api.example.com/revcent/events", payload, {
      headers: {
        Authorization: "Bearer " + process.env["EXTERNAL_API_TOKEN"],
        "Content-Type": "application/json"
      },
      timeout: 5000
    });

    callback(null, {
      sent: true,
      status: response.status
    });
  } catch (error) {
    callback(error);
  }
};
```

This pattern can power CRM syncs, shipment notifications, chargeback alerts, fraud checks, support tickets, reporting pipelines, and internal automation.

---

## Safety And Security

Functions are powerful because they can connect systems and make decisions. That also means they should be built carefully.

Best practices:

- Keep high-impact Functions disabled until reviewed.
- Store secrets in encrypted environment variables.
- Validate inbound requests before trusting payloads.
- Use IP restrictions where appropriate.
- Use short external request timeouts.
- Handle failed requests intentionally.
- Avoid duplicate processing with idempotency keys when possible.
- Return only the data the caller or workflow needs.
- Keep Payment Profile Functions especially small and safe.
- Test with realistic event data before enabling.

---

## Common Mistakes To Avoid

Avoid these mistakes:

- creating a Function and immediately updating it before `GetFunction` returns `status: "READY"`,
- editing a Function repeatedly in quick succession without checking whether provisioning is ready for the next update,
- enabling high-impact automation before testing,
- submitting code without `exports.handler`,
- mixing return, throw, and callback styles in a way that completes the same execution path more than once,
- using ESM `import` syntax,
- configuring dependency versions that cannot be installed,
- hardcoding secrets in code,
- returning secrets in logs or responses,
- trusting inbound webhook data without validation,
- returning a string from an Email Template Function,
- returning anything other than `pass` or `fail` from a filter Function,
- using a filter Function when the goal is to run custom logic inside an AI step,
- using a normal AI tool Function when the goal is to block an AI run,
- using slow external requests inside a Payment Profile flow without a safe fallback.

---

## Setup Checklist

Before enabling a Function, verify:

- The Function has a clear name.
- The description explains the trigger and business purpose.
- The correct trigger type is selected.
- Trigger-specific settings are complete.
- Account Event filters are correct if used.
- Schedule cron expression and timezone are correct if used.
- URL or webhook security is handled if public endpoints are used.
- Required environment variables are present.
- Dependencies use installable package names and versions.
- Dependency code uses `require()`.
- The code includes `exports.handler`.
- The code completes each path by returning a value, throwing an error, or calling `callback`.
- Error handling is present.
- Email Template Functions return a JSON object.
- Filter Functions return exactly `pass` or `fail`.
- Pre-agent Functions return a plain JSON object.
- Payment Profile Functions have safe fallback routing.
- The Function has been tested with realistic payloads.

---

## Relationship To Other RevCent Features

Functions are not isolated. They are most valuable when they connect other RevCent features together.

With Events, Functions turn account activity into automation.

With Email Templates, Functions generate custom data at send time.

With AI Assistants, Functions provide controlled custom tools and eligibility filters.

With AI Voice Agents, Functions provide tools, filters, and pre-call context.

With Payment Profiles, Functions add advanced decision-making to payment flows.

With Function URLs and webhooks, Functions connect RevCent to the outside world.

---

## Summary

Functions are RevCent's programmable business logic layer.

They let a business run custom JavaScript from account events, schedules, URLs, webhooks, Email Templates, API/MCP calls, AI workflows, AI Voice Agents, and Payment Profile flows.

The most important ideas are:

```text
Choose the right trigger.
Understand the event data.
Include the handler in the code.
Complete each run by returning a value, throwing an error, or calling `callback`.
Use require() for dependencies.
Use installable dependency names and versions.
Keep secrets in environment variables.
Return the right response shape.
Secure public URLs and webhooks.
Test before enabling.
```

Used well, Functions let RevCent adapt to the exact way a business operates instead of forcing the business to fit inside a fixed set of settings.


---
Document Parent Directory
* [Features](https://revcent.com/documentation/markdown/ecosystem/feature/index.md) - Non-technical markdown documentation for features within the RevCent ecosystem. A feature is a part of the RevCent ecosystem that a user can create and configure.

---
Document Parent Directory
* [Features](https://revcent.com/documentation/markdown/ecosystem/feature/index.md) - Non-technical markdown documentation for features within the RevCent ecosystem. A feature is a part of the RevCent ecosystem that a user can create and configure.