# 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.

Source:
- RevCent Knowledge Base: Functions — `https://kb.revcent.com/en/integrations/functions`
- RevCent Knowledge Base: Key Values — `https://kb.revcent.com/en/tools/key-value`

---

## 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.
- Read Key Values for account-wide shared configuration.
- Update string Key Values for state management, cursors, and feature flags.
- Use supported Node.js dependencies.
- Make outbound internet requests.

Functions are executed in a secure virtual environment using Node.js 20.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. |
| Function state / shared configuration | Read Key Values and update string Key Values for cursors, checkpoints, feature flags, thresholds, and reusable settings. |
| 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;

callback(null, {
  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;

callback(null, {
  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
callback(null, {
  custom_property: "custom value"
});
```

Incorrect:

```javascript
callback(null, "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
callback(null, "pass");
```

or:

```javascript
callback(null, "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
callback(null, {
  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
callback(null, {
  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, whitelisted 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 = global["axios"];

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 20.x.

Important environment details:

- Functions do not share data or state across runs.
- No filesystem access.
- No `require()` or `import`.
- Dependencies are accessed through the `global` object.
- Environment variables are accessed through `process.env`.
- Function code is already wrapped in a handler with `event`, `context`, and `callback`.
- Always call `callback` to end the Function run.
- Functions that run too long can timeout.
- Functions with too many execution errors may be disabled.

## Handler Wrapper

RevCent already wraps Function code in:

```javascript
function(event, context, callback) {
  // your code runs here
}
```

Do not include this wrapper in your code.

Correct:

```javascript
callback(null, {
  success: true
});
```

Incorrect:

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

---

# Dependencies

RevCent Functions do not support `require()` or `import`.

Dependencies are made available through:

```javascript
global["module_name"]
```

Example:

```javascript
const axios = global["axios"];
const moment = global["moment"];
const lodash = global["lodash"];
```

## Dependency Notes

- Dependencies must be selected from the allowed dependency list.
- Each Function has its own dependency configuration.
- After changing dependencies, allow up to 2 minutes for the new bundle to become available.
- If a needed dependency is not available, contact RevCent.

## Common Dependencies

| Dependency | Use |
|---|---|
| `axios` | HTTP requests. |
| `@slack/web-api` | Slack integration. |
| `@sendgrid/mail` | SendGrid email. |
| `twilio` | SMS and voice integrations. |
| `openai` | OpenAI API calls. |
| `lodash` | Data manipulation. |
| `moment` / `moment-timezone` | Dates and timezones. |
| `jsonwebtoken` | JWT signing or verification. |
| `crypto-js` | Hashing and HMAC signatures. |
| `shippo` | Shipping integrations. |
| `klaviyo-sdk` | Klaviyo integration. |
| `activecampaign` | ActiveCampaign integration. |
| `mongodb`, `mysql`, `pg`, `redis` | Database integrations. |
| `validator`, `ajv` | Input and JSON schema validation. |

---

# Environment Variables and Key Values

Functions can use secure environment variables through `process.env` and can access account-wide Key Values through the RevCent Function object.

There are two main concepts:

| Source | Scope | Use |
|---|---|---|
| Function environment variables | Specific Function | API keys, per-Function secrets, tokens, endpoint URLs. |
| Key Values | Account-wide | Shared configuration, state cursors, feature flags, non-secret thresholds, pointer aliases. |

Environment variables are best for secrets. Key Values are best for shared state and non-secret account-wide configuration.

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 callback responses.
- Do not log secrets.
- Use clear names like `SLACK_BOT_TOKEN`, `OPENAI_API_KEY`, or `PARTNER_WEBHOOK_SECRET`.

---


---

# Key Values in Functions

Key Values are account-wide values that Functions can read and, for string Key Values, update.

They are one of the most useful ways for Functions to maintain shared configuration or persistent state between runs.

Functions can read Key Values with:

```javascript
global["revcent"].GetKeyValue(my_key, callback)
```

Functions can update string Key Values with:

```javascript
global["revcent"].UpdateKeyValue(my_key, value, callback)
```

Important:

```text
Functions can update only string Key Values.
Pointer Key Values cannot be updated within a Function.
```

---

## Why Key Values Matter for Functions

Functions often need memory or configuration.

Examples:

```text
A scheduled Function needs to remember when it last ran.
A sync Function needs to remember the last external cursor.
A fraud alert Function needs to check whether alerts are enabled.
A reporting Function needs a last processed sale ID.
A customer segmentation Function needs a configurable lifetime value threshold.
```

Without Key Values, this state may need to be hardcoded, stored externally, or recalculated every run.

With Key Values, Functions can store small account-wide values directly in RevCent.

---

## Common Key Value Use Cases in Functions

| Use Case | Example Key | Purpose |
|---|---|---|
| Last processed cursor | `last_processed_sale` | Prevent duplicate processing. |
| Scheduled report checkpoint | `daily_report_cursor` | Track the last successful report run. |
| External sync cursor | `shipping_sync_cursor` | Resume external API syncs. |
| Feature flag | `fraud_alerts_enabled` | Turn logic on/off without editing Function code. |
| Dynamic threshold | `vip_ltv_threshold` | Change business thresholds without code edits. |
| Shared config | `support_email` | Reuse account-wide configuration. |
| Payment profile pointer | `active_payment_profile` | Read an account-wide payment profile alias. |

---

## Example: Reading a Feature Flag

```javascript
global["revcent"].GetKeyValue("fraud_alerts_enabled", function(error, value) {
  if (error) {
    callback(error);
    return;
  }

  if (value !== "true") {
    callback(null, {
      skipped: true,
      reason: "Fraud alerts are disabled."
    });
    return;
  }

  callback(null, {
    skipped: false,
    alerts_enabled: true
  });
});
```

---

## Example: Updating a Scheduled Cursor

```javascript
global["revcent"].GetKeyValue("daily_report_cursor", function(error, value) {
  if (error) {
    callback(error);
    return;
  }

  let state = {};
  try {
    state = JSON.parse(value || "{}");
  } catch (parseError) {
    callback(parseError);
    return;
  }

  // Use the previous state to decide what data to process.

  const nextState = JSON.stringify({
    last_run_unix: Math.floor(Date.now() / 1000),
    last_processed_sale_id: "XXXXXXXXXXXXXXXXXXXX"
  });

  global["revcent"].UpdateKeyValue("daily_report_cursor", nextState, callback);
});
```

---

## Key Values vs Environment Variables

Key Values and environment variables have different jobs.

| Feature | Best For |
|---|---|
| Key Values | Shared account-wide configuration, cursors, state, feature flags, non-secret thresholds. |
| Environment Variables | API keys, passwords, tokens, private credentials, Function-specific secrets. |

Do not store secrets in Key Values unless the business has explicitly decided that is appropriate and RevCent documentation supports the use case.

Use environment variables for secrets.

Use Key Values for state and non-secret shared configuration.

---

## Key Values vs Metadata

Key Values are not metadata.

| Feature | Scope |
|---|---|
| Key Value | Account-wide value accessed by key. |
| Metadata | Data attached to a specific RevCent item. |

Use metadata when the value belongs to a specific customer, sale, subscription, transaction, or other item.

Use Key Values when the value is account-wide or needs to persist between Function executions.

---

## Best Practices for Function State

1. Use string Key Values for Function-managed state.
2. Store structured state as JSON strings.
3. Parse JSON carefully and handle parse errors.
4. Keep state values small and under the Key Value size limit.
5. Retrieve current state before updating.
6. Avoid multiple Functions writing to the same key unless intentionally designed.
7. Do not update pointer Key Values from inside Functions.
8. Do not use Key Values as a secret store.
9. Always call `callback` to end execution.
10. Return after calling `callback` when code continues below.


# Event, Context, and Callback

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
```

## `callback`

The `callback` function ends the Function run.

Success:

```javascript
callback(null, {
  success: true
});
```

Error:

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

Always call `callback` to avoid timeouts.

---

# 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
  callback(null, {
    success: true
  });
} catch (error) {
  callback(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 callback 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.
- No `require()` or `import`.
- Dependencies must be whitelisted.
- 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.

Provisioning and dependency notes:

- Creating a Function may take a couple of minutes to provision.
- Dependency updates may take up to 2 minutes to bundle and become available.
- Test after provisioning and dependency installation are complete.

---

# 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.