# RevCent Functions Overview for Ecommerce Businesses

RevCent Functions allow ecommerce businesses to run custom JavaScript code inside RevCent when specific events, requests, schedules, AI actions, payment flows, or email template compilations occur.

Functions are useful when a business needs custom automation, third-party integrations, advanced payment logic, AI workflow control, or dynamic personalization that goes beyond standard platform settings.

## What Are RevCent Functions?

A RevCent Function is a hosted JavaScript execution unit.

Instead of running your own server, you write custom JavaScript code and RevCent runs it for you when a configured trigger occurs.

Functions can:

- React to ecommerce events.
- Send data to third-party systems.
- Receive data from external systems.
- Generate custom email template data.
- Add custom AI Assistant or AI Voice Agent logic.
- Run scheduled jobs.
- Control advanced payment routing.
- Build custom webhook or URL endpoints.
- Store and use encrypted values.
- Use account-wide configuration and external state where appropriate.
- Use installable Node.js dependencies.
- Make outbound internet requests.

Functions are executed in a secure virtual environment using Node.js 22.x.

---

## Why Ecommerce Businesses Use Functions

Ecommerce operations often require business-specific rules that cannot be fully solved with standard settings.

Examples:

- “When a high-value sale is created, alert Slack and tag the customer.”
- “When a customer is added to a certain group, sync them to an external CRM.”
- “When a shipment is created, send the details to a warehouse API.”
- “Before processing payment, check an external risk engine.”
- “If a customer calls an AI Voice Agent, generate dynamic instructions from their purchase history.”
- “When an email template renders, add custom personalized content.”
- “Receive a webhook from a fulfillment partner and update internal data.”
- “Run a daily report and send it to the operations team.”

Functions make these types of workflows possible without needing a separate application server.

---

## Major Use Cases

| Business Need | Function Use Case |
|---|---|
| Ecommerce automation | Run code when sales, customers, subscriptions, shipments, refunds, fraud events, or chargebacks occur. |
| Third-party integrations | Send or receive data from CRMs, fulfillment platforms, Slack, email providers, SMS providers, analytics tools, databases, and custom APIs. |
| Payment optimization | Add logic inside Next-Gen Payment Profile flows to choose gateways, route declines, or call risk APIs. |
| Email personalization | Generate custom data for Email Templates at render time. |
| AI workflow control | Give AI Assistants or AI Voice Agents controlled custom tools. |
| AI filtering | Allow or block AI Assistant / AI Voice Agent execution for specific items. |
| AI Voice Agent dynamic instructions | Generate pre-agent content for voice-agent instructions using Handlebars. |
| Scheduled jobs | Run recurring reports, syncs, cleanup jobs, or monitoring tasks. |
| Public endpoints | Create URL or webhook endpoints for partner systems. |

---

# Function Triggers

The Function trigger determines what causes the Function to run and what data is available in `event.data`.

RevCent Functions support these trigger categories:

| Trigger | What It Does | Common Ecommerce Uses |
|---|---|---|
| `account_event` | Runs automatically when a RevCent account event occurs. | Sale created, customer updated, shipment shipped, chargeback created, subscription renewed. |
| `schedule` | Runs on a fixed schedule using a cron expression. | Daily reports, recurring syncs, cleanup jobs. |
| `function_url` | Runs when a generated Function URL receives a GET or POST request and returns the Function response. | Custom internal endpoints, partner lookup endpoints, on-demand tools. |
| `webhook` | Runs when a generated webhook URL receives a POST request and returns a static OK response. | Receiving third-party webhooks or event notifications. |
| `email_template` | Runs while compiling an Email Template and returns `custom_data`. | Dynamic receipt content, conditional email personalization, external data enrichment. |
| `api_direct` / API/AI | Runs when triggered directly through API/MCP or AI. Also supports AI System Tools, filter Functions, and AI Voice Agent pre-agent Functions. | AI tools, on-demand workflows, AI filtering, custom agent instructions. |
| `payment_profile` | Runs during a Next-Gen Payment Profile flow. | Gateway routing, fraud checks, decline parsing, payment orchestration. |

---

# Account Event Functions

Account Event Functions run automatically when specific RevCent events occur.

This is one of the most useful trigger types for ecommerce automation.

## Common Account Event Categories

Account events can be related to:

- Sales
- Product sales
- Customers
- Customer cards
- Subscriptions
- Subscription renewals
- Trials
- Shipments
- Refunds and pending refunds
- Chargebacks
- PayPal disputes
- Fraud detections
- Sentinel alerts
- Invoices
- Transactions
- Products
- Discounts
- Notes
- Taxes
- Offline payments
- Check direct payments

## Example Ecommerce Automations

| Event | Possible Function |
|---|---|
| Sale created successfully | Send order to fulfillment provider. |
| Sale failed or declined | Add sale to recovery workflow. |
| Chargeback created | Alert finance and customer support. |
| Shipment shipped | Notify external tracking system. |
| Subscription renewal failed | Send account to retention workflow. |
| Customer created | Sync customer to CRM. |
| Fraud detection created | Post to risk-review Slack channel. |
| Pending refund created | Notify accounting or customer support. |
| Invoice created | Push invoice details to external accounting system. |

## Event Body

For account events, the Function receives event details in `event.data`.

Common account event paths:

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

Example:

```javascript
let itemType = event.data.item_type;
let itemId = event.data.item_id;
let item = event.data.item_details;

return {
  processed: true,
  item_type: itemType,
  item_id: itemId
};
```

## Event Body JSON Links

The event body JSON is based on the first word in the event notation.

Pattern:

```text
https://revcent.com/documentation/files/function/event/account_event/<item_type>.json
```

Examples:

| Event Notation | Item Type | Event Body JSON |
|---|---|---|
| `sale.created.success` | `sale` | `https://revcent.com/documentation/files/function/event/account_event/sale.json` |
| `customer.created` | `customer` | `https://revcent.com/documentation/files/function/event/account_event/customer.json` |
| `shipping.updated.shipped` | `shipping` | `https://revcent.com/documentation/files/function/event/account_event/shipping.json` |
| `subscription.updated.renewed.success` | `subscription` | `https://revcent.com/documentation/files/function/event/account_event/subscription.json` |
| `subscription_renewal.updated.success` | `subscription_renewal` | `https://revcent.com/documentation/files/function/event/account_event/subscription_renewal.json` |
| `trial.updated.expired.success` | `trial` | `https://revcent.com/documentation/files/function/event/account_event/trial.json` |

---

# Schedule Functions

Schedule Functions run on a fixed schedule using a standard five-part cron expression.

Use scheduled Functions for recurring operational tasks.

## Ecommerce Use Cases

- Send a daily revenue summary.
- Sync yesterday’s orders to a warehouse.
- Export customer data to a reporting system.
- Check pending refunds every morning.
- Run a nightly customer segmentation job.
- Send inventory or fulfillment reminders.
- Poll an external API for updates.

## Event Body

Schedule event data is an empty string.

```javascript
event.data
```

Example:

```json
{
  "data": ""
}
```

Event body JSON:

```text
https://revcent.com/documentation/files/function/event/schedule.json
```

## Cron Notes

Schedule Functions use a standard five-part cron expression:

```text
minute hour day-of-month month day-of-week
```

Example:

```text
0 9 * * *
```

Meaning: run every day at 9:00 AM in the configured timezone.

Important schedule notes:

- Cron intervals cannot be less than 10 minutes apart.
- Scheduled Functions are checked every 10 minutes, so exact minute execution may vary by up to 10 minutes.
- Only standard five-part cron expressions are supported.
- `@daily`, `@hourly`, and similar shortcut syntax is not supported.

---

# Function URL Functions

A Function URL trigger creates a public URL that can execute the Function.

Unlike webhooks, Function URLs return the Function response to the caller.

## Ecommerce Use Cases

- Build a lightweight lookup endpoint.
- Create a partner API endpoint.
- Build an internal utility endpoint.
- Accept a form submission and return a calculated response.
- Allow a trusted system to request RevCent-related data.
- Trigger an immediate operation from an external system.

## Event Body

For Function URL requests, `event.data` is the request body as a string.

Example:

```json
{
  "data": "{\"test\":\"urltest\"}"
}
```

Event body JSON:

```text
https://revcent.com/documentation/files/function/event/function_url.json
```

## Context Data

For URL triggers, request metadata is available in `context.source`.

Common context paths:

```javascript
context.source.method
context.source.content_type
context.source.ip_address
context.source.headers
context.source.url_params
```

## Security Notes

Function URLs are publicly accessible unless protected by your Function logic and/or IP restrictions.

Use Function URL authentication when needed:

- Validate shared secrets.
- Check headers.
- Check URL parameters.
- Validate signatures.
- Restrict allowed IP addresses.
- Avoid returning sensitive data unless the request is authenticated.

---

# Webhook Functions

Webhook Functions create a public webhook URL that receives POST requests.

Unlike Function URLs, webhook triggers do not return the Function response. RevCent returns a static OK response after accepting the POST.

## Ecommerce Use Cases

- Receive fulfillment status updates.
- Receive shipping provider callbacks.
- Receive CRM notifications.
- Receive partner order updates.
- Receive lead capture events.
- Receive payment or fraud provider webhooks.
- Receive third-party system status changes.

## Event Body

Webhook request body is available as a string in `event.data`.

Example:

```json
{
  "data": "{\"test\":\"webhooktest\"}"
}
```

Event body JSON:

```text
https://revcent.com/documentation/files/function/event/webhook.json
```

## Webhook Response

Webhook Functions always return a static response to the sender:

```json
{
  "result": "OK"
}
```

This is useful because third parties can POST data without receiving sensitive Function output.

## Security Notes

Webhook URLs are publicly accessible unless protected.

Best practices:

- Verify signatures.
- Validate shared secrets.
- Check source IPs when possible.
- Parse body based on `context.source.content_type`.
- Use idempotency keys to avoid duplicate processing.
- Never trust inbound webhook data without validation.

---

# Email Template Functions

Email Template Functions run during Email Template compilation.

They are used to generate a `custom_data` object that becomes available to Handlebars inside the Email Template.

## Ecommerce Use Cases

- Generate a custom receipt footer.
- Add dynamic support information.
- Pull external loyalty data.
- Add product recommendations.
- Add campaign-specific brand names.
- Add customer-specific personalization.
- Generate custom HTML blocks.
- Add tracking or fulfillment messaging.
- Calculate dynamic values not present in the base template data.

## Event Body

Email Template Functions receive the item details related to the Email Template trigger.

Common path:

```javascript
event.data.item_details
```

Example:

```javascript
let item = event.data.item_details;

return {
  support_email: "support@example.com",
  customer_domain: item.customer.email.split("@")[1]
};
```

Email Template usage:

```handlebars
<p>Support: {{custom_data.support_email}}</p>
<p>Email domain: {{custom_data.customer_domain}}</p>
```

## Response Requirement

An Email Template Function must return a valid JSON object.

Correct:

```javascript
return {
  custom_property: "custom value"
};
```

Incorrect:

```javascript
return "custom value";
```

The returned object is inserted into the template input data as `custom_data`.

---

# API / AI Functions

API/AI Functions can be triggered directly by API/MCP or used by AI.

A Function can also be triggered from an AI Assistant step through the system tools that AI Assistants have access to, such as `TriggerFunction`. This lets an AI Assistant run approved custom Function logic as part of an assistant workflow without exposing arbitrary execution access.

They can also be used as AI System Tools, filter Functions, or AI Voice Agent pre-agent Functions depending on source type.

## Trigger Sources

API/AI Functions can be triggered by:

| Source Type | Description |
|---|---|
| `api_call` | Triggered directly through API/MCP. |
| `tool_call` | Triggered by AI as a System Tool. |
| `filter_function` | Used to filter whether an AI Assistant or AI Voice Agent should proceed. |
| `pre_agent_function` | Used before an AI Voice Agent call to generate dynamic instruction content. |

Event body JSON for direct API triggering:

```text
https://revcent.com/documentation/files/function/event/api_direct.json
```

## Normal API / AI Tool Call Use Cases

- Let AI call a safe custom action.
- Let AI generate a payload and send it to a third party.
- Run a custom lookup on demand.
- Summarize customer history.
- Trigger a custom workflow.
- Normalize or transform data.

## Custom Arguments

Custom arguments are used for normal AI System Tool calls.

They allow AI to generate argument values based on descriptions.

Example:

```javascript
event.data.custom_arguments.customer_email
event.data.custom_arguments.reason
```

Important:

- Custom arguments are only for normal API/AI direct tool usage.
- Do not use custom arguments for filter Functions.
- Do not use custom arguments for AI Voice Agent pre-agent Functions.

---

# AI Assistant and AI Voice Agent Filter Functions

Filter Functions are API/AI Functions used to determine whether an AI Assistant or AI Voice Agent should proceed for a specific item.

## Ecommerce Use Cases

- Only call customers with eligible declined sales.
- Prevent AI from running on high-risk customers.
- Skip customers who opted out of contact.
- Only run AI for specific campaigns or products.
- Prevent repeat calls for the same sale.
- Apply custom eligibility rules before AI starts.

## Event Body

Filter Function event body is based on `item_type` and `item_id`.

Pattern:

```text
https://revcent.com/documentation/files/function/event/filter/<item_type>.json
```

Examples:

| Item Type | Event Body JSON |
|---|---|
| `sale` | `https://revcent.com/documentation/files/function/event/filter/sale.json` |
| `customer` | `https://revcent.com/documentation/files/function/event/filter/customer.json` |
| `shipping` | `https://revcent.com/documentation/files/function/event/filter/shipping.json` |
| `subscription` | `https://revcent.com/documentation/files/function/event/filter/subscription.json` |
| `subscription_renewal` | `https://revcent.com/documentation/files/function/event/filter/subscription_renewal.json` |
| `trial` | `https://revcent.com/documentation/files/function/event/filter/trial.json` |

Common paths:

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

## Required Response

A filter Function must return one of two strings:

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

or:

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

Meaning:

- `pass`: allow the AI Assistant or AI Voice Agent to proceed.
- `fail`: prevent the AI Assistant or AI Voice Agent from proceeding.

---

# AI Voice Agent Pre-Agent Functions

Pre-agent Functions run immediately before an AI Voice Agent call starts.

They generate custom data that can be used inside AI Voice Agent instructions with Handlebars.

## Ecommerce Use Cases

- Generate a product list for an outbound sales call.
- Add dynamic company or brand name.
- Add campaign-specific instructions.
- Add refund or escalation rules.
- Pull customer context from an external CRM.
- Add custom call objectives based on sale details.
- Add structured JSON for the AI Voice Agent to reference.

## Event Body

Pre-agent event body JSON:

```text
https://revcent.com/documentation/files/function/event/pre_agent.json
```

Common paths:

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

Pre-agent Functions may run for:

| AI Voice Agent Scenario | Event Behavior |
|---|---|
| Inbound call with customer phone match | Receives customer item context. |
| Inbound call without customer phone match | May receive an empty object. |
| Outbound call from event trigger | Receives event notation plus related item context. |
| Outbound call from on-demand trigger | Receives supplied item type, item ID, and populated item details. |

## Required Response

Return a plain JSON object.

Example:

```javascript
return {
  company_name: "Acme Inc.",
  allow_full_refunds: false,
  product_list: [
    {
      name: "Product A",
      price: 29.99
    }
  ]
};
```

## Handlebars Usage in AI Voice Agent Instructions

The returned object is available under:

```handlebars
{{pre_agent_function.response.company_name}}
{{pre_agent_function.response.allow_full_refunds}}
{{{toString pre_agent_function.response.product_list}}}
```

The AI Voice Agent Handlebars data includes:

```json
{
  "pre_agent_function": {
    "has_response": true,
    "response": {
      "company_name": "Acme Inc.",
      "allow_full_refunds": false
    }
  }
}
```

---

# Payment Profile Functions

Payment Profile Functions run during a Next-Gen Payment Profile flow.

They are advanced and powerful because the Function can influence payment routing and flow behavior.

## Ecommerce Use Cases

- Choose a gateway based on custom logic.
- Call an external fraud or risk API.
- Parse gateway decline responses.
- Route payment attempts based on gateway history.
- Return a custom error message.
- Decide which flow node should run next.
- Override gateway selections.
- Run analytics while payment processing is happening.
- Apply custom routing for specific cards, campaigns, products, customers, or prior attempts.

## Run Methods

A Run Function node can use two run methods:

| Run Method | Behavior |
|---|---|
| Queue And Continue | Function runs separately. The flow does not wait. The green output is followed. |
| Wait For Response | RevCent waits for the Function response and uses it to determine flow behavior. |

Important for `Wait For Response`:

- The Function has a maximum of 8 seconds to respond within the flow.
- Red output should be routed as a backup in case the Function fails or times out.
- Bad code can prevent payment from being processed.
- External requests add latency.
- This should only be used by experienced developers.

## Event Body

Payment Profile event body JSON:

```text
https://revcent.com/documentation/files/function/event/payment_profile.json
```

Common paths:

```javascript
event.data.item_type
event.data.item_id
event.data.item_event
event.data.item_details.request
event.data.item_details.entity
event.data.item_details.customer
event.data.item_details.customer_card
event.data.item_details.campaign
event.data.item_details.payment_profile
event.data.item_details.payment_amount
event.data.item_details.products
event.data.item_details.shipping
event.data.item_details.tax
event.data.item_details.gateway_history
event.data.item_details.node_id
event.data.item_details.next_nodes
event.data.item_details.current_step
event.data.item_details.step_array
event.data.item_details.flow_path
```

## Payment Profile Response Object

When using `Wait For Response`, the Function can return:

```javascript
return {
  next_node_id: "43965f05-887a-4e70-8646-0410440a3494",
  next_output: "1",
  set_gateway_id: "bOLjn0yvKpUp10qK298R",
  selection_method: "evenly_distribute",
  choose_gateways: ["2r7zOBMldVIomKNdKZoG"],
  choose_gateway_groups: ["GOGaPRql9oUAAkrm5Ll9"],
  custom_error: "Card CVV Invalid"
};
```

| Field | Purpose |
|---|---|
| `next_node_id` | Route to a specific connected next node. |
| `next_output` | Choose output `1` green or `2` red. |
| `set_gateway_id` | Set a specific gateway for payment processing. |
| `selection_method` | Override gateway selection method. |
| `choose_gateways` | Override gateway selections. |
| `choose_gateway_groups` | Override gateway group selections. |
| `custom_error` | Send a custom error to a following Abort Flow node. |

---

# Third-Party Integrations

Functions can integrate with third-party systems because they support outbound internet access, installable dependencies, and encrypted environment variables.

## Common Ecommerce Integrations

| Integration Type | Examples |
|---|---|
| CRM | HubSpot, Salesforce, ActiveCampaign, custom CRM APIs. |
| Messaging | Slack, Twilio, SendGrid, Mailchimp. |
| Fulfillment | Warehouse APIs, Shippo, custom fulfillment systems. |
| Marketing | Klaviyo, Mailchimp, ActiveCampaign. |
| Analytics | Custom BI systems, data warehouses, event collectors. |
| Fraud / Risk | External risk scoring APIs. |
| Databases | PostgreSQL, MySQL, MongoDB, Redis. |
| AI | OpenAI or other AI services. |
| Accounting | Invoice or payment reporting systems. |

## Outbound Requests

Example using `axios`:

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

exports.handler = async function(event, context, callback) {
  try {
    const response = await axios.post(
      "https://api.example.com/events",
      {
        item_type: event.data.item_type,
        item_id: event.data.item_id,
        item_details: event.data.item_details
      },
      {
        headers: {
          Authorization: `Bearer ${process.env["PARTNER_API_KEY"]}`,
          "Content-Type": "application/json"
        },
        timeout: 5000
      }
    );

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

---

# Execution Environment

RevCent Functions run in a secure virtual environment using Node.js 22.x.

Important environment details:

- Functions do not share data or state across runs.
- No filesystem access.
- Dependencies are loaded with CommonJS `require()`.
- ESM `import` syntax is not supported.
- Environment variables are accessed through `process.env`.
- Function code must include an exported handler.
- Use `exports.handler = async function(event, context) { ... }` for return/throw style.
- Include `callback` as the third handler argument only when the code calls `callback(error, response)`.
- RevCent does not add the handler automatically.
- Functions can complete by returning a value, throwing an error, or calling `callback(error, response)`.
- Functions that run too long can timeout.
- Functions with too many execution errors may be disabled.

## Function Handler

Function code should include the handler:

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

The handler receives `event` and `context`. Include `callback` as the third argument only when using callback-style completion.

Correct:

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

---

# Dependencies

RevCent Functions can use dependencies that install successfully.

Example:

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

## Dependency Notes

- Any dependency may be used if it can be installed successfully.
- Package names and versions must be valid.
- `"latest"` is allowed.
- If a dependency name or version cannot be installed, the Function cannot be provisioned successfully and will error.
- Each Function has its own dependency configuration.
- After changing dependencies, allow up to 5 minutes for the new dependency set to become available.
- Use CommonJS `require()`.
- Do not use ESM `import` syntax.


# Environment Variables

Functions can use secure environment variables through `process.env`.

Environment variables are best for:

- API keys,
- per-Function secrets,
- tokens,
- endpoint URLs,
- private credentials,
- sensitive integration settings.

Example:

```javascript
const apiKey = process.env["PARTNER_API_KEY"];
```

Best practices:

- Store secrets in encrypted environment variables.
- Do not hardcode API keys in code.
- Do not return secrets in Function responses.
- Do not log secrets.
- Use clear names like `SLACK_BOT_TOKEN`, `OPENAI_API_KEY`, or `PARTNER_WEBHOOK_SECRET`.

---


---

# Event, Context, and Completion

Every Function receives:

```javascript
event
context
callback
```

## `event`

The `event` object contains the trigger-specific data.

Most business logic begins with:

```javascript
event.data
```

## `context`

The `context` object contains metadata about the Function run.

Useful context paths:

```javascript
context.source.trigger
context.source.type
context.source.method
context.source.content_type
context.source.ip_address
context.source.headers
context.source.url_params
context.function.id
context.function.name
context.function_run.id
context.dependencies
```

## Completion

A Function can complete in three ways:

- Return a value.
- Throw an error.
- Call `callback(error, response)`.

Success:

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

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
  });
};
```

If using `callback`, return afterward when code below should not continue.

---

# Business Workflow Examples

## Example: Sale Success to Fulfillment Provider

Trigger:

```text
account_event
```

Event notation:

```text
sale.created.success
```

What the Function does:

1. Reads sale details from `event.data.item_details`.
2. Builds a fulfillment API payload.
3. Sends the payload with `axios`.
4. Returns success.

---

## Example: Declined Sale Recovery

Trigger:

```text
account_event
```

Event notation:

```text
sale.created.failed.declined
```

What the Function does:

1. Reads sale and customer details.
2. Checks campaign/product eligibility.
3. Sends the customer into a recovery workflow.
4. Optionally triggers an AI Voice Agent or external CRM sequence.

---

## Example: Custom Email Receipt Data

Trigger:

```text
email_template
```

What the Function does:

1. Reads sale details from `event.data.item_details`.
2. Generates a custom footer, support contact, or product recommendation.
3. Returns a JSON object.
4. Email Template uses it as `custom_data`.

---

## Example: AI Voice Agent Sales Call

Trigger:

```text
api_direct as pre_agent_function
```

What the Function does:

1. Reads customer or sale item details.
2. Builds a list of products to offer.
3. Returns `company_name` and `product_list`.
4. AI Voice Agent instructions use Handlebars to insert that data.

---

## Example: Next-Gen Payment Profile Routing

Trigger:

```text
payment_profile
```

What the Function does:

1. Reads payment amount, customer card, gateway history, and flow path.
2. Calls an external risk API.
3. Returns `set_gateway_id`, `next_node_id`, or `custom_error`.
4. Payment flow proceeds based on the Function response.

---

## Example: Webhook From Fulfillment Partner

Trigger:

```text
webhook
```

What the Function does:

1. Receives a POST body from fulfillment partner.
2. Verifies a signature or secret.
3. Parses tracking data.
4. Updates a RevCent item or stores data externally.
5. Callback ends execution; webhook sender receives static OK response.

---

# Best Practices

## Naming

Use names that explain the trigger and purpose.

Good:

```text
Account Event - Slack Alert - Chargeback Created
Payment Profile - Gateway Decision - Risk API
AI Voice Agent - Pre-Agent - Product List
Email Template - Custom Data - Receipt
Webhook - Fulfillment Partner - Tracking Update
```

Poor:

```text
Function 1
Test
Ryan Function
```

## Descriptions

Descriptions are highly recommended.

Include:

- What triggers the Function.
- What data it receives.
- What it sends or returns.
- Any third-party dependency.
- Any required environment variables.
- Whether it affects payment, AI, email, or operational workflows.

## Error Handling

Use `try/catch`.

```javascript
try {
  // logic
  return {
    success: true
  };
} catch (error) {
  throw error;
}
```

## Security

- Use encrypted environment variables.
- Validate inbound request bodies.
- Validate webhook signatures.
- Use IP restrictions where possible.
- Avoid logging sensitive data.
- Avoid exposing secrets in responses.
- Keep payment-profile Functions fast and safe.

## Testing

Before enabling production use:

1. Confirm the trigger type.
2. Confirm the event body shape.
3. Test with realistic payloads.
4. Validate Function responses.
5. Confirm dependencies are available.
6. Confirm environment variables are set.
7. Confirm third-party API credentials work.
8. Monitor initial runs.

---

# Limitations and Operational Notes

Important limitations:

- Functions must be enabled for the account.
- There may be limits per account and per Function run volume.
- Function run time is limited.
- No filesystem access.
- Dependencies must be loaded with CommonJS `require()`.
- ESM `import` syntax is not supported.
- Dependency names and versions must be installable.
- State is not shared across Function executions.
- Console logs should be strings; stringify objects or arrays.
- Too many execution errors may automatically disable a Function.

Deployment and dependency notes:

- Use `GetFunction` to check a Function's deployment `status` after creation or dependency updates.
- `CreateFunction` starts creation deployment.
- Updating `dependencies` with `EditFunction` triggers redeployment.
- Other `EditFunction` changes, such as trigger settings or `function_code`, do not trigger redeployment.
- A Function must be `READY` before normal `EditFunction` updates. If status is `UPDATE_FAILED`, retry the dependency update after checking dependency errors.
- After creation or dependency updates, it may take up to 5 minutes for the Function to become `READY`.
- Long polling is recommended when checking deployment status.
- Do not require `READY` as a default preflight for isolated trigger, delete, or read operations.

Deployment status values:

| Status | Meaning | Update Availability | Trigger Availability |
|---|---|---|---|
| `READY` | The Function is ready. | Can be updated with `EditFunction`. | Can be triggered if configured/enabled for the trigger path. |
| `CREATING` | The Function is being created. | Cannot be updated. | Cannot be triggered. |
| `CREATE_FAILED` | Function creation failed. | Cannot be updated. | Cannot be triggered. |
| `UPDATING` | Dependencies are being redeployed after a dependency update. | Cannot be updated until deployment completes. | Can still be triggered. |
| `UPDATE_FAILED` | Dependency update failed. | Can retry the update after checking invalid dependencies or other deployment errors. | Can still be triggered. |

---

# Quick Decision Guide

| Goal | Recommended Trigger |
|---|---|
| Run code when a sale/customer/shipping/subscription event happens | `account_event` |
| Run a recurring report or sync | `schedule` |
| Expose a custom endpoint that returns data | `function_url` |
| Receive third-party POST data | `webhook` |
| Add dynamic data to Email Templates | `email_template` |
| Let API or AI trigger custom logic | `api_direct` |
| Trigger a function within an AI Assistant step | `api_direct` |
| Filter AI Assistant or AI Voice Agent execution | `api_direct` as filter Function |
| Generate dynamic AI Voice Agent instructions | `api_direct` as pre-agent Function |
| Run logic during payment processing | `payment_profile` |

---

# Summary

Functions are RevCent’s extensibility layer for ecommerce automation.

They allow ecommerce businesses to:

- React to important events.
- Integrate with third-party systems.
- Personalize customer communication.
- Automate internal operations.
- Enhance AI workflows.
- Control payment routing.
- Receive external data.
- Run scheduled tasks.
- Build custom business logic without hosting a separate server.

For most ecommerce teams, Functions are best used when a workflow is important, repeatable, and specific to the business.


---
Document Parent Directory
* [Operations](https://revcent.com/documentation/markdown/mcp/operation/index.md) - AI/MCP details and overviews for operations available within the RevCent MCP.

---
Document Parent Directory
* [Operations](https://revcent.com/documentation/markdown/mcp/operation/index.md) - AI/MCP details and overviews for operations available within the RevCent MCP.