# Credit or Debit card

Learn how to accept online payments by credit or debit card using the Stark Bank platform.

We use a resource called Merchant Purchase to represent each card payment. In this guide, you'll learn how to manage the main use cases and understand the payment life cycle.

Since sensitive card data should never pass through your server, we created the Merchant Session. It lets you set up a secure, temporary session so your website or app can send card details directly to Stark Bank.

After a purchase is created, Stark Bank splits it into one or more installments — even single payments get one — so you can track exactly when each amount will land in your account.

NOTE: Read [Core Concepts](https://docs.starkbank.com/get-started/core-concepts.md) before continuing this guide.

**RESOURCE SUMMARY**

**Merchant Purchase**The card payment you charge your customer.**Merchant Installment**Each scheduled payment from a purchase, credited to your account.**Merchant Session**Secure session that lets your website send card data directly to Stark Bank.**Merchant Card**Saved card details for repeat purchases.

## Available Languages

Code samples on this page are in Python. The same content is available with samples in:

- [Python](https://docs.starkbank.com/get-started/card-payment-python.md)
- [Node.js](https://docs.starkbank.com/get-started/card-payment-node.md)
- [PHP](https://docs.starkbank.com/get-started/card-payment-php.md)
- [Java](https://docs.starkbank.com/get-started/card-payment-java.md)
- [Ruby](https://docs.starkbank.com/get-started/card-payment-ruby.md)
- [Elixir](https://docs.starkbank.com/get-started/card-payment-elixir.md)
- [.NET](https://docs.starkbank.com/get-started/card-payment-dotnet.md)
- [Go](https://docs.starkbank.com/get-started/card-payment-go.md)
- [Clojure](https://docs.starkbank.com/get-started/card-payment-clojure.md)
- [cURL](https://docs.starkbank.com/get-started/card-payment-curl.md)

## Setup

For each environment (Sandbox or Production):

1. Create an account at Stark Bank.

2. Create a webhook with the following subscriptions to receive events at your desired URL:

`merchant-purchase`

`merchant-installment`

`merchant-card`

2.1. Via Internet Banking: 

Integrations > Webhook > New Webhook

2.2. Via API: 

Use the [POST /webhook](https://docs.starkbank.com/api.md#webhook) route to create the webhook

## Payment Flows

There are three main ways to accept a card payment with Stark Bank:

**Standard checkout** (most common): Create a Merchant Session on your server, then collect the card details on your website or app and submit the purchase directly to Stark Bank. This flow doesn't require PCI compliance. See [Merchant Session](#merchant-session-overview) and [Merchant Purchase](#merchant-purchase-overview) below.

**3DS checkout** (adds an extra security step): Works like the standard checkout, but the card issuer authenticates the cardholder during checkout, using the Stark 3DS SDK in your front-end. When the authentication succeeds, the liability for fraud chargebacks shifts from you to the issuer. To enable it, create the session with `challengeMode="enabled"`. See [3DS Authentication](#3ds-authentication) below.

**Repeat charges** (requires a prior approved purchase): After a customer's first payment, their card is saved as a Merchant Card. You can use it to charge them again without collecting card details — great for subscriptions or returning customers. Repeat charges are credit only and cannot use 3DS. See [Merchant Card](#merchant-card-overview) and [Creating a Merchant Purchase via API](#creating-a-merchant-purchase-via-api) below.

Any of these flows can also use **pre-authorization**: with `confirmationMode="manual"`, the amount is authorized and held on the card until you confirm the purchase, for the full amount or a lower one. Pre-authorization is available for credit purchases only. See [Pre-authorization](#pre-authorization) below.

## 3DS Authentication

With 3DS (3-D Secure), the card issuer authenticates the cardholder during checkout, which reduces fraud and undue declines. When the purchase is authenticated, the liability for fraud chargebacks shifts from you to the issuer.

3DS happens in four steps:

Your backend creates a Merchant Session with `challengeMode="enabled"` and hands the session UUID to your front-end.
Your front-end sends the card data directly to Stark Bank with that session and receives the purchase with status **pending** and an authentication token.
Your front-end calls the Stark 3DS SDK with that token and receives the authentication result.
Your backend sends that result to Stark Bank, which concludes the authorization.

The card data goes from the browser directly to Stark Bank and never passes through your backend. The SDK does not call the Stark Bank API nor conclude the purchase: it only runs the 3DS authentication in the browser and returns its result.

| Who | What |
| --- | --- |
| Your backend | Creates the session, receives the challenge from your front-end and completes the purchase on Stark Bank. |
| Your front-end | Collects the card data, creates the purchase on Stark Bank with the session and runs the SDK. |
| You, once per SDK version | Downloads the SDK, hosts it on your domain and includes the script tag on your checkout pages. |
| Stark Bank | Issues the authentication token, validates the challenge and authorizes the purchase. |

**3DS requires the session flow.** A purchase made with a saved card (`POST /merchant-purchase` with a `cardId`) cannot be authenticated: 3DS runs in the cardholder's browser and needs the full card number, which is never returned for a saved card. Sending a `challengeMode` other than `disabled` in that route returns the `invalidChallengeMode` error.

**One hour to complete.** A pending purchase must be completed within one hour of its creation. After that, it fails and must be created again. This deadline is independent from the session expiration and from the token expiration.

**Zero dollar purchases** are never authenticated, even in a 3DS session.

**Installing the SDK**

1. Download the file [https://starkbank.com/static/libs/stark3ds@1.0.2/stark3ds.min.js](https://starkbank.com/static/libs/stark3ds@1.0.2/stark3ds.min.js). The path is versioned: when a new version is released, the previous file remains available, so your integration does not break until you update it.

2. Host the file on your own domain, over HTTPS. Do not point your script tag to the Stark Bank URL: it is the download source, not a CDN for production use. Serving it from your domain keeps an outage on our side from affecting your checkout and keeps the script under your cache and CSP control.

3. Include the script tag before your checkout code: `<script src="/assets/js/stark3ds.min.js"></script>`. The script exposes the global object `Stark3DS`, with the methods `authenticate`, `isAuthenticated`, `toChallengeResult` and `isLiabilityShiftToIssuer`.

To confirm which file you are hosting: version 1.0.2 has 12,279 bytes and MD5 `f7eedb7805b4c2aec8162590ce418efb`.

**Stark3DS.authenticate(input)**

Runs the 3DS authentication and resolves with the result. The card issuer decides whether the cardholder is challenged: without a challenge, the authentication completes with no interaction; with a challenge, the issuer shows an extra step over your page, usually a code sent by SMS or an approval in the bank's app, and the promise only resolves when the cardholder finishes it.

Keep your page usable while the authentication runs: do not navigate away, reload or unmount the component after calling `authenticate()`. The call is limited to 120 seconds, after which it rejects with `Stark3DSAuthenticateTimeoutError` and the purchase remains pending.

| Field | Required | Description |
| --- | --- | --- |
| accessToken | Yes | The token.accessToken returned when the purchase was created. |
| environment | No | "sandbox" (default) or "production". |
| order.number | Yes | Use purchase.endToEndId. |
| order.amount | Yes | Amount in cents (1000 = R$ 10.00). |
| order.currency | Yes | ISO 4217 currency code ("BRL"). |
| order.installments | Yes | Number of installments. Debit is always 1. |
| order.paymentMethod | Yes | "credit" or "debit". |
| card.number | Yes | Card number, digits only. |
| card.expirationMonth | Yes | "01" to "12". |
| card.expirationYear | Yes | Four digits, e.g. "2030". |
| billing | Yes | Holder name, email, phone and address: the same data sent when the purchase was created. The issuer uses it to assess the risk. |
| billing.customerId | No | Your identifier for the customer. |
| device.ipAddress | Recommended | The buyer's real IP address. |
| device.fingerprint | No | Device fingerprint, if you already collect one. |
| device.provider | No | Fingerprint provider. |
| shipping | No | Shipping address. Use sameAsBilling: true to repeat the billing address. |
| cart | No | Cart items: name, description, sku, quantity, unitPrice. |
| merchantUrl | No | Your store URL. Default: the page origin. |

The promise resolves with `{authentication, challenge}`. The `challenge` object, with `cavv`, `eci`, `version`, `xid` and `referenceId`, only exists when `authentication.status` is `authenticated`. Send it to your backend exactly as returned: `xid` and `referenceId` may be null, and must never be removed or replaced, because that invalidates the authentication.

| Status | Meaning | What to do |
| --- | --- | --- |
| authenticated | Authenticated. The challenge is present. | Complete the purchase on your backend. |
| failed | The issuer evaluated and did not authenticate: the cardholder made a mistake or did not finish the challenge, or the issuer refused. | Retrying the same purchase tends to fail again. Guide the buyer, or continue without 3DS, keeping the chargeback liability. |
| unenrolled | The card or the issuer is not enrolled in 3DS at the moment. | Not a buyer or integration error, and retrying does not help. Continue without 3DS if you want to conclude the sale. |
| error | Technical failure during the authentication. Unlike failed, the issuer made no decision. | A new attempt may work. Check returnCode and returnMessage. |
| disabled | 3DS disabled in the authentication configuration. | Should not happen in this flow. If it does, contact Stark Bank. |
| unsupported_brand | Card network without 3DS support. | Continue without 3DS. |

For any status other than `authenticated`, the `authentication` object also carries `returnCode` and `returnMessage`, plus `eci`, `version` and `referenceId` when available. Keep them in your logs: they are what allows Stark Bank to diagnose the case.

| Helper | Description |
| --- | --- |
| Stark3DS.isAuthenticated(output) | true when the authentication succeeded and the challenge is present. |
| Stark3DS.toChallengeResult(output) | Extracts the challenge. Throws Stark3DSValidationError if the authentication failed. |
| Stark3DS.isLiabilityShiftToIssuer(eci, brand) | Tells, from the ECI and the card network, whether the chargeback liability shifted to the issuer. |

Always inform the card network to `isLiabilityShiftToIssuer` when you know it: `"mastercard"`, `"visa"`, `"elo"` or `"amex"`. An ECI only has meaning within a network: `05` is authenticated on Visa and does not exist on Mastercard, while `01` is authenticated on Mastercard and does not exist on Visa. Without the network, any authenticated ECI is accepted, which may indicate a protection that does not exist. An unknown network returns `false`.

**Environments**

Send `environment` to `authenticate()`: `"sandbox"` (default) or `"production"`. In Production, send `"production"` explicitly: a Production token used with the Sandbox environment is refused. Your backend, the token and the front-end environment must all be in the same environment. The SDK loads the authentication script it needs, so allow `script-src` in your Content-Security-Policy for `https://mpisandbox.braspag.com.br` (Sandbox) and `https://mpi.braspag.com.br` (Production).

**Error handling**

| Situation | Behavior |
| --- | --- |
| Authentication not completed (failed, unenrolled and others) | The promise resolves without a challenge. Check it with Stark3DS.isAuthenticated(). |
| Invalid input | Rejects with Stark3DSValidationError. |
| Authentication timeout (120 seconds) | Rejects with Stark3DSAuthenticateTimeoutError. |
| Authentication script fails to load | Rejects with Stark3DSError. |

## Pre-authorization

Pre-authorization lets you authorize a payment now and confirm (capture) it later. The authorized amount is held on the customer's card until you confirm it, and you can confirm the full amount or a lower one.

In the standard flow (`confirmationMode="automatic"`), the purchase is authorized and confirmed automatically. In the pre-authorization flow (`confirmationMode="manual"`), authorization and confirmation are separate steps:

Create the session or the purchase with `confirmationMode="manual"`. See [Creating a Pre-authorization Merchant Session](#creating-a-pre-authorization-merchant-session) and [Creating a Merchant Purchase via API](#creating-a-merchant-purchase-via-api) below.
Once authorized, the purchase status becomes **approved**.
Confirm the purchase. Its status becomes **confirmed**. See [Confirming a Merchant Purchase](#confirming-a-merchant-purchase) below.

**Confirmation deadline.** Confirm the purchase before the `confirmationDeadline` returned in the purchase. Confirmations are refused in the last 15 minutes before the deadline, and purchases not confirmed by then are automatically canceled. The deadline can be set with your account manager to between 1 and 28 days (default: 28 days).

**Restrictions.** The `confirmationMode` field is optional and defaults to `"automatic"`, so integrations that do not send it keep the current behavior. Only credit purchases support `"manual"`: debit purchases are not allowed. Manual confirmation is not allowed for zero dollar purchases either.

Before the confirmation, you can cancel the authorization. After it, you can reverse the purchase, fully or partially:

| Action | Request | Body |
| --- | --- | --- |
| Create a session with pre-authorization | POST /merchant-session | "confirmationMode": "manual" |
| Create a purchase with pre-authorization | POST /merchant-purchase | "confirmationMode": "manual" |
| Confirm | PATCH /merchant-purchase/:id | {"status": "confirmed", "amount": N} |
| Cancel (approved) | DELETE /merchant-purchase/:id | None |
| Full reversal (confirmed or paid) | DELETE /merchant-purchase/:id | None |
| Partial reversal (confirmed or paid) | PATCH /merchant-purchase/:id | {"status": "reversed", "amount": N} |

## Sandbox

The Sandbox environment simulates card payment behaviors — approvals, declines and errors — without real charges. Use it to test your full integration before going live. The 3DS authentication runs for real against the issuer's test environment, using the 3DS test cards below, while the authorization is simulated separately.

**Sandbox vs Production:** Stark Bank uses separate workspaces for each environment, each with its own URL and API keys. Changes in one environment don't affect the other.

If you don't have a Sandbox workspace yet, create one here:

[Create a Workspace in Sandbox](https://web.starkbank.com/sandbox/create)

## Test Cards

Use the card numbers below to simulate different payment scenarios in the Sandbox environment. All test cards accept any future expiration date and any 3-digit CVC.

| Scenario | Card Number | Expected Behavior |
| --- | --- | --- |
| Successful payment | 4242 4242 4242 4242 | Purchase is approved and confirmed. |
| Declined — insufficient funds | 4000 0000 0000 0002 | Purchase is denied with reason: insufficient funds. |
| Declined — generic | 5105 1051 0510 5100 | Purchase is denied by the issuer bank. |
| Expired card | 3782 822463 10005 | Purchase fails due to expired card. |
| Incorrect CVC | 3714 496353 98431 | Purchase fails due to incorrect security code. |

**3DS test cards**

Each card below forces a 3DS authentication result, so you can exercise every path of your checkout without depending on a real issuer's decision. The `authentication.status` column is exactly what the SDK returns. Use any holder name.

These cards determine the authentication result, not the purchase result. In Sandbox, the authorization is simulated separately, so a card that authenticates successfully may still end with the purchase **denied**. If `authentication.status` is `authenticated` and the challenge reached your backend, the 3DS step worked. To exercise the complete path up to **approved** with a challenge, prefer the Mastercard 5200 0000 0000 2151.

**With challenge**: the cardholder sees the issuer's screen before the result returns.

| Card Number | Network | authentication.status | Scenario |
| --- | --- | --- | --- |
| 4000 0000 0000 2503 | Visa | authenticated | Cardholder successfully authenticated |
| 5200 0000 0000 2151 | Mastercard | authenticated | Cardholder successfully authenticated |
| 6505 2900 0000 2190 | Elo | authenticated | Cardholder successfully authenticated |
| 4000 0000 0000 2370 | Visa | failed | Cardholder does not complete the authentication |
| 5200 0000 0000 2490 | Mastercard | failed | Cardholder does not complete the authentication |
| 6505 2900 0000 2208 | Elo | failed | Cardholder does not complete the authentication |
| 4000 0000 0000 2420 | Visa | unenrolled | Challenge unavailable at the moment |
| 5200 0000 0000 2664 | Mastercard | unenrolled | Challenge unavailable at the moment |
| 6505 2900 0000 2257 | Elo | unenrolled | Challenge unavailable at the moment |
| 4000 0000 0000 2644 | Visa | error | System error during the authentication |
| 5200 0000 0000 2656 | Mastercard | error | System error during the authentication |
| 6505 2900 0000 2265 | Elo | error | System error during the authentication |

**Without challenge**: the issuer decides alone, with no interaction from the cardholder.

| Card Number | Network | authentication.status | Scenario |
| --- | --- | --- | --- |
| 4000 0000 0000 2701 | Visa | authenticated | Cardholder successfully authenticated |
| 5200 0000 0000 2235 | Mastercard | authenticated | Cardholder successfully authenticated |
| 6505 2900 0000 2000 | Elo | authenticated | Cardholder successfully authenticated |
| 4000 0000 0000 2925 | Visa | failed | Cardholder does not complete the authentication |
| 5200 0000 0000 2276 | Mastercard | failed | Cardholder does not complete the authentication |
| 6505 2900 0000 2018 | Elo | failed | Cardholder does not complete the authentication |

Only the cards with `authenticated` produce a challenge to send to your backend. With the others, `Stark3DS.isAuthenticated()` returns `false` and `Stark3DS.toChallengeResult()` throws `Stark3DSValidationError`: test that your checkout handles the failure without breaking. Reserve a test for each row before going live.

## Merchant Session Overview

If your website or app needs to collect card details from customers — without those details ever touching your server — you should create a Merchant Session. This is the recommended approach for most integrations.

A Merchant Session works in two steps. First, your server creates a session via the Stark Bank API, defining the allowed funding types, installment options, expiration, and 3DS challenge mode. You'll receive a session object with a unique UUID.

Then, your client-side uses that UUID to submit the purchase along with the cardholder's sensitive data (card number, expiration, security code, holder info, billing address, and browser metadata) directly to Stark Bank — so card data never touches your backend.

Once a card is used successfully through a Merchant Session Purchase, it's stored as a Merchant Card and can be reused in future purchases without a new session.

### Creating a Merchant Session

To create a Merchant Purchase, you first need to create a Merchant Session on your server.

The session defines the purchase parameters such as the allowed funding types, installment options and expiration. You'll receive a UUID that your client-side will use to submit the purchase.

The expiration is mandatory and must be between 60 and 86400 seconds (24 hours). It is only checked when the purchase is created: a purchase created with an expired session is rejected with the merchantSessionExpired error.

When an installment option has more than one installment, each installment must be at least 500 (R$5.00): 'totalAmount' divided by 'count' cannot be lower than 500.

### Creating a 3DS Merchant Session

To create a Merchant Purchase with 3DS authentication, you need to create a Merchant Session with the field 'challengeMode' set to 'enabled'. The default is 'disabled'.

3DS (3-D Secure) lets the card issuer authenticate the cardholder during checkout — similar to a two-factor authentication for card payments. Apart from the 'challengeMode' field, the session creation is identical to a regular Merchant Session. See [3DS Authentication](#3ds-authentication) above for the complete flow.

### Creating a Pre-authorization Merchant Session

To authorize a purchase now and confirm it later, create the Merchant Session with the field 'confirmationMode' set to 'manual'. All purchases made through the session follow the pre-authorization flow: once authorized, they remain **approved** until you confirm them. See [Pre-authorization](#pre-authorization) above and [Confirming a Merchant Purchase](#confirming-a-merchant-purchase) below.

The default 'confirmationMode' is 'automatic', which confirms approved purchases automatically. Manual confirmation is only available for credit purchases, so 'allowedFundingTypes' cannot contain 'debit', and it is not allowed for zero dollar purchases.

### Creating a Zero Dollar Merchant Session

A zero dollar Merchant Session is used to validate a card without charging the cardholder.

To create one, add an option with 'totalAmount' equal to '0' and 'count' equal to '1' to 'allowedInstallments', as in the example below. Zero dollar purchases are not authenticated with 3DS.

## Merchant Card Overview

A Merchant Card stores card information for use in future recurring purchases.

### The Merchant Card object

**Parameters**

| Name | Type | Description |
| --- | --- | --- |
| `id` | STRING | Unique id for the merchant card. |
| `created` | STRING | Creation datetime. Example: "2020-04-23T23:00:00.000000+00:00". |
| `ending` | STRING | Last 4 digits of the card number. |
| `expiration` | STRING | Card expiration datetime. Example: "2035-02-01T02:59:59.999999+00:00". |
| `fundingType` | STRING | Funding type. Options: "credit", "debit". |
| `holderName` | STRING | Name of the card holder. |
| `network` | STRING | Card network. |
| `productId` | STRING | First digits (BIN) of the card. |
| `status` | STRING | Current card status. Options: "active", "expired", "canceled", "blocked". |
| `tags` | LIST OF STRINGS | Tags associated with the card. |
| `updated` | STRING | Last update datetime. Example: "2020-04-23T23:00:00.000000+00:00". |

### Getting Merchant Cards

You can query Merchant Cards using tags to find cards associated with a specific customer.

When creating a Merchant Card, assign a tag that identifies the customer. Later, use the tags parameter to retrieve all cards linked to that customer.

### Receiving Card Webhook

**Listen to Card Webhooks**

After creation, you can use webhooks to monitor status changes.

Every time a Merchant Card changes, we create a Log. Logs are useful for understanding the life cycle of each Merchant Card. Whenever a new Log is created, we'll send a webhook to your registered URL.

## Merchant Purchase Overview

A Merchant Purchase represents a card payment charged to your customer. It can be created in two ways: through a Merchant Session, where your client-side submits the purchase directly to Stark Bank using the session UUID; or via the API using a Merchant Card ID for recurring charges.

After creation, the purchase follows a life cycle: it starts as created, moves to approved once the card network authorizes it, and is then confirmed, automatically or by you when the purchase uses pre-authorization. You can also cancel an approved purchase or reverse a confirmed or paid one, either partially or fully.

Each Merchant Purchase generates one or more Merchant Installments, which represent the individual payments that will be credited to your account.

### The Merchant Purchase object

**Parameters**

| Name | Type | Description |
| --- | --- | --- |
| `id` | STRING | Unique id for the merchant purchase. |
| `amount` | INTEGER | Amount in cents to be received. Example: 100 (R$1.00). |
| `cardEnding` | STRING | Last 4 digits of the card. |
| `cardId` | STRING | ID of the Merchant Card used for the purchase. |
| `cardProductId` | STRING | First digits (BIN) of the card used for the purchase. |
| `challengeMode` | STRING | Holder verification mode. Options: "enabled", "disabled". |
| `challengeUrl` | STRING | URL where the cardholder completes a verification requested by the issuer, when there is one. Empty for 3DS purchases, which return a token for the Stark 3DS SDK instead. |
| `confirmationDeadline` | STRING | Datetime until which a purchase with confirmationMode "manual" can be confirmed. Confirmations are refused from 15 minutes before it. Example: "2020-05-21T23:00:00.000000+00:00". |
| `confirmationMode` | STRING | Purchase confirmation mode. Options: "automatic", "manual". |
| `created` | STRING | Creation datetime. Example: "2020-04-23T23:00:00.000000+00:00". |
| `currencyCode` | STRING | Currency code of the purchase. |
| `endToEndId` | STRING | End-to-end ID of the purchase. |
| `fee` | INTEGER | Fee charged in cents. |
| `fundingType` | STRING | Funding type. Options: "credit", "debit". |
| `holderId` | STRING | Your identifier for the cardholder. |
| `installmentCount` | INTEGER | Number of purchase installments. |
| `network` | STRING | Card network. |
| `softDescriptor` | STRING | Text shown on the cardholder's statement. |
| `source` | STRING | Source of the purchase. |
| `status` | STRING | Current purchase status. Options: "created", "pending", "processing", "approved", "denied", "confirmed", "paid", "canceled", "voided", "failed". |
| `tags` | LIST OF STRINGS | Tags associated with the purchase. |
| `transactionIds` | LIST OF STRINGS | Ledger transaction IDs linked to the purchase. |
| `updated` | STRING | Last update datetime. Example: "2020-04-23T23:00:00.000000+00:00". |

### The Merchant Purchase Status

A Merchant Purchase has the following life cycle:

![merchant-purchase-status](https://docs.starkbank.com/static/documentationApi/docs-merchant-purchase-status.svg)

| Status | Description |
| --- | --- |
| Created | The Merchant Purchase was created in Stark Bank. |
| Pending | Waiting for the cardholder to complete the 3DS authentication. This only applies if you enabled 3DS. |
| Processing | The authorization is being concluded. The final status is delivered by webhook. |
| Approved | The issuer bank accepted the purchase. |
| Denied | The issuer bank denied the purchase. |
| Failed | The purchase failed. |
| Confirmed | The payment was confirmed and will be credited to your account. |
| Paid | All installments were paid to your account. |
| Canceled | The purchase was canceled by you, or automatically when a pre-authorized purchase was not confirmed in time. |
| Voided | The purchase was fully reversed. |

### The Merchant Purchase Logs

Every time a Merchant Purchase changes, we create a Log. Logs are useful for understanding the life cycle of each purchase. Whenever a new Log is created, we'll send a webhook to your registered URL.

Check out this diagram to understand the possible Merchant Purchase Logs:

![merchant-purchase-log](https://docs.starkbank.com/static/documentationApi/docs-merchant-purchase-log.svg)

A confirmed or paid Merchant Purchase can be reversed, partially or fully, more than once. Each reversal follows this flow of logs:

![merchant-purchase-log-reversal](https://docs.starkbank.com/static/documentationApi/docs-merchant-purchase-log-reversal.svg)

| Log type | Status | Description |
| --- | --- | --- |
| Created | Created | The Merchant Purchase was successfully created in Stark Bank. |
| Pending | Pending | The Merchant Purchase is waiting for the cardholder to complete the 3DS authentication. |
| Processing | Processing | The Merchant Purchase authorization is being concluded. |
| Approved | Approved | The Merchant Purchase was authorized by the issuer bank. |
| Denied | Denied | The Merchant Purchase was denied by the issuer bank. |
| Failed | Failed or Approved | The Merchant Purchase processing failed. A failed confirmation keeps the purchase approved. |
| Confirming | Approved | The Merchant Purchase confirmation is being processed. |
| Confirmed | Confirmed | The Merchant Purchase payment was confirmed and will be credited to your account. |
| Canceling | Approved | The Merchant Purchase cancellation is being processed. |
| Canceled | Canceled | The Merchant Purchase was canceled. |
| Credited | Confirmed or Paid | An installment of the Merchant Purchase was credited to your account. The log carries the transaction ID. |
| Paid | Paid | All installments of the Merchant Purchase were paid to your account. |
| Reversing | Confirmed or Paid | The Merchant Purchase reversal is being processed. |
| Sending | Confirmed or Paid | The reversal amount was debited from your account. |
| Refunded | Confirmed or Paid | The reversal refund failed and its amount was credited back to your account. |
| Reversed | Confirmed or Paid | The Merchant Purchase was partially reversed. |
| Voided | Voided | The Merchant Purchase was fully reversed. |

**Note:** You only receive these webhooks if you have the **merchant-purchase** subscription set.

### Creating a Merchant Purchase via Session

After creating a Merchant Session, you can create a purchase using the UUID generated in the session through a public route. This means the transaction does not need to go through your backend.

Note: the UUID serves as a unique key that allows us to associate the purchase your client is creating directly with your merchant account.

A purchase declined by the issuer is returned with HTTP status 200 and status **denied**. The decline reason is in the purchase's denied log.

### Creating a 3DS Merchant Purchase via Session

After creating a 3DS Merchant Session, your front-end creates the purchase with the session UUID through a public route, sending the card data directly to Stark Bank. The route accepts calls from browsers of any origin; to restrict where the purchase can be created from, use 'allowedIps' when creating the session.

In a 3DS session, 'holderEmail' and 'holderPhone' (digits only, with area code) are mandatory, and the purchase is rejected with HTTP status 400 if either is missing.

The billing address ('billingStreetLine1', 'billingStreetLine2', 'billingCity', 'billingStateCode', 'billingZipCode' and 'billingCountryCode') and the 'metadata' object with the buyer's device data ('userAgent', 'userIp', 'language', 'timezoneOffset', 'screenHeight' and 'screenWidth') are optional, but we recommend sending them: the issuer uses them to assess the risk and decide whether to challenge the cardholder.

The purchase is returned with status **pending** and a 'token'. Keep 'purchase.id' and 'token.accessToken' for the next steps. The purchase must be completed within one hour, or it fails and must be created again.

### Authenticating a 3DS Merchant Purchase

With the token returned on the purchase creation, your front-end calls `Stark3DS.authenticate()` to run the 3DS authentication. See [3DS Authentication](#3ds-authentication) above for installing the SDK and for its full reference.

When the authentication succeeds, send the resulting challenge object to your backend, which completes the purchase. When it does not, the purchase remains pending: do not complete it. You can continue without 3DS by creating a new purchase in a session with 'challengeMode' set to 'disabled', keeping the chargeback liability.

The challenge object returned by the SDK:

### Completing a 3DS Merchant Purchase

Your backend sends the challenge object received from your front-end to Stark Bank, which concludes the authorization. The purchase must have status **pending**. Send the object exactly as the SDK returned it, including null values.

The purchase is returned as **approved** when the authorization succeeds or **denied** when it is declined. It may also be returned as **processing**, in which case the final status is delivered by the merchant-purchase webhook. Return the final result to your front-end.

This route is currently not available in the SDKs.

### Refreshing a 3DS Merchant Purchase token

If the token expired before the cardholder finished the authentication, your backend can issue a new one for a purchase that is still **pending**. No request body is required. The new token does not extend the one hour deadline of the purchase.

This route is currently not available in the SDKs.

### Creating a Zero Dollar Merchant Purchase via Session

After creating a zero dollar Merchant Session, you can create a purchase using the UUID generated in the session through a public route. This transaction does not need to go through your backend.

To create a zero dollar merchant purchase, you only need to set the field 'amount' to '0'.

### Creating a Merchant Purchase via API

To create a purchase directly from your server, use the POST /merchant-purchase endpoint with a Merchant Card ID for recurring charges.

For this integration, you must already have an approved purchase with this card. After the purchase is approved, an entity called Merchant Card is generated and you can use it for recurring purchases.

The only field you need from the Merchant Card is its ID. You can check it by consulting an approved Merchant Purchase or using the endpoint to list the Merchant Cards.

Purchases with a saved card are credit only, must have an amount of at least 100 (R$1.00), with each installment of at least 500 (R$5.00) when there is more than one, and cannot use 3DS: 'challengeMode' only accepts 'disabled'. To use pre-authorization, send 'confirmationMode' as 'manual'.

### Querying Merchant Purchases

You can retrieve a Merchant Purchase by its ID or list them using parameters such as **limit, after, before** to filter the results, as shown in the example below:

You can also query Merchant Purchases using tags to find purchases associated with a specific order. When creating a Merchant Purchase, assign a tag with the order ID. Later, use the tags parameter to retrieve all purchases linked to that order.

### Confirming a Merchant Purchase

Purchases created with 'confirmationMode' set to 'manual' (pre-authorization) are authorized and remain **approved**, with the amount held on the customer's card, until you confirm them. You can confirm the full authorized amount or a lower one, with a minimum of 100 (R$1.00).

Only purchases with manual confirmation mode and status **approved** can be confirmed, and only one confirmation can be in progress at a time. After the confirmation, the purchase status changes to **confirmed**.

Each pre-authorized purchase has a 'confirmationDeadline'. Confirm it before then: from 15 minutes before the deadline, the confirmation is refused with the invalidOperation error, and purchases not confirmed by the deadline are automatically canceled. The deadline can be set with your account manager to between 1 and 28 days (default: 28 days).

If the confirmation cannot be concluded right away, the response message is 'Merchant Purchase confirmation in progress' and the purchase stays **approved** with a **confirming** log. The result arrives by webhook: a **confirmed** log when it succeeds, or a **failed** log when it fails, in which case the purchase stays **approved** with its previous amount. After multiple failed confirmation attempts, the purchase is automatically canceled and can no longer be confirmed.

To give up a pre-authorized purchase, cancel it as described in [Canceling a Merchant Purchase](#canceling-a-merchant-purchase).

### Canceling a Merchant Purchase

To cancel a Merchant Purchase, its status must be **approved**. The amount is set to 0, which cancels the authorization.

While the cancellation is being processed, the purchase status remains **approved**. After it is completed, the status changes to **canceled**.

You can also cancel an approved purchase with `DELETE /merchant-purchase/:id`, with no request body.

### Partially Reversing a Merchant Purchase

To partially reverse a Merchant Purchase, its status must be **confirmed** or **paid**. Send the new amount of the purchase after the reversal: for example, to reverse 2000 of a purchase of 5000, send 3000. The amount must be between 100 and the current amount minus 1. This action debits the difference and reverses part of the purchase.

Partial reversals are not allowed on the same day (GMT-3) as the purchase confirmation. They are allowed from the following day on.

While the reversal is being processed, the purchase status remains the same, and it also remains the same after the partial reversal is completed.

### Fully Reversing a Merchant Purchase

To fully reverse a Merchant Purchase, its status must be **confirmed** or **paid**. Send the amount 0: this action reverses the entire purchase amount.

While the reversal is being processed, the purchase status remains the same. After the full reversal is completed, the status changes to **voided**.

You can also fully reverse a confirmed or paid purchase with `DELETE /merchant-purchase/:id`, with no request body.

### Receiving Purchase Webhook

**Approved Webhook Example**

## Merchant Installment Overview

When you create a Merchant Purchase, you can choose to receive it in one installment or split it into multiple installments.

Each installment is tracked as a Merchant Installment, which helps you monitor when each payment is due and which ones have already been credited.

Once an installment is credited to your account, you'll receive a credited log with the transaction ID that appears on your statement.

### The Merchant Installment object

**Parameters**

| Name | Type | Description |
| --- | --- | --- |
| `id` | STRING | Unique id for the merchant installment. |
| `amount` | INTEGER | Installment amount in cents. |
| `created` | STRING | Creation datetime. Example: "2020-04-23T23:00:00.000000+00:00". |
| `due` | STRING | Expected settlement date. Example: "2020-04-23T23:00:00.000000+00:00". |
| `fee` | INTEGER | Total fee charged in cents, including the anticipation fee when there is one. |
| `fundingType` | STRING | Funding type. Options: "credit", "debit". |
| `isProtected` | BOOLEAN | Whether the installment is reserved to cover a reversal of its purchase. |
| `network` | STRING | Card network. |
| `nominalDue` | STRING | Originally scheduled settlement date. Example: "2020-04-23T23:00:00.000000+00:00". |
| `purchaseId` | STRING | ID of the Merchant Purchase linked to the installment. |
| `status` | STRING | Current installment status. Options: "created", "paid", "voided". |
| `tags` | LIST OF STRINGS | Tags associated with the installment. |
| `transactionIds` | LIST OF STRINGS | Ledger transaction IDs linked to the installment. |
| `updated` | STRING | Last update datetime. Example: "2020-04-23T23:00:00.000000+00:00". |

### The Merchant Installment Status

A Merchant Installment has the following life cycle:

![merchant-installment-status](https://docs.starkbank.com/static/documentationApi/docs-merchant-installment-status.svg)

| Status | Description |
| --- | --- |
| Created | The Merchant Installment was created. |
| Paid | The Merchant Installment was paid to your account. |
| Voided | The Merchant Installment was voided. |

### The Merchant Installment Logs

Every time a Merchant Installment changes, we create a Log. Logs are useful for understanding the life cycle of each installment. Whenever a new Log is created, we'll send a webhook to your registered URL.

Check out this diagram to understand the possible Merchant Installment Logs:

![merchant-installment-log](https://docs.starkbank.com/static/documentationApi/docs-merchant-installment-log.svg)

When its purchase is reversed, partially or fully, each affected Merchant Installment follows this flow of logs:

![merchant-installment-log-reversal](https://docs.starkbank.com/static/documentationApi/docs-merchant-installment-log-reversal.svg)

| Log type | Status | Description |
| --- | --- | --- |
| Created | Created | The Merchant Installment was created in Stark Bank. |
| Updated | Created | The Merchant Installment due date was updated. |
| Paid | Paid | The Merchant Installment was paid to your account. |
| Credited | Paid | The Merchant Installment amount was credited to your account. The log carries the transaction ID. |
| Reversing | Unchanged | A reversal of the purchase is being applied to the Merchant Installment. |
| Sending | Unchanged | The reversal amount was debited from your account. |
| Refunded | Unchanged | The reversal refund failed and its amount was credited back to your account. |
| Failed | Unchanged | The reversal of the Merchant Installment failed and its previous amount was restored. |
| Reversed | Unchanged | The Merchant Installment was partially reversed. |
| Voided | Voided | The Merchant Installment was fully reversed. |

**Note:** You only receive these webhooks if you have the **merchant-installment** subscription set.

### Querying Merchant Installments

You can retrieve a Merchant Installment by its ID or even list them using parameters such as **limit, after, before** to filter the results, as shown in the example below:

### Querying Merchant Installment Logs

You can retrieve Merchant Installment Logs by using parameters such as **limit, after, before** to filter the results, as shown in the example below:

Each log tracks a status change in the installment's life cycle.

### Receiving Installment Webhook

**Listen to Merchant Installment Webhooks**

After creation, you can use asynchronous Webhooks to monitor status changes of the entity. The Merchant Installment follows this life cycle:

Every time a Merchant Installment changes, we create a Log. Logs are useful for understanding the life cycle of each Merchant Installment. Whenever a new Log is created, we'll send a webhook to your registered URL.
