Skip to content

Flutter SDK

Flutter 套件基於原生 iOS / Android SDK 包裝,統一暴露一個 Dart 的 CaptchalaClient。同時支援 Linux / macOS / Windows 桌面端(內嵌 WebView)。

GitHub 上的範例

📦

Captcha-La/flutter-demo — 完整可執行範例,包含所有整合步驟。

安裝

Add the package from pub.dev:

yaml
# pubspec.yaml
dependencies:
  captchala: ^1.3.2
  http: ^1.2.0          # used by the demo's token-fetch helpers
bash
flutter pub get
flutter run               # auto-picks the foreground device
# or:
flutter run -d <device-id>

For iOS / macOS the first build runs pod install automatically. Make sure ios/Podfile declares platform :ios, '13.0' (or higher).

快速開始

dart
import 'package:flutter/material.dart';
import 'package:captchala/captchala.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});
  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  String _status = 'Tap to verify';
  bool _verifying = false;

  Future<void> _runVerify() async {
    setState(() { _verifying = true; _status = 'Fetching server_token...'; });

    // 1. Fetch a one-shot server_token from YOUR backend.
    final initialToken = await fetchServerTokenFromYourBackend();

    // 2. Build config from your business action.
    final config = CaptchalaConfig(
      appKey: 'YOUR_APP_KEY',
      action: 'login',                  // login, register, pay, …
      lang: 'en',                       // en, zh-CN, zh-TW, ja, ko, ms, vi, id
      theme: 'light',                   // 'light' | 'dark'
      enableVoice: true,
      enableOfflineMode: true,
      maskClosable: false,
      serverToken: initialToken,
    );

    // 3. Initialize, register callbacks, then call verify().
    final client = await CaptchalaClient.instance.initialize(config);
    client.setCallbacks(
      onSuccess: (r) async {
        // Send r.passToken to YOUR backend for validation.
        if (!mounted) return;
        setState(() { _status = 'OK: ${r.passToken}'; _verifying = false; });
      },
      onFail:    (e) { if (mounted) setState(() { _status = 'fail: ${e.code}'; _verifying = false; }); },
      onError:   (e) { if (mounted) setState(() { _status = 'error: ${e.code} ${e.message}'; _verifying = false; }); },
      onClose:   () { if (mounted && _verifying) setState(() { _status = 'closed'; _verifying = false; }); },
      onServerTokenExpired: () => fetchServerTokenFromYourBackend(),
    );
    await client.verify();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          ElevatedButton(
            onPressed: _verifying ? null : _runVerify,
            child: Text(_verifying ? 'Verifying...' : 'Verify with CAPTCHA'),
          ),
          const SizedBox(height: 12),
          Text(_status, style: const TextStyle(fontFamily: 'monospace')),
        ]),
      ),
    );
  }
}

API 一覽

符號用途
CaptchalaClient.instance外掛程式的單例存取入口。
CaptchalaConfig(...)普通 Dart 資料類別:appKeyactionlangthemeenableVoiceenableOfflineModemaskClosableserverToken
await client.initialize(config)套用設定,回傳同一個 client 實例,便於串接 setCallbacks
setCallbacks(...)註冊 onSuccessonFailonErroronCloseonServerTokenExpired 回呼。
await client.verify()開啟原生驗證碼視圖(Android:在 Flutter 之上呈現 Activity;iOS:UIViewController)。
CaptchalaResultonSuccess 中回傳的物件。欄位:passTokenchallengeIdttlisOfflineisClientOnly

伺服器端驗證

result.passToken(或 result.token)送到你的後端,再呼叫 CaptchaLa API 驗證。切勿在用戶端程式碼中暴露 X-App-Secret

bash
POST https://apiv1.captcha.la/v1/validate
X-App-Key: YOUR_APP_KEY
X-App-Secret: YOUR_APP_SECRET
Content-Type: application/json

{ "pass_token": "<result.passToken>", "client_ip": "<end-user IP>" }

完整驗證端點及 X-App-Key / X-App-Secret 流程請見 API 參考

常見問題

  • iOS pod install 失敗
    ios/Podfile 中設定 platform :ios, '13.0'(或更高)。切換外掛程式版本後執行 flutter clean && flutter pub get && cd ios && pod install

  • Android minSdkVersion 不一致
    android/app/build.gradleminSdkVersion 提升到 21。低於該版本時原生 SDK 會拒絕編譯。

  • 回呼在背景 isolate 上觸發
    在回呼中呼叫 setState 前,先用 if (mounted) 守衛 UI 狀態變更。demo 中每個會更新狀態的回呼都做了這項檢查。

  • 桌面端(Linux / Windows / macOS)
    Linux 需要 GTK3 + WebKitGTK + libcurl。Windows 需要 Edge WebView2 Runtime(Windows 10 1809+)。macOS 桌面會自動使用系統 WebView。

系統需求

  • Flutter 3.10+ / Dart 3.0+
  • Android: minSdkVersion 21 (Android 5.0+)
  • iOS: 13.0+ with CocoaPods
  • Desktop (optional): GTK3 + WebKitGTK on Linux, WebView2 Runtime on Windows 10 1809+

MIT-licensed examples · CaptchaLa is operated independently