> For the complete documentation index, see [llms.txt](https://docs.perkville.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.perkville.com/features/redeeming-rules/using-middle-to-automate-rewards/real-time-redemption-responses.md). Agents can also search and read this documentation through its [MCP server](https://docs.perkville.com/~gitbook/mcp).

# Real-time redemption responses

Perkville classifies each Middle redemption as successful, rejected, or uncertain. For ordinary points redemptions, this determines whether the redemption commits, whether points are deducted, and which voucher status is saved. [Automatic challenge rewards](#automatic-challenge-rewards) have a separate fulfillment lifecycle.

When fulfillment is uncertain, Perkville preserves the points deduction and records an error because Middle may already have applied the reward. A workflow can also explicitly decline fulfillment and tell Perkville to roll back the redemption.

See [Real-time redemption requests](https://docs.perkville.com/features/redeeming-rules/using-middle-to-automate-rewards/real-time-redemption-requests.md) for the endpoint, authentication, and payload sent to the workflow.

## Response contract

The workflow’s Return step must define an object containing these fields:

| Field             | Type                                                                            | Purpose                                                                                                              |
| ----------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `success`         | Middle returned HTTP 200 with outer `success: true` and `output.success: true`. | Deduct points and save the voucher with status `MIDDLE`.                                                             |
| `success_message` | String                                                                          | Instructions shown on the voucher after successful fulfillment. Use an empty string when no instructions are needed. |
| `error_message`   | String                                                                          | Customer-facing reason when fulfillment is declined. Use an empty string when there is no error.                     |

Perkville checks this output schema when loading workflow choices. Middle wraps the Return step’s object in an HTTP response with an outer `success` field and an `output` object. The two success fields have different meanings: outer `success` reports whether Middle executed the workflow successfully; `output.success` reports whether the reward was fulfilled. Return JSON booleans `true` or `false`, not strings.

### Successful fulfillment

HTTP `200`:

```json
{
  "success": true,
  "output": {
    "success": true,
    "success_message": "Your smoothie credit has been added.",
    "error_message": ""
  }
}
```

Perkville commits the ordinary redemption, deducts points, and saves a `MIDDLE` voucher. A nonempty `success_message` becomes its redemption instructions. If the message is empty or absent, the instructions remain blank.

### Declined fulfillment

To decline fulfillment without deducting points in an ordinary redemption, return HTTP `200` with outer `success: true` and `output.success: false`:

```json
{
  "success": true,
  "output": {
    "success": false,
    "success_message": "",
    "error_message": "This reward is not available at this location."
  }
}
```

Perkville rolls back the ordinary redemption and displays `output.error_message`. If that message is empty, it displays “This reward is temporarily unavailable. Please try again later.” Only return this result when the reward has not been applied. An HTTP `200` response with outer `success: false` is classified as an error rather than a declined fulfillment.

## Outcomes

| Outcome     | Meaning                                                                                                                                                                               | Points and voucher behavior                                                          |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `success`   | Middle confirmed the workflow completed.                                                                                                                                              | Deduct points and save the voucher with status `MIDDLE`.                             |
| `no_deduct` | The workflow explicitly declined fulfillment, the request could not connect, or another failure is classified as safe to roll back.                                                   | Roll back the ordinary redemption. No points are deducted and no voucher is created. |
| `error`     | The result is ambiguous and the workflow may already have executed, so Perkville deducts the points and saves a voucher with `MIDDLE_ERROR` status rather than risk running it again. | Deduct points and save the voucher with status `MIDDLE_ERROR`.                       |

### How responses and failures are classified

| Situation                                                                                                                   | Classification   | Result                                                       |
| --------------------------------------------------------------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------ |
| Missing Middle API key or workflow URL                                                                                      | Validation error | No request is sent; roll back the redemption.                |
| Cannot establish a connection to Middle                                                                                     | `no_deduct`      | Roll back and show a temporary-unavailable message.          |
| HTTP 4xx response with an allowlisted error code                                                                            | `no_deduct`      | Roll back; no points are deducted and no voucher is created. |
| Valid workflow result with `output.success = false`                                                                         | `no_deduct`      | Roll back and use Middle’s `error_message` when available.   |
| Request timeout                                                                                                             | `error`          | Deduct points and save a `MIDDLE_ERROR` voucher.             |
| Other `requests.RequestException`                                                                                           | `error`          | Deduct points and save a `MIDDLE_ERROR` voucher.             |
| HTTP 5xx or another non-200 response not classified above                                                                   | `error`          | Deduct points and save a `MIDDLE_ERROR` voucher.             |
| HTTP 4xx response with a runtime or unknown error code                                                                      | `error`          | Deduct points and save a `MIDDLE_ERROR` voucher.             |
| Invalid response JSON                                                                                                       | `error`          | Deduct points and save a `MIDDLE_ERROR` voucher.             |
| HTTP 200 response object with top-level `success` not true, missing or non-object `output`, or non-Boolean `output.success` | `error`          | Deduct points and save a `MIDDLE_ERROR` voucher.             |

A connection failure is treated as safe to roll back because Perkville assumes the workflow was never reached. A timeout is ambiguous because Middle may have completed the workflow after Perkville stopped waiting.

#### HTTP 4xx errors that do not deduct points

Perkville automatically rolls back an HTTP 4xx response only when its error code appears in this allowlist:

```
INVALID_AUTHORIZATION_HEADER
AUTHENTICATION_FAILED
API_ENDPOINT_NOT_FOUND
API_ENDPOINT_NOT_LIVE
API_TRIGGER_NOT_LIVE
REQUEST_TOO_LARGE
INVALID_JSON
INVALID_REQUEST_BODY
WORKFLOW_NOT_LIVE
WORKFLOW_NOT_API_ELIGIBLE
RESPONSE_TOO_LARGE
```

All other 4xx codes—including workflow-runtime errors and unknown future codes—are treated as ambiguous.

If Middle introduces a new error code for a failure that occurs before execution, Perkville may deduct points for that error until the code is added to the allowlist.

`RESPONSE_TOO_LARGE` is currently in the no deduction allowlist, but it can occur when the completed response exceeds Middle’s 256 KiB limit. Do not interpret that code as proof that no external action occurred. Keep the workflow’s response small.

## Customer-facing behavior

### Rejected or unavailable redemptions

A `no_deduct` result is returned as a failed redemption. The customer sees either:

* The workflow-provided rejection message, such as a location-specific restriction.
* A generic temporary-unavailable message.

The redemption is rolled back, so the customer keeps their points.

### Unconfirmed redemptions

For a `MIDDLE_ERROR` voucher, the customer sees a message explaining that Perkville could not confirm the redemption and that the request may nevertheless have been processed.

If the normalized result contains a usable workflow error message, that message is preferred. Otherwise, Perkville displays the generic ambiguity warning.

Runtime 4xx error messages are logged but are deliberately excluded from the customer-facing response: the helper sets their `error_message` to `None`.

### Voucher status labels

| Voucher status | Internal display label      |
| -------------- | --------------------------- |
| `MIDDLE`       | Redeemed automatically      |
| `MIDDLE_ERROR` | Automated redemption failed |

The `MIDDLE_ERROR` display label does not establish whether the reward was applied in the external system.

## Automatic challenge rewards

Challenge rewards using deferred external credit are committed before Middle is called. Perkville first saves the voucher as `PENDING_EXTERNAL_CREDIT` and queues fulfillment after the reward transaction commits. Before contacting Middle, the worker changes it to `CHALLENGE_CREDIT_UNCERTAIN` so another worker will not automatically fulfill the same voucher again.

A successful Middle response saves `MIDDLE`. If the attempt raises an exception, the voucher remains `CHALLENGE_CREDIT_UNCERTAIN`. If the call returns `MIDDLE_ERROR`, the worker changes it to `CHALLENGE_CREDIT_UNCERTAIN` for review. A `no_deduct` response raises a validation error in this path and also leaves the already committed challenge reward requiring review; it does not roll back that reward as it would an ordinary redemption.

## Retries and troubleshooting

Perkville’s redemption request helper does not automatically retry the POST. Middle starts a new execution for every request that reaches the workflow and does not support an API idempotency key. Before retrying a timeout or uncertain redemption, check Middle’s workflow history and the downstream system to determine whether the reward was already applied.

For workflows that may be retried, use downstream duplicate protection based on `transaction_id` where the receiving system supports it. The same transaction ID is not automatically deduplicated by Middle.

Middle can include `workflow_report_url` and `warnings` in its response, but Perkville’s redemption helper does not retain those fields. Use the request’s `transaction_id` to correlate workflow inputs with the Perkville redemption.

When investigating a failure, check the business’s API key, the reward’s selected invoke URL, the endpoint’s linked keys and active state, the workflow’s live version, and both success fields in the response. See the [Middle Real-time Workflow API](https://docs.middle.app/middle-docs/product/real-time-workflow-api) for authentication, endpoint access, execution errors, and limits.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.perkville.com/features/redeeming-rules/using-middle-to-automate-rewards/real-time-redemption-responses.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
