> ## Documentation Index
> Fetch the complete documentation index at: https://docs.asapp.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Voice Payment Collection

> Collect card payments from callers over the phone with GenerativeAgent, keeping card data in a PCI-secure zone.

<Note>
  Voice payment collection is available on voice tasks only. Card digits are captured in a PCI-secure zone and are never exposed to GenerativeAgent or written to conversation logs. GenerativeAgent sees only masked outcomes (card brand and last four digits).
</Note>

A voice payment function lets GenerativeAgent collect a card payment from a caller without leaving the supervised conversation. GenerativeAgent guides the caller through entering their card details on the keypad, confirms a masked summary, and runs the charge or tokenization through the API connections you configure.

By using a voice payment function, you can:

* Collect a one-time card payment during a voice call.
* Tokenize a card for later or recurring use.
* Let the caller ask questions or cancel partway through without a partial charge.
* Send the payment outcome to your systems through success and failure connections.

## How it works

At a high level, GenerativeAgent runs the payment conversation while card data stays in a PCI-secure zone that GenerativeAgent never sees:

1. **Gather what's needed** from the conversation: GenerativeAgent collects any input parameters from context or by asking the caller.
2. **Start the session**: GenerativeAgent calls your start connection, which returns the payment details such as amount, currency, and which fields to collect.
3. **Collect the card**: GenerativeAgent guides the caller to enter card digits on the keypad, captured in the PCI-secure zone, then reads back a masked summary to confirm.
4. **Run the payment**: once the caller confirms, the charge or tokenization runs through your processor.
5. **Report the outcome**: GenerativeAgent calls your success or failure connection and reads the matching message to the caller.

A payment session behaves differently from a normal GenerativeAgent conversation:

* **A payment session is deterministic:** Once GenerativeAgent starts a session, collection becomes a fixed, step-by-step loop through each field (card number, expiry, security code, postal code), with validation and per-field retries. GenerativeAgent does not decide what to ask next during collection.
* **GenerativeAgent stays in supervision:** The caller can still speak at any point. GenerativeAgent can answer a question and resume, or cancel the payment. Deterministic collection and live supervision run together.
* **Payment details are derived programmatically:** The amount, currency, fields to collect, and whether to charge or tokenize all come from the start connection, which is your own logic. GenerativeAgent never sets a charge amount.
* **The LLM never sees the card data:** Card digits are collected out of band in the PCI-secure zone, separate from the conversation. GenerativeAgent receives only masked outcomes (brand and last four).
* **ASAPP assists collection; it is not the processor:** ASAPP assists the out-of-band collection of card data, then reaches out to your payment provider to run the charge or tokenization. Your provider and the connection you configure remain the system of record for the payment.

<Note>
  GenerativeAgent never sets the amount and never sees raw card data. The start connection is the source of truth for what to charge, card entry happens out of band in the PCI-secure zone, and ASAPP reaches out to your payment provider to process it.
</Note>

<Accordion title="Detailed Flow">
  Here's how a payment collection works in detail:

  1. GenerativeAgent gathers the input parameters you defined, from conversation context or by asking the caller. Input variables and reference variables are already available.
  2. GenerativeAgent calls the start connection with the Set variables. The connection returns the payment details: amount, currency, the fields to collect, and any processor parameters.
  3. GenerativeAgent reads the disclaimer and the amount confirmation, then guides the caller field by field. Card digits are entered on the keypad and captured in the PCI-secure zone; GenerativeAgent never receives raw digits.
  4. GenerativeAgent reads a masked summary (card brand and last four). The caller confirms or cancels.
  5. On confirmation, the charge or tokenization runs through the processor.
  6. On success, the success connection fires with the masked outcome and any transaction or token id, and GenerativeAgent reads the success message. On a terminal failure, the failure connection fires with a `failed_reason`, and GenerativeAgent reads the failure message and follows the configured fallback.

  ```mermaid theme={null}
  sequenceDiagram
      participant C as Caller
      participant GA as GenerativeAgent
      participant Start as Start connection
      participant PCI as PCI-secure collection
      participant Proc as Payment processor
      participant CB as Success / Failure connection

      GA->>GA: Gather input parameters from context or by asking the caller
      GA->>Start: Send Set variables (input and reference variables available)
      Start-->>GA: Return payment details \(amount, currency, fields to collect\)
      GA->>C: Read disclaimer and amount confirmation
      C->>PCI: Enter card digits on the keypad

      Note over GA,PCI: Card data stays in the PCI-secure zone. GA never sees raw digits
      
      GA->>C: Read masked summary (brand, last4)
      C->>GA: Confirm
      GA->>Proc: Run charge or tokenization
      alt Success
          Proc-->>CB: Success connection fires (masked outcome, transaction or token id)
          GA->>C: Read success message
      else Failure
          Proc-->>CB: Failure connection fires (failed_reason, last_error)
          GA->>C: Read failure message and follow the fallback
      end
  ```
</Accordion>

To set up voice payment collection:

1. [Create the function](#step-1-create-the-function)
2. [Define input parameters](#step-2-define-input-parameters-json)
3. [Set variables](#step-3-set-variables)
4. [Wire up the API connections](#step-4-wire-up-the-api-connections)
5. [Configure messages and collection limits](#step-5-configure-messages-and-collection-limits)
6. [Write the task prompt](#step-6-write-the-task-prompt)

## Step 1: Create the Function

Navigate to the Functions page and click "Create Function."

1. Select the voice payment function type and click "Next: Function details."
   <Frame>
     <img src="https://mintlify.s3.us-west-1.amazonaws.com/asapp/images/generativeagent/StartPaymentSessionFunction.png" alt="TODO: screenshot of selecting the voice payment function type" />
   </Frame>
2. Specify the Name and Purpose of the function.
   * **Function Name**: Provide a concise, unique name, using underscores (e.g., `collect_payment`).
   * **Function Purpose**: Briefly describe when GenerativeAgent should collect a payment (e.g., "Collects a card payment for the caller's outstanding balance once they agree to pay").
     * GenerativeAgent uses this description to determine if and when to call the function.

## Step 2: Define Input Parameters (JSON)

GenerativeAgent already has access to the [input variables](/generativeagent/configuring/tasks-and-functions/input-variables) and [reference variables](/generativeagent/configuring/tasks-and-functions/reference-variables) resolved earlier in the conversation, and those are available automatically to the start connection.

Use input parameters for anything the payment needs that isn't already known, for example the cardholder's name or billing address. For each input parameter you define, GenerativeAgent gets the value from conversation context or asks the caller for it.

Under "Input Parameters," enter a valid JSON schema describing what to collect.

```json Example Input Schema theme={null}
{
  "type": "object",
  "required": ["cardholder_name"],
  "properties": {
    "cardholder_name": {
      "type": "string",
      "description": "The name on the card; asked if not already known"
    },
    "billing_address": {
      "type": "string",
      "description": "The billing address for the card"
    }
  }
}
```

## Step 3: Set Variables

Set variables map to the actual input fields your start connection expects. Each Set variable can pull from:

* an input parameter, with `params.X`
* a reference variable resolved earlier in the conversation, with `refs.X`
* a static value

[Jinja2](https://jinja.palletsprojects.com/en/stable/) is fully supported in these fields, so you can rename, combine, or transform values before they reach the connection.

```jinja2 theme={null}
{{vars.get("order_id")}}
```

## Step 4: Wire Up the API Connections

A voice payment function uses three [API connections](/generativeagent/configuring/connect-apis). Tag each connection with the matching Application so it appears in the correct slot. Each slot's picker shows only connections carrying that tag.

* **Payment session start** (required): resolves the payment details for this call.
* **Payment session success** (optional): receives the outcome after a successful charge or tokenization.
* **Payment session failure** (optional): receives a reason after a terminal failure.

### Start connection

GenerativeAgent calls the start connection with the flat Set variables as input. Your connection returns the details for this payment session.

```json Start connection response theme={null}
{
  "amount": 4200,
  "currency": "USD",
  "description": "Order #10482",
  "processor_parameters": 
  { 
  "invoice_id": "INV-10482",
  "min_postal_code_length": 5,
  "is_postal_code_required": true,
  "is_security_code_required": true,
  "valid_card_types": ["visa", "amex"],
  "allowed_payment_types": ["credit-card"],
  "token_type": "one-time"
  }
}
```

* `amount`: amount to charge. `0` indicates tokenization or subscription setup.
* `currency`: ISO 4217 currency code.
* `description`: free text passed through with the payment.
* `processor_parameters`: an arbitrary object passed through to your payment processor. Use it for reconciliation IDs and processor-specific fields. It is echoed back on the success and failure connections.
* `min_postal_code_length`, `is_postal_code_required`, `is_security_code_required`: control which fields GenerativeAgent collects.
* `valid_card_types`: card brands accepted for this session.
* `allowed_payment_types`: payment types accepted for this session.
* `token_type`: only meaningful when `amount` is `0`. One of `one-time`, `reusable`, `payment-method`.

### Success connection

GenerativeAgent calls the success connection once on a successful charge or tokenization. The request carries your Set variables as flat fields plus the payment result. Your endpoint returns any `2xx` response as an acknowledgment.

```json Success connection request theme={null}
{
  "session_reference_id": "ps_8f21c0",
  "order_id": "10482",
  "email": "caller@example.com",
  "transaction_id": "ch_9aa312",
  "token_id": null,
  "processor_parameters": { "invoice_id": "INV-10482" }
}
```

`transaction_id` and `token_id` appear at the root level when your connector exposes them. Some connectors return one, the other, or neither, depending on whether the charge or token is handled in your integration.

### Failure connection

GenerativeAgent calls the failure connection once on a terminal failure. Branch on `failed_reason` to drive your recovery logic.

```json Failure connection request theme={null}
{
  "session_reference_id": "ps_8f21c0",
  "order_id": "10482",
  "email": "caller@example.com",
  "processor_parameters": { "invoice_id": "INV-10482" }
}
```

## Step 5: Configure Messages and Collection Limits

Configure the prompts GenerativeAgent reads to the caller during collection, along with the collection limits.

Messages:

* `disclaimer`: read once before collection starts.
* `before_starting_session`: read after the start connection resolves, before collection begins. Can reference values from the start connection response (e.g., "You will be charged \$42.00 for order 10482, is that okay?").
* `credit_card`: read when collecting the card number.
* `security_code`: read when collecting the security code.
* `confirmation_message`: read as the masked summary before the caller confirms.
* `collection_error`: read when a field fails and the caller is asked to retry.
* `payment_error`: read when the payment is unsuccessful.
* `payment_success`: read when the payment completes successfully.

Collection limits:

* **Per-field retry limit**: the maximum number of retries per field before the session ends as a failure.
* **Inter-digit timeout**: the seconds allowed between keypad presses before the entry is treated as stalled.

## Step 6: Write the Task Prompt

Add the function to the task's list of available functions so GenerativeAgent can use it. GenerativeAgent reads each configured message to the caller and listens for caller speech throughout collection, so the caller can ask questions or change course at any point.

Write prompt instructions for the escape paths you want to support:

* Answer a question about the order or amount, then resume collection.
* Switch to a different card.
* Cancel the payment.

A companion cancel function is available to GenerativeAgent automatically whenever a payment session is active. When the caller cancels, GenerativeAgent ends the session without a charge.

<Accordion title="Example task instructions for collecting a payment">
  ```jinja theme={null}
  # Objective
  Collect payment for the caller's outstanding order once they agree to pay.

  # Instructions
  1. Confirm the caller wants to pay for order {{ refs.order_id }}.
  2. Call the `collect_payment` function to start collection.
  3. If the caller asks a question mid-payment, answer it, then continue collection.
  4. If the caller wants to stop, cancel the payment without charging.
  5. On success, confirm the payment and offer further help.
  6. On failure, read the failure message and offer to retry or transfer to an agent.
  ```
</Accordion>

### Best Practices

<AccordionGroup>
  <Accordion title="Write prompts for the ear, not the eye">
    Callers hear these messages read aloud. Keep prompts short and unambiguous, and state amounts and order details plainly in `before_starting_session` and `confirmation_message`.
  </Accordion>

  <Accordion title="Use processor_parameters for reconciliation">
    Pass invoice or order IDs through `processor_parameters` from the start connection. They are echoed back on the success and failure connections, so you can match an outcome to the original request.
  </Accordion>

  <Accordion title="Always configure a failure connection">
    A failure connection gives you a single signal to branch on for declines, abandonment, and timeouts. Without it, your systems learn about failures only through your own reconciliation.
  </Accordion>

  <Accordion title="Plan recovery in the task prompt">
    Decide what happens after a failed payment: offer a retry, transfer to a live agent, or end the call gracefully. Spell this out in the task prompt so GenerativeAgent handles it consistently.
  </Accordion>
</AccordionGroup>

## Payment Providers

Reach out to ASAPP to set up your preferred payment provider. ASAPP works with you to connect it and determine how collected card data is sent for processing. The function setup described here is the same regardless of which provider you use.

## Next Steps

<CardGroup>
  <Card title="Task Best Practices" href="/generativeagent/configuring/task-best-practices">
    Learn more about best practices for task and function configuration.
  </Card>

  <Card title="Connecting Your APIs" href="/generativeagent/configuring/connect-apis">
    Create and tag the API connections used for the payment session slots.
  </Card>

  <Card title="Handling Events" href="/generativeagent/integrate/handling-events">
    See how GenerativeAgent communicates with your backend systems.
  </Card>

  <Card title="Previewer" href="/generativeagent/configuring/previewer">
    Test your functions in real time with the Previewer tool.
  </Card>
</CardGroup>
