> ## 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.

# Set Up Your Server to Interact With The Fluz JS Widget

Installation of the Fluz Javascript widget is relatively straightforward.

You must embed or import the Javascript onto a page on your site. Once the javascript has loaded in, you can bind a UI element to open the javascript modal included as part of the imported javascript.

You must also include a JWT that pre-authorizes the user to complete a particular transaction, as described below.

## Create a "Pre-approved transaction" token.

Since the user is interacting with the Fluz platform to move money in and out of your spend account, any interaction with the widget must include a signed JWT token that effectively "pre-authorizes" the user to complete the transaction.

What this means is, for instance, if user "abc123" has \$50 in their operator account that they wish to withdraw to Fluz, you generate a `patToken` that Fluz can use to validate the transaction and amount. This patToken contains the `amount`, your `apiKey`, the `transactionType`, the `externalId`, user data, and then a JTI. This token is signed with your `apiSecret` that can be found in your app details in the `for-developers` section of Fluz.

| key                    | value                                                                                                                                                                                                                                           |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| amount                 | the amount in dollars and cents that the user is approved to transact with                                                                                                                                                                      |
| transactionType        | `DEPOSIT` or `WITHDRAW`.<br />`DEPOSIT` means the user is putting money into Fluz, and then moving it to your operator spend account.<br />`WITHDRAW` means the user is doing a payout from your operator spend account to their Fluz account.  |
| apiKey                 | the API key of your app                                                                                                                                                                                                                         |
| externalId             | Your unique identifier for your user. Can be a userId, accountId, phone number, email address - whatever you use in your system. We will provide this when we send you information like webhook events, so you can map the user in your system. |
| jti                    | a UUID v4 that is generated when you go to sign the token. We use this token for idempotency. You can read more [in the official jti spec](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7).                                               |
| phoneNumber (optional) | a string with phone number of user. If passed, user will skip the **Enter the phone number** step of login/registration and will be moved straight to **Enter the two-factor-authentication code** step                                         |
| firstName (optional)   | a string with the first name of the user                                                                                                                                                                                                        |
| lastName (optional)    | a string with the last name of the user                                                                                                                                                                                                         |
| email (optional)       | a string with the email of user                                                                                                                                                                                                                 |
| username (optional)    | a string with the username                                                                                                                                                                                                                      |

## Code snippets to generate the 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

Installation:

`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

Installation:

`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);
    }
}
```
