All Products
Search
Document Center

Captcha:Integrate Flutter for OpenHarmony with the V3 architecture

Last Updated:Oct 23, 2025

You can use a WebView component to integrate Alibaba Cloud Captcha 2.0 for mobile HTML5 and provide human-computer authentication for your app. This approach is common in mature hybrid mobile application (Hybrid App) development. This topic describes how to integrate Captcha 2.0 with an app developed using Flutter for OpenHarmony.

Background information

Captcha 2.0 for mobile HTML5 provides benefits such as rapid iteration and strong compatibility. Integrating the Captcha 2.0 service with your app using a WebView helps you avoid compatibility issues caused by dependencies and references in native app components. The rapid iteration of mobile HTML5 Captcha 2.0 also helps your app better handle high-risk scenarios.

Integration flow

To integrate Captcha 2.0 for HTML5 with a Flutter app, follow these steps:

  1. HTML5 page client: Integrate Captcha 2.0 on the client of your HTML5 business page.

  2. Server for the HTML5 page: Integrate the Captcha 2.0 software development kit (SDK) on your server. Then, call the VerifyIntelligentCaptcha API operation to perform secondary authentication.

  3. Flutter for OpenHarmony app: Use the flutter_inappwebview plugin to load the business page that requires Captcha 2.0 in your app.

Prerequisites

  • You have enabled the Alibaba Cloud Captcha 2.0 service.

  • You have created an authentication scenario and set the Integration Method to Webview+H5 (Supports apps and mini-programs).

  • You have an app that is developed using Flutter for OpenHarmony. This topic uses version 3.22.0-ohos-1.0.4 as an example.

Procedure

Step 1: Integrate Captcha 2.0 on the client of the HTML5 business page

  1. In the code for your HTML5 business page client, integrate the client code provided by Captcha 2.0. For more information, see Integrate the client for web and H5 pages (V3 architecture).

    Note

    If your business uses the V2 architecture, see Integrate the client for web and H5 pages (V2 architecture).

  2. In the `success` callback function, add a JavaScript function to return the signature verification parameters to the custom Message Passing Interface (MPI) testJsInterface. This interface is defined in Step 3. After the Flutter interface receives the parameters, the Flutter app can send requests for signature verification and process the results.

    // success callback function
    function success(captchaVerifyParam) {
        // Send the verification result to Flutter (using the communication method of flutter_inappwebview)
        if (window.flutter_inappwebview && window.flutter_inappwebview.callHandler) {
            window.flutter_inappwebview.callHandler('testInterface', captchaVerifyParam);
        }
    }

Step 2: Integrate Alibaba Cloud Captcha 2.0 on the server for the HTML5 page

On your HTML5 business page server, integrate the server-side SDK provided by Captcha 2.0. Then, call the VerifyIntelligentCaptcha API operation to initiate signature verification for your business requests. For more information, see Server-side integration.

Step 3: Enable and deploy the business page in the Flutter app

  1. Add the webview_flutter dependency to the pubspec.yaml file:

    dependencies:
      flutter:
      sdk: flutter
      # Use the WebView plugin that supports the HarmonyOS platform
      flutter_inappwebview:
        git:
          url: https://gitcode.com/openharmony-sig/flutter_inappwebview
          path: "flutter_inappwebview"
  2. Configure the OpenHarmony application: In the ohos/entry/src/main/module.json5 file, add network permissions:

    {
      "module": {
        "name": "entry",
        "type": "entry",
        // Other configurations
        // ...
        "requestPermissions": [
          {"name": "ohos.permission.INTERNET"},
          {"name": "ohos.permission.GET_NETWORK_INFO"}
        ]
      }
    }
  3. Create a Flutter page to load the Captcha WebView:

    import 'package:flutter/material.dart';
    import 'package:flutter_inappwebview/flutter_inappwebview.dart';
    import 'package:flutter/services.dart';
    
    class CaptchaPage extends StatefulWidget {
      const CaptchaPage({Key? key, required this.title}) : super(key: key);
      final String title;
    
      @override
      State<CaptchaPage> createState() => _CaptchaPageState();
    }
    
    class _CaptchaPageState extends State<CaptchaPage> {
      InAppWebViewController? _controller;
    
      @override
      void initState() {
        super.initState();
      }
    
      // Handle the Captcha verification result
      void _handleCaptchaResult(dynamic captchaVerifyParam) {
        try {
          print('Received Captcha parameters: $captchaVerifyParam');
          
          // Check if the parameters are empty
          if (captchaVerifyParam == null) {
            throw Exception('Received empty verification parameters');
          }
          
          // Directly send the verification parameters to the server
          _sendToServer(captchaVerifyParam);
          
        } catch (e) {
          print('Failed to process Captcha parameters: $e');
          _showSnackBar('Failed to process verification parameters: $e', isError: true);
        }
      }
    
      // Send verification parameters to the server (example)
      Future<void> _sendToServer(dynamic captchaVerifyParam) async {
        try {
          // Call your server-side API for secondary authentication here
          print('Preparing to send to the server for verification: $captchaVerifyParam');
          
          // Simulate successful server-side verification
          _showSnackBar('Server-side verification successful', isError: false);
        } catch (e) {
          print('Server-side verification failed: $e');
          _showSnackBar('Server-side verification failed: $e', isError: true);
        }
      }
    
      void _showSnackBar(String message, {bool isError = false}) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(message),
            backgroundColor: isError ? Colors.red : Colors.green,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          ),
          body: _buildWebViewContent(),
        );
      }
    
    
      // Build the WebView content
      Widget _buildWebViewContent() {
        return Stack(
          children: [
            InAppWebView(
              initialData: InAppWebViewInitialData(
                data: "",
              ),
              initialOptions: InAppWebViewGroupOptions(
                crossPlatform: InAppWebViewOptions(
                  javaScriptEnabled: true,
                  useShouldOverrideUrlLoading: true,
                ),
              ),
              onWebViewCreated: (InAppWebViewController controller) async {
                _controller = controller;
                
                // Add a JavaScript handler
                _controller!.addJavaScriptHandler(
                  handlerName: 'testInterface',
                  callback: (args) {
                    if (args.isNotEmpty) {
                      _handleCaptchaResult(args[0]);
                    }
                  },
                );
                
                // Load the HTML content
                try {
                  String htmlContent = await rootBundle.loadString('assets/captcha.html');
                  await _controller!.loadData(data: htmlContent, baseUrl: WebUri('https://localhost'));
                } catch (e) {
                  print('Failed to load HTML: $e');
                  _showSnackBar('Failed to load Captcha page: $e', isError: true);
                }
              },
            ),
          ],
        );
      }
    }
  4. Use the Captcha page in main.dart:

    import 'package:flutter/material.dart';
    import 'captcha_page.dart';  // Import the Captcha page
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Alibaba Cloud Captcha Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const CaptchaPage(title: 'Alibaba Cloud Captcha Demo'),
        );
      }
    }
  5. Update the pubspec.yaml file to add the HTML resource:

    flutter:
      assets:
        - assets/index.html
  6. Finally, compile and run the project:

    flutter build hap --debug

After you complete these configurations, Captcha 2.0 is integrated with your Flutter for OpenHarmony app. You can test the verification in your app. If the verification works as expected, the integration is successful.

Download the V3 architecture demo for Flutter for OpenHarmony

Flutter for OpenHarmony integration demo