> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fluz.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Configura tu servidor para interactuar con el widget de Fluz JS

La instalación del widget de Javascript de Fluz es relativamente sencilla.

Debes incrustar o importar el Javascript en una página de tu sitio. Una vez que el javascript haya cargado, puedes vincular un elemento de la UI para abrir el modal de javascript incluido como parte del javascript importado.

También debes incluir un JWT que preautorice al usuario a completar una transacción en particular, como se describe a continuación.

## Crea un token de "Transacción preaprobada".

Dado que el usuario está interactuando con la plataforma de Fluz para mover dinero hacia y desde tu cuenta de gasto, cualquier interacción con el widget debe incluir un token JWT firmado que, en efecto, “preautoriza” al usuario para completar la transacción.

Lo que esto significa es que, por ejemplo, si el usuario "abc123" tiene \$50 en su cuenta de operador que desea retirar a Fluz, generas un `patToken` que Fluz puede usar para validar la transacción y el monto. Este patToken contiene el `amount`, tu `apiKey`, el `transactionType`, el `externalId`, datos del usuario y luego un JTI. Este token se firma con tu `apiSecret` que se puede encontrar en los detalles de tu app en la sección `for-developers` de Fluz.

| key                    | value                                                                                                                                                                                                                                                                                  |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| amount                 | el monto en dólares y centavos con el que el usuario está aprobado para transaccionar                                                                                                                                                                                                  |
| transactionType        | `DEPOSIT` o `WITHDRAW`.<br />`DEPOSIT` significa que el usuario está ingresando dinero a Fluz y luego moviéndolo a tu cuenta de gasto de operador.<br />`WITHDRAW` significa que el usuario está haciendo un pago desde tu cuenta de gasto de operador hacia su cuenta de Fluz.        |
| apiKey                 | la clave de API de tu app                                                                                                                                                                                                                                                              |
| externalId             | Tu identificador único para tu usuario. Puede ser un userId, accountId, número de teléfono, dirección de correo electrónico: lo que uses en tu sistema. Proporcionaremos esto cuando te enviemos información como eventos de webhook, para que puedas mapear al usuario en tu sistema. |
| jti                    | un UUID v4 que se genera cuando procedes a firmar el token. Usamos este token para idempotencia. Puedes leer más [en la especificación oficial de jti](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7).                                                                          |
| phoneNumber (optional) | una cadena con el número de teléfono del usuario. Si se envía, el usuario omitirá el paso **Enter the phone number** del inicio de sesión/registro y pasará directamente al paso **Enter the two-factor-authentication code**                                                          |
| firstName (optional)   | una cadena con el nombre del usuario                                                                                                                                                                                                                                                   |
| lastName (optional)    | una cadena con el apellido del usuario                                                                                                                                                                                                                                                 |
| email (optional)       | una cadena con el correo electrónico del usuario                                                                                                                                                                                                                                       |
| username (optional)    | una cadena con el nombre de usuario                                                                                                                                                                                                                                                    |

## Fragmentos de código para generar el JWT

### JavaScript

```javascript theme={null}
import jwt from 'jsonwebtoken';

const { sign } = jwt;
const amount = 0; // Pass in the amount here
const transactionType = ""; // DEPOSIT or WITHDRAW
const externalId = ""; // This is your unique identifier. It might be a userID, accountID.

const jti = uuidv4();

const secret = ""; // Your api secret

const generatedToken = sign({
  amount,
  apiKey: "", // Your apiKey
  transactionType,
  externalId,
  jti,
}, secret, { expiresIn: '1 day' });
```

### Ruby

Instalación:

`gem install jwt`

```ruby theme={null}
require 'jwt'
require 'securerandom'

amount = 0 # Pass in the amount here
transaction_type = "" # DEPOSIT or WITHDRAW
external_id = "" # This is your unique identifier. It might be a userID, accountID.

jti = SecureRandom.uuid

secret = "" # Your api secret

payload = {
  amount: amount,
  apiKey: "", # Your apiKey
  transactionType: transaction_type,
  externalId: external_id,
  jti: jti,
  exp: Time.now.to_i + (24 * 60 * 60) # 1 day
}

generated_token = JWT.encode(payload, secret, 'HS256')
puts generated_token
```

### Python

Instalación:

`pip install PyJWT`

```python theme={null}
import jwt
import uuid
from datetime import datetime, timedelta

amount = 0  # Pass in the amount here
transaction_type = "" # DEPOSIT or WITHDRAW
external_id = ""  # This is your unique identifier. It might be a userID, accountID.

jti = str(uuid.uuid4())

secret = ""  # Your API_SECRET. Please reach out to your Fluz account manager if you do not have this.

payload = {
    "amount": amount,
    "apiKey": "", # Your apiKey
    "transactionType": transaction_type,
    "externalId": external_id,
    "jti": jti,
    "exp": datetime.utcnow() + timedelta(days=1)
}

generated_token = jwt.encode(payload, secret, algorithm="HS256")
print(generated_token)
```

### Go

```go theme={null}
package main

import (
    "fmt"
    "time"
    "github.com/golang-jwt/jwt/v5"
    "github.com/google/uuid"
)

func main() {
    amount := 0 // Pass in the amount here
    transactionType := "" // DEPOSIT or WITHDRAW
    externalId := "" // This is your unique identifier. It might be a userID, accountID.
    
    jti := uuid.New().String()
    
    secret := "" // Your api_secret
    
    claims := jwt.MapClaims{
        "amount":          amount,
        "apiKey":          "", // your api_key
        "transactionType": transactionType,
        "externalId":      externalId,
        "jti":             jti,
        "exp":             time.Now().Add(24 * time.Hour).Unix(),
    }
    
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    generatedToken, err := token.SignedString([]byte(secret))
    
    if err != nil {
        fmt.Println("Error generating token:", err)
        return
    }
    
    fmt.Println(generatedToken)
}
```

### Java

```java theme={null}
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JwtGenerator {
    public static void main(String[] args) {
        int amount = 0; // Pass in the amount here
        String transactionType = ""; // DEPOSIT or WITHDRAW
        String externalId = ""; // This is your unique identifier. It might be a userID, accountID.
        
        String jti = UUID.randomUUID().toString();
        
        String secret = ""; // Your api_secret
        
        Map<String, Object> claims = new HashMap<>();
        claims.put("amount", amount);
        claims.put("apiKey", ""); // your api_key
        claims.put("transactionType", transactionType);
        claims.put("externalId", externalId);
        
        long expirationTime = System.currentTimeMillis() + (24 * 60 * 60 * 1000); // 1 day
        
        String generatedToken = Jwts.builder()
                .setClaims(claims)
                .setId(jti)
                .setExpiration(new Date(expirationTime))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        
        System.out.println(generatedToken);
    }
}
     
```

### PHP

```php theme={null}
<?php

require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Ramsey\Uuid\Uuid;

$amount = 0; // Pass in the amount here
$transactionType = ""; // DEPOSIT or WITHDRAW
$externalId = ""; // This is your unique identifier. It might be a userID, accountID.

$jti = Uuid::uuid4()->toString();

$secret = ""; // Your api_secret

$payload = [
    "amount" => $amount,
    "apiKey" => "", // your api_key
    "transactionType" => $transactionType,
    "externalId" => $externalId,
    "jti" => $jti,
    "exp" => time() + (24 * 60 * 60) // 1 day
];

$generatedToken = JWT::encode($payload, $secret, 'HS256');
echo $generatedToken;
?>
```

### C# (.NET)

```csharp theme={null}
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;

class JwtGenerator
{
    static void Main()
    {
        int amount = 0; // Pass in the amount here
        string transactionType = ""; // DEPOSIT or WITHDRAW
        string externalId = ""; // This is your unique identifier. It might be a userID, accountID.
        
        string jti = Guid.NewGuid().ToString();
        
        string secret = ""; // Your api_secret
        
        var claims = new List<Claim>
        {
            new Claim("amount", amount.ToString()),
            new Claim("apiKey", ""), // your api_key
            new Claim("transactionType", transactionType),
            new Claim("externalId", externalId),
            new Claim(JwtRegisteredClaimNames.Jti, jti)
        };
        
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        
        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.UtcNow.AddDays(1),
            signingCredentials: creds
        );
        
        var generatedToken = new JwtSecurityTokenHandler().WriteToken(token);
        Console.WriteLine(generatedToken);
    }
}
```
