Skip to content

Flutter SDK

Plugin Flutter xây trên SDK iOS / Android gốc, cung cấp một CaptchalaClient Dart duy nhất cho cả hai nền tảng di động. Cũng hỗ trợ desktop Linux / macOS / Windows qua WebView nhúng.

Demo trên GitHub

📦

Captcha-La/flutter-demo — ví dụ đầy đủ, có thể chạy được, kèm mọi bước tích hợp.

Cài đặt

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

Bắt đầu nhanh

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 chính

Ký hiệuMục đích
CaptchalaClient.instanceTruy cập singleton của plugin.
CaptchalaConfig(...)Bản ghi Dart đơn giản: appKey, action, lang, theme, enableVoice, enableOfflineMode, maskClosable, serverToken.
await client.initialize(config)Áp dụng cấu hình. Trả về cùng một client instance để chain setCallbacks.
setCallbacks(...)Đăng ký các callback onSuccess, onFail, onError, onClose, onServerTokenExpired.
await client.verify()Mở giao diện CAPTCHA native (Android: Activity phủ trên Flutter; iOS: UIViewController).
CaptchalaResultĐược truyền cho onSuccess. Trường: passToken, challengeId, ttl, isOffline, isClientOnly.

Xác thực phía máy chủ

Chuyển result.passToken (hoặc result.token) tới backend của bạn rồi xác thực qua API CaptchaLa. Tuyệt đối không để lộ X-App-Secret trong mã client.

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>" }

Xem Tài liệu API để biết chi tiết endpoint xác thực và quy trình X-App-Key / X-App-Secret.

Khắc phục sự cố

  • iOS pod install thất bại
    Trong ios/Podfile, đặt platform :ios, '13.0' (hoặc cao hơn). Sau khi đổi phiên bản plugin, chạy flutter clean && flutter pub get && cd ios && pod install.

  • minSdkVersion Android không khớp
    Nâng minSdkVersion trong android/app/build.gradle lên 21. SDK Android gốc sẽ từ chối compile ở mức thấp hơn.

  • Callback chạy trên isolate nền
    Luôn dùng if (mounted) trước khi gọi setState trong callback. Demo đã bọc mọi callback cập nhật state bằng kiểm tra này.

  • Target desktop (Linux / Windows / macOS)
    Linux cần GTK3 + WebKitGTK + libcurl. Windows cần Edge WebView2 Runtime (Win 10 1809+). Desktop macOS dùng WebView hệ thống tự động.

Yêu cầu

  • 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