> 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 de socio
</h2>

partner-token evita poner tokens cortos en las 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-419/sdk/agent-sdk/java/embed-token): ejemplo de emisión de token backend.
* [Trading Widget Inicio Rápido](/es-419/sdk/trading-widget/quick-start): flujo de inicialización completo.
* [Secretos y Firmas](/es-419/sdk/security/secrets-signing): mantén credenciales privilegiadas de Agente en el backend.
* [Solución de problemas](/es-419/sdk/security/troubleshooting): diagnosticar fallas 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 pasárselo a createEmbedToken.            |
| Símbolo    | SDK -> Backend de socios | Símbolo de intercambio 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 expiración del token devuelta por 6MM.                                         |

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

| Condición                                 | Manejo recomendado                                                                         |
| ----------------------------------------- | ------------------------------------------------------------------------------------------ |
| Sesión en pareja 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 solicitud y recrea la instancia del widget.                                     |
| El usuario no tiene permitido operar      | Devuelve un error controlado por el socio y no crees un token embed.                       |

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

Agent-SSO mantiene el flujo antiguo de tickets de entrada de agente. 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
    },
  },
})
```