> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.6mm.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.6mm.com/_mcp/server.

# Trading Widget Autenticación

<h2 id="recommended-mode-partner-token">
  Modo recomendado: token-partner
</h2>

partner-token evita poner tokens cortos en URLs y mantiene apiSecret en el backend del partner.

```js
const widget = TradingWidget.create('#trading-widget', {
  baseUrl: 'https://app.6mm.com',
  auth: {
    mode: 'partner-token',
    tokenProvider: async ({ channelId, symbol, reason }) => {
      const resp = await fetch('/api/trading/embed-token', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ channelId, symbol, reason }),
      })

      if (!resp.ok) {
        throw new Error('Failed to request embed token')
      }

      return resp.json()
    },
  },
})
```

<h2 id="related-documentation">
  Documentación relacionada
</h2>

* [Create Embed Token](/es-ES/sdk/agent-sdk/java/embed-token): ejemplo de emisión de token backend.
* [Trading Widget Inicio rápido](/es-ES/sdk/trading-widget/quick-start): flujo de inicialización completo.
* [Secretos y Firmas](/es-ES/sdk/security/secrets-signing): mantén las credenciales privilegiadas de Agente en el backend.
* [Solución de problemas](/es-ES/sdk/security/troubleshooting): diagnosticar fallos de sesión, token, origen e inicialización.

<h2 id="backend-flow">
  Flujo de backend
</h2>

```text
1. Partner frontend receives auth_request from the iframe.
2. SDK calls tokenProvider.
3. Partner frontend calls its own backend.
4. Partner backend validates the partner session.
5. Partner backend calls 6MM Agent API or Java SDK createEmbedToken.
6. SDK sends embedToken to the iframe through postMessage.
7. iframe exchanges embedToken for a 6MM access token.
8. iframe continues initialization and emits ready.
```

<h2 id="tokenprovider-contract">
  tokenProvider contrato
</h2>

| Campo      | Dirección                | Descripción                                                                                      |
| ---------- | ------------------------ | ------------------------------------------------------------------------------------------------ |
| channelId  | SDK -> Backend de socios | Identificador único de sesión de widget. El backend debería pasarlo a createEmbedToken.          |
| Símbolo    | SDK -> Backend de socios | Símbolo de trading solicitado actualmente. Úsalo para el alcance del token cuando sea necesario. |
| Razón      | SDK -> Backend de socios | Por qué el SDK solicita un token, como la carga inicial o la actualización.                      |
| embedToken | Backend de socios -> SDK | Token de corta duración creado por el Agent SDK o Agente API.                                    |
| expireAt   | Backend de socios -> SDK | La marca de tiempo de caducidad del token devuelve por 6MM.                                      |

<h2 id="failure-handling">
  Manejo de fallos
</h2>

| Estado                                    | Manipulación recomendada                                                                   |
| ----------------------------------------- | ------------------------------------------------------------------------------------------ |
| Sesión de socios expirada                 | Devuelve el 401 desde el endpoint del socio y pide al usuario que inicie sesión de nuevo.  |
| La creación de tokens falló temporalmente | Lanza un error en tokenProvider y permite que el widget muestre un error de autenticación. |
| channelId desajuste                       | Rechaza la petición y recrea la instancia del widget.                                      |
| El usuario no puede operar                | Devuelve un error controlado por el socio y no crees un token embed.                       |

<h2 id="compatibility-mode-agent-sso">
  Modo de compatibilidad: agent-sso
</h2>

agent-sso mantiene el flujo antiguo de tickets /agent-entry. Prefiero partner-token para nuevas integraciones.

```js
const widget = TradingWidget.create('#trading-widget', {
  baseUrl: 'https://app.6mm.com',
  auth: {
    mode: 'agent-sso',
    entryUrlProvider: async ({ redirectPath }) => {
      const resp = await fetch('/api/trading-entry', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ redirectPath }),
      })
      const data = await resp.json()
      return data.webUrl
    },
  },
})
```