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

# 设置你的服务器以与 Fluz JS 小部件交互

安装 Fluz Javascript 小部件相对简单。

你需要将该 Javascript 嵌入或导入到你网站的某个页面中。Javascript 加载后，你可以将某个 UI 元素绑定为打开随导入脚本一起提供的 Javascript 模态框。

你还必须包含一个 JWT，用于预先授权用户完成特定交易，详细说明如下。

## 创建“预先批准的交易”令牌

由于用户会与 Fluz 平台交互以在你的消费账户之间转入和转出资金，任何与小部件的交互都必须包含一个已签名的 JWT 令牌，以有效“预授权”用户完成交易。

这意味着，例如，如果用户“abc123”在其运营商账户中有 \$50 想要提现到 Fluz，你需要生成一个 `patToken`，以便 Fluz 可以用它来验证交易和金额。该 patToken 包含 `amount`、你的 `apiKey`、`transactionType`、`externalId`、用户数据，以及一个 JTI。此令牌使用你的 `apiSecret` 签名，你可以在 Fluz 的 `for-developers` 部分的应用详情中找到它。

| key                    | value                                                                                                                |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------- |
| amount                 | 用户被批准用于交易的金额（以美元与美分为单位）                                                                                              |
| transactionType        | `DEPOSIT` 或 `WITHDRAW`。<br />`DEPOSIT` 表示用户将资金充值到 Fluz，然后再转入你的运营商消费账户。<br />`WITHDRAW` 表示用户从你的运营商消费账户向其 Fluz 账户进行提现。 |
| apiKey                 | 你的应用的 API key                                                                                                        |
| externalId             | 你用于标识用户的唯一标识符。可以是 userId、accountId、电话号码、电子邮件地址——无论你在系统中使用什么。当我们向你发送诸如 webhook 事件之类的信息时会提供此字段，以便你在系统中完成用户映射。          |
| jti                    | 签名令牌时生成的 UUID v4。我们将此令牌用于幂等性。你可以在[官方 jti 规范](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7)中了解更多信息。           |
| phoneNumber (optional) | 包含用户电话号码的字符串。如果提供，用户将跳过登录/注册流程中的 **Enter the phone number** 步骤，并直接进入 **Enter the two-factor-authentication code** 步骤 |
| firstName (optional)   | 用户的名字字符串                                                                                                             |
| lastName (optional)    | 用户的姓氏字符串                                                                                                             |
| email (optional)       | 用户的电子邮件字符串                                                                                                           |
| username (optional)    | 用户名字符串                                                                                                               |

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