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

# Payphone

> Charge cards on the web and Payphone app pushes in Ecuador with the Payphone Botón de Pago, API Sale, and @fire-spark/payments-payphone-checkout.

> [!WARNING]
>
> **Beta.** `@fire-spark/payments-payphone-checkout` is in beta since SDK 0.15.0. Card payments work only on the web, Payphone reverses only whole, same-day transactions by API (no partial refunds), and the Payphone error catalog is still pending. Test with a Payphone test app before going live.

Payphone (payphone.app) is an Ecuadorian payment platform. One package covers two methods:

* **Card on the web** with the **Botón de Pago por redirección**: Fire spark prepares the Payphone form, your web template opens it in a browser tab, and Fire spark confirms the payment when the customer comes back.
* **Payphone app push** with **API Sale**, for kiosks and mobile apps: Fire spark sends the charge to the customer's Payphone app, and the customer approves it there.

The Payphone token never reaches the channel: Fire spark calls Payphone with it on the server. The card is typed in Payphone's own form and never reaches your channel or Fire spark.

| | |
| - | - |
| Countries | Ecuador |
| Currencies | USD |
| Status | Available (beta) |
| Package | `@fire-spark/payments-payphone-checkout` |

| Method | Channel | What the customer does |
| - | - | - |
| Card (`CARD`) | Web | Pays in the Payphone form opened in a browser tab, then comes back to your site |
| Wallet (`WALLET`) | Kiosk, mobile app | Approves the push in their Payphone app within 5 minutes, with their Payphone balance or a card saved in the app |

## How it works

### Card (web)

1. The adapter asks Fire spark to prepare the payment (`prepare`). Fire spark calls Payphone Prepare with the token and the tender amount, and answers the form URLs.
2. Your template's **bridge** opens the Payphone form in a browser tab (a popup, a new tab, or a full-page redirect).
3. The customer pays. Payphone sends the browser back to your `responseUrl` with `id` and `clientTransactionId` in the query string.
4. The adapter asks Fire spark to confirm (`confirm`). Payphone **reverses any charge not confirmed within 5 minutes**, so the channel confirms as soon as the customer is back. The Payphone form itself lives 10 minutes.

### Wallet (kiosk and app)

1. The adapter takes the phone number from the order customer, or asks for it with `ui.input`.
2. Fire spark sends the charge to that phone with API Sale (`sale`).
3. The customer approves the push in the Payphone app within 5 minutes. The adapter shows "Aprueba el pago en tu app Payphone" and reads the status (`sale_status`) every 3 seconds.
4. A push nobody approves in time is withdrawn (`sale_cancel`), and the tender ends `FAILED` with `WALLET_EXPIRED`.

## Requirements

* A Payphone business account and an app configuration in **Payphone Developer**, with its token. Test and production use separate configurations (see [Test](#test)).
* For card: a web template on the domain registered in Payphone Developer, served over https (`localhost` works for development). Payphone forbids its form inside apps, iframes, and WebViews, so card payments are web only.
* For card: your site must send `Referrer-Policy: origin` or `origin-when-cross-origin`. With a stricter policy Payphone answers "Acceso denegado o dominio no permitido".
* For card: a `responseUrl` page on that domain that reads the return and hands it to the bridge (see [The bridge](#the-bridge)).
* For wallet: customers with the Payphone app and a phone number registered in Payphone.

## Activate it

1. In the dashboard, open your merchant, go to **Payments**, and create a payment with the provider **Payphone** and the method `CARD`, `WALLET`, or one of each.
2. In **Connection Settings**, fill in:

| Field | Key | Secret | Notes |
| - | - | - | - |
| Token | `secret_token` | Yes | Token of your app configuration in Payphone Developer. Stays in the Fire spark API; never sent to channels |
| Payphone store ID | `payphone_store_id` | No | Optional. The Payphone `storeId` of the sucursal to charge to |
| Country code | `country_code` | No | `WALLET` only. Phone country calling code sent with API Sale. Default `593` |

Payphone uses the same host for test and production: the token decides which one you charge.

### Per store

Each store can override the Payphone store ID under **Store settings** in the payment form. A store that leaves it empty uses the Connection Settings one.

| Field | When |
| - | - |
| Payphone store ID (`payphone_store_id`) | Each store charged to its own Payphone sucursal |

Fire spark charges with the store ID of the order's store.

## Use it in the SDK

```bash theme={null}
pnpm add @fire-spark/payments-payphone-checkout
```

Register the adapters your channel offers: card on the web, wallet on kiosks and apps.

```typescript theme={null}
import {
  payphoneCardPayments,
  payphoneWalletPayments
} from "@fire-spark/payments-payphone-checkout";

// Web
order.setPaymentAdapters([
  payphoneCardPayments({
    bridge, // your template's PayphoneRedirectBridge, see below
    responseUrl: "https://shop.example.com/payphone/return"
  }),
  payphoneWalletPayments()
]);

// Kiosk or mobile app
order.setPaymentAdapters([payphoneWalletPayments()]);

const result = await order.payIntent({ payment: payphonePayment });
```

The wallet phone prompt uses your payment UI (`input` in `order.setPaymentUI`), and progress messages use `message`. See [Terminal prompts and storage](https://firespark.cloud/docs/guides/payments/use-payments-in-the-sdk.md#terminal-prompts-and-storage).

`payIntent({ payment })` places one real tender. To split Payphone with another method, call `order.setTenders` with an allocation and then `payIntent()`. See [Use payments in the SDK](https://firespark.cloud/docs/guides/payments/use-payments-in-the-sdk.md).

### Card options

| Option | Required | Description |
| - | - | - |
| `bridge` | Yes | Opens the Payphone form in a browser tab and reports the return (`PayphoneRedirectBridge`) |
| `responseUrl` | Yes | https page of the registered domain where Payphone sends the customer back with `id` and `clientTransactionId` |
| `cancellationUrl` | No | https page Payphone sends the customer to when they cancel the form |
| `payWith` | No | `card` (default) opens the card form. `payphone` opens Payphone's own form to pay with the Payphone balance |
| `language` | No | `es` (default) or `en`. Language of the Payphone form |

### Wallet options

| Option | Required | Description |
| - | - | - |
| `phone` | No | `(ctx) => Promise<string \| null>`. Your own way to get the phone. Default: the order customer phone, else asked with `ui.input` |
| `phoneLabel` | No | Label of the phone prompt. Default: `Celular registrado en Payphone` |

If the customer leaves the phone prompt empty, the tender ends `FAILED` with `CANCELLED_BY_USER`.

### The bridge

The bridge is your web template's code. The package defines its shape (`PayphoneRedirectBridge`), not its UI:

| Member | Description |
| - | - |
| `open({ url, attemptReference, responseUrl, signal })` | Opens `url` in a browser tab. Resolves `{ type: "returned", id, clientTransactionId }` when the tab comes back to `responseUrl`, `{ type: "cancelled" }` if the customer closed it, or `{ type: "redirected" }` when it navigated the whole page away. Close the tab and resolve `cancelled` when `signal` aborts |
| `takeReturn(attemptReference)` | Optional. After a full-page redirect, the return saved by the `responseUrl` page for that attempt, once; else `null` |

The package exports `parsePayphoneReturn(url)`, which reads `id` and `clientTransactionId` from a return URL, or `null` if it is not one. `clientTransactionId` is the attempt reference: the adapter rejects a return for another attempt with `INVALID_REQUEST`.

> [!NOTE]
>
> The code below is an **example of your template's own code**, not part of the package. Adapt it to your router and UI.

Popup or new tab, with `postMessage` from the return page:

```typescript theme={null}
import type {
  PayphoneRedirectBridge,
  PayphoneRedirectOutcome
} from "@fire-spark/payments-payphone-checkout";

const MESSAGE = "payphone:return";

export const bridge: PayphoneRedirectBridge = {
  open: ({ url, signal }) =>
    new Promise(resolve => {
      const tab = window.open(url, "_blank");
      if (!tab) {
        // Popup blocked: fall back to a full-page redirect.
        resolve({ type: "redirected" });
        window.location.assign(url);
        return;
      }
      const finish = (outcome: PayphoneRedirectOutcome) => {
        window.removeEventListener("message", onMessage);
        clearInterval(closed);
        signal.removeEventListener("abort", onAbort);
        resolve(outcome);
      };
      const onMessage = (event: MessageEvent) => {
        if (event.origin !== window.location.origin) return;
        if (event.data?.type !== MESSAGE) return;
        finish({ type: "returned", ...event.data.back });
      };
      const onAbort = () => {
        tab.close();
        finish({ type: "cancelled" });
      };
      const closed = setInterval(() => {
        if (tab.closed) finish({ type: "cancelled" });
      }, 1000);
      window.addEventListener("message", onMessage);
      signal.addEventListener("abort", onAbort);
    }),
  takeReturn: async attemptReference => {
    const key = `payphone:return:${attemptReference}`;
    const saved = sessionStorage.getItem(key);
    if (!saved) return null;
    sessionStorage.removeItem(key);
    return JSON.parse(saved);
  }
};
```

The `responseUrl` page sends the return to the opener, or saves it for `takeReturn` after a full-page redirect:

```typescript theme={null}
import { parsePayphoneReturn } from "@fire-spark/payments-payphone-checkout";

const back = parsePayphoneReturn(window.location.href);

if (back && window.opener) {
  // Popup or new tab: hand the return to the checkout and close.
  window.opener.postMessage(
    { type: "payphone:return", back },
    window.location.origin
  );
  window.close();
} else if (back) {
  // Full-page redirect: save it for bridge.takeReturn, then go back to
  // your checkout, which resumes the pending tender.
  const key = `payphone:return:${back.clientTransactionId}`;
  sessionStorage.setItem(key, JSON.stringify(back));
}
```

After a `redirected` outcome the tender stays `PENDING`. When the adapter queries it, it calls `takeReturn` and confirms the return as soon as it is there. Confirm within 5 minutes of the payment, or Payphone reverses it.

## Amounts and taxes

Fire spark computes the amounts on the server, in cents, from the order lines: untaxed lines go to `amountWithoutTax`, taxed lines without their tax to `amountWithTax`, and the tax to `tax`. Each part is prorated to the tender amount, and they add up to it exactly. The device never sends an amount. Fire spark also sends the cardholder's email, phone, and ID number from the order customer when it has them.

## Storefront endpoints

The adapters call these through the payment server operations. They use the storefront session.

| Endpoint | Method | What it does |
| - | - | - |
| `POST /api/storefront/v1/payments/{payment_id}/operations/prepare` | `CARD` | Prepares the Payphone form for the current payment attempt and returns its URLs. Takes `response_url`, `cancellation_url`, and `lang`; both URLs must be https (or `localhost`). The amount comes from the tender, never from the request |
| `POST /api/storefront/v1/payments/{payment_id}/operations/confirm` | `CARD` | Confirms the return (`id`, `client_transaction_id`) and returns the outcome (`PAID`, `FAILED`, or `PENDING`) |
| `POST /api/storefront/v1/payments/{payment_id}/operations/sale` | `WALLET` | Sends the charge to the customer's Payphone app (`phone_number`) |
| `POST /api/storefront/v1/payments/{payment_id}/operations/sale_status` | `WALLET` | Status of this attempt's push |
| `POST /api/storefront/v1/payments/{payment_id}/operations/sale_cancel` | `WALLET` | Withdraws a push that is still pending |

## What the customer sees

On the web, the Payphone form in a browser tab, then your `responseUrl` page. On kiosks and apps, your phone prompt (when the order has no phone) and the waiting message while they approve in the Payphone app.

A paid card tender records `details` with the card brand, last 4 digits, and authorization code. A wallet tender (or a card payment made with the Payphone balance) records `method: "WALLET"`, `wallet: "payphone"`, and a reference. The result metadata includes `attempt_reference`, `payment` (`provider_transaction_id`, `authorization_code`, `reference`, `brand`, `card_type`, `last4`), and `provider` (`transaction_id`, `client_transaction_id`, `status_code`, `deferred`). There is no voucher.

## Timeouts and unknown results

* One card attempt lasts up to 15 minutes; one wallet attempt up to 6 minutes. Neither is retried automatically: a retry would be a new charge.
* If Payphone does not answer within 30 seconds, the tender ends `FAILED` with `AMBIGUOUS` and `needs_review`. Check the transaction in Payphone Business.
* A card charge that is never confirmed is reversed by Payphone itself after 5 minutes.
* Fire spark does not use Payphone's status webhook ("notificación externa"): it needs Payphone to enable it and is not signed. The adapters read the status themselves.

## Refunds

Fire Spark reverses a paid Payphone charge on the server when you call `order.cancel()` or `order.refund()`, with the payment's token (Payphone Reverse by transaction id). The device does nothing: the adapter reports the reversal as `server`.

* **Whole transaction only.** A partial refund is not sent to Payphone: the ledger operation fails and you refund it by hand in Payphone Business.
* **Same day only.** Payphone reverses a transaction only until 23:59 Ecuador time of the day it was paid. After that the reversal fails: refund it by hand in Payphone Business.
* An attempt that was never charged is just discarded.

A failed reversal stays in the order's payment ledger with Payphone's reason, for an operator to finish.

## Common errors

| Spark code | Payphone cause | What to do |
| - | - | - |
| `CARD_DECLINED` | `statusCode` `2` on a card payment | Ask for another card or method |
| `WALLET_REJECTED` | `statusCode` `2` on a push, or the push was refused | Ask for another method |
| `WALLET_EXPIRED` | Nobody approved the push within 5 minutes | Send the push again with a new attempt |
| `CANCELLED_BY_USER` | The customer closed the form, or left the phone prompt empty | Offer the method again |
| `AMBIGUOUS` | No answer, or `errorCode` `20`, `25` | Flagged for review (`needs_review`). Check the transaction in Payphone Business |
| `INVALID_CREDENTIALS` | Token missing or rejected (HTTP 401, 403) | Check `secret_token` in Connection Settings |
| `INVALID_REQUEST` | `responseUrl` or `cancellationUrl` not https, phone shorter than 7 digits, a return for another attempt, Payphone validation errors (`errorCode` `2029`) | Fix the URLs or the phone and try again |
| `PROVIDER_UNAVAILABLE` | HTTP 5xx, 429 | Try again with a new attempt |

The package exports the Payphone code map as `payphoneErrors`. Codes it does not know fall back to `CARD_DECLINED` (card) or `WALLET_REJECTED` (wallet). See [Payment errors](https://firespark.cloud/docs/guides/payments/errors.md).

## Test

Create a **test configuration** in Payphone Developer and paste its token in Connection Settings. A Payphone test app approves every transaction: there are no banks and no real charges.

1. Invite your testers from the Payphone app, so they can pay with their own Payphone accounts.
2. Pay a card or wallet tender from your channel.
3. Review the transactions in Payphone Developer, under **Probadores** > **Transacciones**.

Card payments work from `localhost` during development, with the `Referrer-Policy` above.

## Compatibility

| `@fire-spark/payments-payphone-checkout` | Provider | `@fire-spark/payments` |
| - | - | - |
| 0.15.0 (beta) | Payphone Botón de Pago + API Sale | Same version |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.