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