> ## 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 Widget 互動

安裝 Fluz Javascript widget 相對簡單。

您必須在您網站的某個頁面嵌入或匯入該 Javascript。當 javascript 載入後，您可以綁定一個 UI 元件，以開啟作為匯入 javascript 一部分所包含的 javascript 模態視窗。

您也必須包含一個 JWT，用來預先授權使用者完成特定交易，如下所述。

## 建立「預先核准交易」權杖。

由於使用者會與 Fluz 平台互動，將資金在您的消費帳戶中進出，任何與 widget 的互動都必須包含一個已簽署的 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

安裝：

`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

安裝：

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