---
updatedAt: 2026-03-03T17:17:23.000Z
agentTools:
  projectIndex: https://docs.dlocal.com/llms.txt
---

# dLocal Direct

Tokenize cards securely using dLocal Direct.

# Using dLocal Direct

## Step 1: Set up dLocal Direct

dLocal Direct is available as part of dLocal.js. To get started, include this script on your pages —it should always be loaded directly from <https://js.dlocal.com/direct>. For testing purposes, you can use <https://js-sandbox.dlocal.com/direct>

```html
<script src="https://js.dlocal.com/direct/"></script>
```

Next, create an instance of dLocal Direct:

```javascript
var dlocal = dlocal('your_API_key');
```

<br />

> **To initialize the dLocal helper you will need an API Key**. Please contact your Technical Account Manager to obtain one.

<br />

***

## Step 2: Create a token to securely transmit card information

The payment details collected using dLocal Direct can then be converted into a token. Create an event handler that handles the submit event on the form. The handler sends the sensitive information to dLocal for tokenization and prevents the form’s submission (the form is submitted by JavaScript in the next step).

```javascript
// Create a token or display an error when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();
var name = document.getElementById('card-holder').value;
var pan = document.getElementById('pan').value;
var expirationYear = document.getElementById('expiration-year').value;
var expirationMonth = document.getElementById('expiration-month').value;
var cvv = document.getElementById('cvv').value;
var country = 'BR';
  dlocal.createToken( {
    name, pan, expirationYear, expirationMonth, cvv, country
  }).then(function(result) {
      // Send the token to your server.
      dlocalTokenHandler(result.token);
  }).catch((result) => {
    if (result.error) {
      // Inform the customer that there was an error.
      var errorField = document.getElementById('card-errors');
      errorField.textContent = result.error.message;
    }
  });
});
```

`dlocal.createToken` returns a `Promise` which resolves with a `result` object. This object has `result.token` the token that was successfully created.

### `createToken` function parameters

In order to use the `createToken` function you should send the following parameters

| Parameter Name    | Type   | Description                                                            | Mandatory |
| :---------------- | :----- | :--------------------------------------------------------------------- | :-------- |
| `name`            | String | Cardholder's name                                                      | Yes       |
| `pan`             | String | The card number, as a string                                           | Yes       |
| `country`         | String | Two letters representing the Country of the transaction (BR, MX, etc). | Yes       |
| `expirationMonth` | String | Two digit number representing the card's expiration month.             | Yes       |
| `expirationYear`  | String | Two or four digit number representing the card's expiration year.      | Yes       |
| `cvv`             | String | Credit card verification value.                                        | Yes       |

<br />

***

## Step 3: Submit the token and the rest of your form to your server

The last step is to submit the token, along with any additional information that has been collected, to your server.

```javascript
function dlocalTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var tokenInput = document.createElement('input');
tokenInput.setAttribute('type', 'hidden');
tokenInput.setAttribute('name', 'dlocalToken');
tokenInput.setAttribute('value', token);
form.appendChild(tokenInput);

// Submit the form
form.submit();
}
```

<br />

> ℹ️ Note
>
> **Tokens created with this method expire after 10 minutes, or after one operation with that token is made (eg: Payment or Save Card)**. If you want to save the card to make other payments later, you need to **save the card**. [Learn more about saving cards](https://docs.dlocal.com/docs/saving-cards).

# Handling errors

## Expected errors

[block:parameters]
{
  "data": {
    "h-0": "Status",
    "h-1": "Parameter",
    "h-2": "Message",
    "h-3": "Description",
    "0-0": "`REJECTED`",
    "0-1": "`cvv`",
    "0-2": "The card’s security code is incorrect.",
    "0-3": "Invalid security code format",
    "1-0": "`REJECTED`",
    "1-1": "`card_number`",
    "1-2": "The card number is incorrect.",
    "1-3": "Card number is not valid.",
    "2-0": "`REJECTED`",
    "2-1": "`expiration_month`<br>`expiration_year`",
    "2-2": "The card expiration date is incorrect.",
    "2-3": "Incorrect expiration date.<br><br> E.g. MM-YY or MM-YYYY",
    "3-0": "`REJECTED`",
    "3-1": "`holder_name`",
    "3-2": "The card owner’s name is incorrect.",
    "3-3": "Name is empty."
  },
  "cols": 4,
  "rows": 4,
  "align": [
    "left",
    "left",
    "left",
    "left"
  ]
}
[/block]

## Unexpected errors

Unexpected errors may occur during the card tokenization process in Dlocal Direct. These issues are not caused by incorrect usage or invalid input but result from internal problems, downstream service dependencies, or temporary disruptions.

While Dlocal Direct is designed for high availability and reliability, these scenarios, typically reflected in HTTP 5xx and 4xx status codes, require robust handling to ensure resilient integrations.

### Common 5xx and 4xx status codes

| Status Code | Description           | Typical Cause                                      |
| ----------- | --------------------- | -------------------------------------------------- |
| 500         | Internal Server Error | An unhandled exception occurred.                   |
| 502         | Bad Gateway           | Failure in communication with an upstream service. |
| 503         | Service Unavailable   | Temporary overload or maintenance.                 |
| 504         | Gateway Timeout       | Request timed out before completion.               |
| 404         | Not Found             | The service is temporarily unavailable.            |

### Recommended handling methods

To ensure stability and fault tolerance, implement the following recommendations:

<br />

<details open>
<summary class="summary_head">

#### Implement retry Logic

</summary>

<br />

Use exponential backoff when retrying requests that return 5xx responses. Avoid tight retry loops that could increase load.

```Text Retry Logic
Initial delay: 1 second
Backoff factor: x2
Maximum attempts: 5
```

<br />

</details>

***

<details>
<summary class="summary_head">

#### Use idempotency keys

</summary>

<br />

Include idempotency keys in POST requests to prevent duplicate operations when retrying.

<br />

</details>

***

<details>
<summary class="summary_head">

#### Apply a circuit breaker pattern

</summary>

<br />

Implement a circuit breaker pattern to halt requests after a threshold of failures temporarily. Resume requests only after a defined cooldown period.

<br />

</details>

***

<br />

#### Contacting support

If persistent 5xx or 4xx errors occur, or a specific request consistently fails, contact your designated Technical Account Manager or email us at <integrations@dlocal.com> with the following information:

* Transaction ID from the error response
* API endpoint and request parameters
* Timestamp and timezone
* Relevant logs or screenshots

Unexpected errors are rare, but possible in distributed systems. Dlocal Direct actively monitors and responds to these issues to maintain reliable service.