# Crear un Pago Autenticado con 3DS

Añada una capa adicional de seguridad a sus transacciones y reduzca el riesgo de fraude implementando la autenticación 3D Secure (3DS). Esta guía demuestra cómo utilizar la GetNet Global API para verificar la identidad del titular de la tarjeta antes de procesar su pago.

## Requisitos

Antes de iniciar la integración, complete lo siguiente:

  * **Credenciales de la API**: Póngase en contacto con el Equipo de Soporte de Integración para obtener su `client_id` y `client_secret`.
  * **Access Token**: Genere un token Bearer utilizando sus credenciales a través del endpoint de Access Token.
  * **Soporte de la Marca de la Tarjeta**: Verifique que la marca de la tarjeta sea Mastercard o Visa. Actualmente, estas están soportadas para 3DS en Argentina, Chile, México, España, Brasil y Uruguay.

> **Obligatorio para Europa**: Las transacciones dentro del Espacio Económico Europeo (EEE) requieren autenticación 3DS para cumplir con la PSD2 y la Autenticación Reforzada de Clientes (SCA). Consulte la documentación de [Taxes and Regulations](https://www.google.com/search?q=/developer-resources/taxes-regulations%23spain) para obtener detalles sobre las exenciones.

## Entendiendo el Proceso de Autenticación 3DS

El emisor de la tarjeta determina dinámicamente el flujo de 3DS en función de la evaluación de riesgos, la marca de la tarjeta y las capacidades del emisor. Después de iniciar el Enrollment, la API devuelve un campo `status` que dicta su siguiente paso.

Gestione los tres escenarios posibles:

1.  **Autenticación Directa**: La autenticación se completa inmediatamente (estado: `Authenticated` o `Attempt`).
2.  **Challenge Requerido**: Se requiere la verificación del cliente (estado: `Pending Challenge`). Elija entre renderizar una plantilla HTML o realizar un POST manual utilizando los datos del **ACS Direct Form**.
3.  **Pending Enrollment Continue**: Se requiere un procesamiento adicional (estado: `Pending Enrollment Continue`), lo que puede resultar finalmente en autenticación o en un Challenge.

## Referencia Rápida: Flujo de Decisión

Siga esta lógica de decisión basándose en el `status` devuelto por la API:

**Después del Paso 2 (Iniciar Enrollment):**

  * **"Authenticated" o "Attempt"**: Proceda al [Paso 4: Crear el Pago](https://www.google.com/search?q=%23step-4-create-the-payment).
  * **"Pending Challenge"**: Elija `redirect_html_template` o `acs_redirect_form`. Proceda al [Paso 3B: Validar la Autenticación](https://www.google.com/search?q=%23step-3b-validate-authentication) y luego al [Paso 4: Crear el Pago](https://www.google.com/search?q=%23step-4-create-the-payment).
  * **"Pending Enrollment Continue"**: Proceda al [Paso 3C: Continuar Enrollment](https://www.google.com/search?q=%23step-3c-continue-enrollment).

## Pasos de Implementación

### Paso 1: Obtener el Access Token y Tokenizar la Tarjeta

1.  Solicite un access token utilizando sus credenciales de la API.
2.  Tokenice la información de la tarjeta utilizando el [endpoint de token](https://www.google.com/search?q=/en/products/online-payments/regional-api/swagger%23tag/cards/POST/dpm/cofre-gw-proxy/v1/tokens/card).

### Paso 2: Iniciar Enrollment

Llame al endpoint [3DS - Init Authentication](https://www.google.com/search?q=/en/products/online-payments/regional-api/swagger%23tag/payments/post/dpm/security-gwproxy/v2/enrolments-initial).

```json
curl --request POST \
  --url https://api-sbx.globalgetnet.com/dpm/security-gwproxy/v2/enrolments-initial \
  --header 'authorization: Bearer ' \
  --header 'content-type: application/json' \
  --data '{
  "currency": "CLP",
  "md": "NmQyZTQzODAtZDhhMy00Y2NiLTkxMzgtYzI4OTE4MjgxOGE0",
  "term_url": "123",
  "amount": 1,
  "payment_method": {
    "expiration_month": "05",
    "expiration_year": "25",
    "security_code": "282",
    "number_token": "4292b573ea94b257dcb132afe242b4a15c9866d16e2d4d64d8e571c877af0540c3946b8bddaf37c2c75a1810863fc6b0fe0e841ebbc752c1d23ccfb5fdaac3d1"
  },
  "description": "TEST",
  "operation": "CREDIT",
  "extra_fields": {
    "billing_address": {
      "street": "Av. Brasil",
      "number": "1000",
      "complement": "Sala 1",
      "district": "São Geraldo",
      "city": "Porto Alegre",
      "state": "RS",
      "country": "BR",
      "postal_code": "90230060",
      "reference": "Near the hospital"
    },
    "shipping_address": {
      "street": "Av. Brasil",
      "number": "1000",
      "complement": "Sala 1",
      "district": "São Geraldo",
      "city": "Porto Alegre",
      "state": "RS",
      "country": "BR",
      "postal_code": "90230060",
      "reference": "Near the hospital"
    }
  }
}'
```

**Ejemplo de respuesta (Pending Challenge):**

```json
{
  "transaction_id": "84c05897-fbf1-4a91-90e8-d292a0fda1c8",
  "status": "Pending Challenge",
  "protocol": "3DS2.3.1",
  "redirect_html_template": "<html>...</html>",
  "acs_redirect_form": {
    "action_url": "https://3ds-acs.test.modirum.com/mdpayacs/creq;token=368800071.1773147207.lksz3Q5MLGPuP5RsNmoU_8831PDCBLY_ABFB5xq0wtc",
    "method": "POST",
    "creq": "ewogICAgImFjc1RyYW5zSUQiOiAiNjVhMWUxN2MtZWVmYS00NGU1LTgyMDEtMDI4MjM5ZTVmOTA3IiwKICAgICJjaGFsbGVuZ2VXaW5kb3dTaXplIjogIjAzIiwKICAgICJtZXNzYWdlVHlwZSI6ICJDUmVxIiwKICAgICJtZXNzYWdlVmVyc2lvbiI6ICIyLjMuMSIsCiAgICAidGhyZWVEU1NlcnZlclRyYW5zSUQiOiAiZjI0ZmZhMWItMWY5MC01ZjMxLTgwMDAtMDAwMDAyYmY4Yjc3Igp9",
    "threeDSSessionData": "NmQyZTQzODAtZDhhMy00Y2NiLTkxMzgtYzI4OTE4MjgxOGE0"
  }
}

```

### Paso 3: Verificar el Estado y Seguir el Escenario Adecuado

#### Estado: `Authenticated` o `Attempt`

Extraiga los datos de autenticación (`xid`, `eci`, `cavv`, `ds_trans_id`) y proceda al [Paso 4: Crear el Pago](https://www.google.com/search?q=%23step-4-create-the-payment).

#### Estado: `Pending Challenge`

Redirija al cliente a su banco para la autenticación. Seleccione uno de los siguientes métodos de redirección:

**Opción A: Plantilla HTML**
Extraiga y renderice el `redirect_html_template` directamente en su aplicación.

**Ejemplo de renderización de la plantilla HTML:**

```html
<div id="challenge-container"></div>
<script>
// Receive the redirect_html_template from your backend
const redirectHtmlTemplate = response.redirect_html_template;
// Inject the HTML into your page
document.getElementById('challenge-container').innerHTML = redirectHtmlTemplate;
// The template contains a form that will automatically submit and redirect
// the customer to their bank's authentication page
</script>
```

Alternativamente, puede renderizarlo en el lado del servidor (server-side):

```javascript
// Node.js/Express example
app.post('/initiate-3ds', async (req, res) => {
  const enrollmentResponse = await fetch('https://api-sbx.globalgetnet.com/dpm/security-gwproxy/v2/enrolments-initial', {
    // ... request configuration
  });
  const data = await enrollmentResponse.json();
  if (data.status === 'Pending Challenge') {
    // Send the HTML template directly to the browser
    res.send(data.redirect_html_template);
  }
});
```

**Opción B: ACS Direct Form**
Utilice el objeto `acs_redirect_form` para realizar una petición POST manual desde el navegador del cliente. Este método es preferible, ya que evita los scripts de terceros y permite una interfaz de usuario de "Carga" personalizada.

**Detalles del POST Obligatorios:**

  * **URL**: Utilice la `action_url` proporcionada en la respuesta.
  * **Método**: `POST`
  * **Content-Type**: `application/x-www-form-urlencoded`
  * **Cuerpo (Body)**: Incluya `creq` y `threeDSSessionData`.

**Ejemplo de redirección POST manual:**

```html
<div id="loader">Redirecting to secure bank authentication...</div>

<form id="acs-direct-form" method="POST" action="https://3ds-acs.test.modirum.com/mdpayacs/creq;token=368800071.1773147207.lksz3Q5MLGPuP5RsNmoU_8831PDCBLY_ABFB5xq0wtc">
  <input type="hidden" name="creq" value="ewogICAgImFjc1RyYW5zSUQiOiAiNjVhMWUxN2MtZWVmYS00NGU1LTgyMDEtMDI4MjM5ZTVmOTA3IiwKICAgICJjaGFsbGVuZ2VXaW5kb3dTaXplIjogIjAzIiwKICAgICJtZXNzYWdlVHlwZSI6ICJDUmVxIiwKICAgICJtZXNzYWdlVmVyc2lvbiI6ICIyLjMuMSIsCiAgICAidGhyZWVEU1NlcnZlclRyYW5zSUQiOiAiZjI0ZmZhMWItMWY5MC01ZjMxLTgwMDAtMDAwMDAyYmY4Yjc3Igp9" />
  <input type="hidden" name="threeDSSessionData" value="NmQyZTQzODAtZDhhMy00Y2NiLTkxMzgtYzI4OTE4MjgxOGE0" />
</form>

<script>
  // Programmatically submit the form
  document.getElementById('acs-direct-form').submit();
</script>

```

#### Estado: `Pending Enrollment Continue`

Debe llamar al endpoint del [Paso 3C: Continuar Enrollment](https://www.google.com/search?q=%23step-3c-continue-enrollment).

### Paso 3B: Validar la Autenticación

Después de que el cliente complete el Challenge y regrese a su sitio, capture el token de respuesta y llame al endpoint [3DS - Validate authentication](https://www.google.com/search?q=/en/products/online-payments/regional-api/swagger%23tag/payments/post/dpm/security-gwproxy/v2/validations).

**Ejemplo de petición:**

```bash
curl --request POST \
  --url https://api-sbx.globalgetnet.com/dpm/security-gwproxy/v2/validations \
  --header 'authorization: Bearer <your-token>' \
  --header 'content-type: application/json' \
  --data '{
  "transaction_id": "502040201060404060506040",
  "xid": "VDdnR0kyU1g4ZXlxMkhWTlp0VnA=",
  "token": "<cres-token-from-challenge-callback>"
}'
```

### Paso 3C: Continuar Enrollment

Si el estado inicial es `Pending Enrollment Continue`, llame al endpoint [3DS - Banking Login Authentication Payload](https://www.google.com/search?q=/en/products/online-payments/regional-api/swagger%23tag/payments/post/dpm/security-gwproxy/v2/enrolments-continue).

**Ejemplo de respuesta (estado Pending Challenge):**

```json
{
  "transaction_id": "84c05897-fbf1-4a91-90e8-d292a0fda1c8",
  "status": "Pending Challenge",
  "protocol": "3DS2.3.1",
  "acs_redirect_form": {
    "action_url": "https://3ds-acs.test.modirum.com/mdpayacs/creq;token=368800071.1773147207.lksz3Q5MLGPuP5RsNmoU_8831PDCBLY_ABFB5xq0wtc",
    "method": "POST",
    "creq": "ewogICAgImFjc1RyYW5zSUQiOiAiNjVhMWUxN2MtZWVmYS00NGU1LTgyMDEtMDI4MjM5ZTVmOTA3IiwKICAgICJjaGFsbGVuZ2VXaW5kb3dTaXplIjogIjAzIiwKICAgICJtZXNzYWdlVHlwZSI6ICJDUmVxIiwKICAgICJtZXNzYWdlVmVyc2lvbiI6ICIyLjMuMSIsCiAgICAidGhyZWVEU1NlcnZlclRyYW5zSUQiOiAiZjI0ZmZhMWItMWY5MC01ZjMxLTgwMDAtMDAwMDAyYmY4Yjc3Igp9",
    "threeDSSessionData": "NmQyZTQzODAtZDhhMy00Y2NiLTkxMzgtYzI4OTE4MjgxOGE0"
  }
}

```

### Paso 4: Crear el Pago

Una vez que se complete la autenticación (`Authenticated` o `Attempt`), llame al endpoint [Create - Authorize](https://www.google.com/search?q=/en/products/online-payments/regional-api/swagger%23tag/payments/post/dpm/payments-gwproxy/v2/payments). Incluya los datos de autenticación (`xid`, `eci`, `cavv`, `ds_trans_id`) en el objeto `payment`.

> **Requisitos específicos del país**: Algunos mercados pueden requerir campos obligatorios adicionales. En Uruguay debe incluir un array `rates` y proporcionar un `regional_regulation_code`. El `regional_regulation_code` es un array donde cada entrada tiene un `code` y un `invoice`. El `invoice` acepta hasta 9 caracteres alfanuméricos. Recomendamos usar solo números. Revise la referencia de [Taxes and Regulations](https://predocs.globalgetnet.com/en/articles?article=taxes-and-regulations) para obtener más información.

**Ejemplo de petición:**

```json
curl --request POST \
  --url https://api-sbx.globalgetnet.com/dpm/payments-gwproxy/v2/payments \
  --header 'authorization: Bearer '\
  --header 'content-type: application/json' \
  --header 'x-seller-id: 54f88e68-7764-4e87-8830-756b1e2c02f8' \
  --data '{
    "order_id": "123order",
    "data": {
      "amount": 118708,
      "currency": "CLP",
      "payment": {
        "payment_method": "CREDIT_AUTHORIZATION",
        "xid": "VDdnR0kyU1g4ZXlxMkhWTlp0VnA=",
        "eci": "24",
        "ds_trans_id": "f7e5f76e-6388-43e6-b8cd-49b251a1f89c",
        "card": { ... }
      }
    }
  }'
```

## Próximos Pasos

  * [Cancelaciones y Reembolsos](https://www.google.com/search?q=/en/products/online-payments/regional-api/swagger%23tag/payments/post/dpm/payments-gwproxy/v2/payments)
  * [Capturar una Transacción Preautorizada](https://www.google.com/search?q=/en/products/online-payments/regional-api/swagger%23tag/payments/post/dpm/payments-gwproxy/v2/payments)