Integrate with the V3 architecture using Webview+H5

更新时间:
复制 MD 格式

Alibaba Cloud Captcha uses a WebView component to load an H5 CAPTCHA page inside your mini program. After the user completes the challenge, the H5 page passes captchaVerifyParam back to your service page for secondary authentication. This topic covers WeChat Mini Program and Alipay Mini Program integration.

Prerequisites

Before you begin, ensure that you have:

How it works

The integration follows a four-stage data flow:

  1. Your service page navigates to the Alibaba Cloud Captcha page inside the mini program.

  2. The Captcha page loads the H5 CAPTCHA challenge in a WebView.

  3. After the user passes the challenge, the H5 page posts captchaVerifyParam back to the mini program via postMessage.

  4. The mini program forwards captchaVerifyParam to your service page through the event channel. Your server then uses it for secondary authentication.

Integration steps

  1. Upload the Alibaba Cloud Captcha H5 page to an HTTPS server you control — a web server, OSS bucket, or CDN all work, as long as the page is served over HTTPS with a text/html content type.

  2. Add the H5 page's domain as a service domain in the WeChat Mini Program admin console or the Alipay Mini Program admin console. For details, see Add a service domain name (WeChat) and Configure an H5 domain name (Alipay).

  3. Create a mini program page that hosts the Captcha H5 page in a WebView component.

  4. From your service page, navigate to the Captcha page. After verification succeeds, the page redirects back with captchaVerifyParam. Use it to trigger secondary authentication.

Flowchart

image

Choose a framework

Select the tab that matches your project:

FrameworkWhen to use
Native mini programPure WeChat or Alipay native development, no cross-platform framework
uni-appCross-platform project using the uni-app framework
TaroCross-platform project using Taro + React

Integration examples

All examples use the V3 architecture.

WeChat Mini Program

H5 CAPTCHA page

Host this HTML file on your HTTPS server. It initializes the CAPTCHA widget and, after the user passes, sends captchaVerifyParam back to the mini program.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <meta name="data-spm" content="5176"/>
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
        <script>
            window.AliyunCaptchaConfig = {
                region: 'cn',
                prefix: 'xxxxxx',
            };
        </script>
        <script type="text/javascript" src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"></script>
        <script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>

    </head>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
        }

        #captcha-container {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background-color: #f5f5f5;
        }

        #captcha-element {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>

    <body>
        <div id="captcha-container">
            <div id="captcha-element"></div>
            <div id="captcha-button"></div>
        </div>

        <script type="text/javascript">
            var captcha;

            function initCaptcha() {
                window.initAliyunCaptcha({
                    SceneId: 'xxxxxx',
                    mode: 'embed',
                    element: '#captcha-element',
                    button: '#captcha-button',
                    success: success,
                    fail: fail,
                    getInstance: getInstance,
                    slideStyle: {
                        width: 360,
                        height: 40,
                    },
                    language: 'cn',
                    timeout: 5000,
                });
            }

            initCaptcha();

            function getInstance(instance) {
                console.log(instance)
                captcha = instance;
            }

            function success(captchaVerifyParam) {
                console.log(captchaVerifyParam);
                // Send captchaVerifyParam back to the mini program.
                wx.miniProgram.postMessage({
                  data: captchaVerifyParam,
                });
                wx.miniProgram.navigateBack();
            }

            function fail(err) {
                console.error(err);
            }
        </script>
    </body>
</html>

Native mini program

Download the full demo: weixin.zip

The Captcha page wraps the H5 page in a WebView. When the H5 page posts a message, the page receives captchaVerifyParam and forwards it to your service page through the event channel.

  1. Create a mini program page for Alibaba Cloud Captcha:

    // main/AliyunCaptcha/AliyuCaptcha.js
    Page({
      data: {
        eventChannel: undefined,
        webViewSrc: 'https://your-captcha-page/index.html'
      },
      onLoad(options) {
        // Get the event channel opened by the service page.
        this.eventChannel = this.getOpenerEventChannel();
      },
      onMessage(e) {
        const captchaVerifyParam = e.detail.data[0];
        console.log('captchaVerifyParam:', captchaVerifyParam);
        // Emit the getCaptchaVerifyParam event so the service page receives the verification parameter.
        if (this.eventChannel) {
          this.eventChannel.emit('getCaptchaVerifyParam', captchaVerifyParam);
        }
      }
    })
    <!--main/AliyunCaptcha/AliyunCaptcha.wxml-->
    <view>
      <web-view src="{{webViewSrc}}" bindmessage="onMessage"></web-view>
    </view>

    Add the page path to page.json:

    {
      "pages": [
        "main/AliyunCaptcha/AliyunCaptcha"
      ]
    }
  2. Trigger navigation to the Captcha page from your service page:

    // main/BizPage/BizPage.js
    Page({
      openAliyunCaptcha() {
        wx.navigateTo({
          url: "/main/AliyunCaptcha/AliyuCaptcha",
          events: {
            // Listen for the getCaptchaVerifyParam event emitted by the Captcha page.
            getCaptchaVerifyParam: (captchaVerifyParam) => {
              console.log('Captcha return result:', captchaVerifyParam)
              // Initiate secondary authentication.
            }
          }
        })
      }
    })
    <!--main/BizPage/BizPage.wxml-->
    <button bindtap="openAliyunCaptcha">Redirect to Alibaba Cloud Captcha H5</button>
  3. After verification succeeds, the H5 page navigates back and the service page receives captchaVerifyParam through the event channel. Use it to initiate secondary authentication.

uni-app

Download the full demo: uniapp.zip

The Captcha page uses a <web-view> component. When the H5 page posts a message, onMessage extracts captchaVerifyParam from e.detail.data[0] and forwards it via the event channel.

  1. Create a mini program page for Alibaba Cloud Captcha:

    <template>
    	<web-view src="https://your-captcha-page/index.html" @message="onMessage"></web-view>
    </template>
    
    <script>
    	export default {
    		methods: {
    			onMessage(e) {
    			  const captchaVerifyParam = e.detail.data[0];
    			  const eventChannel = this.getOpenerEventChannel();
    			  // Forward captchaVerifyParam to the service page.
    			  eventChannel && eventChannel.emit('getCaptchaVerifyParam', captchaVerifyParam);
    			}
    		}
    	}
    </script>

    Add the page path to page.json:

    {
    	"pages": [
    		{
    			"path" : "pages/AliyunCaptcha/AliyunCaptcha",
    			"style" :
    			{
    				"navigationBarTitleText": "Alibaba Cloud Captcha Mini Program H5"
    			}
    		}
    	]
    }
  2. Trigger navigation to the Captcha page from your service page:

    <template>
    	<button @click="handleClickAliyunCaptcha">Trigger Alibaba Cloud Captcha</button>
    </template>
    
    <script>
    	export default {
    		methods: {
    			handleClickAliyunCaptcha(){
    				uni.navigateTo({
    					url:'/pages/AliyunCaptcha/AliyunCaptcha',
    					events: {
    						getCaptchaVerifyParam: (captchaVerifyParam) => {
    						  console.log('Captcha return result:', captchaVerifyParam)
    						  // Initiate secondary authentication.
    						}
    					}
    				});
    			}
    		}
    	}
    </script>
  3. After verification succeeds, the H5 page navigates back and the service page receives captchaVerifyParam through the event channel. Use it to initiate secondary authentication.

Taro

Download the full demo: taro.zip

The Captcha page uses Taro's WebView component. When the H5 page posts a message, handleWebViewMessage retrieves captchaVerifyParam from event.detail.data[0] using Taro.getCurrentInstance().page.getOpenerEventChannel().

  1. Create a mini program page for Alibaba Cloud Captcha:

    import { View, WebView } from '@tarojs/components';
    import Taro from '@tarojs/taro';
    
    export default function Index() {
      const webViewSrc = 'https://your-captcha-page/index.html';
    
      const handleWebViewMessage = (event) => {
        const captchaVerifyParam = event.detail.data[0];
        // Forward captchaVerifyParam to the service page.
        const eventChannel = Taro.getCurrentInstance().page.getOpenerEventChannel();
        eventChannel && eventChannel.emit('getCaptchaVerifyParam', captchaVerifyParam);
      };
    
      return <View>{webViewSrc && <WebView src={webViewSrc} onMessage={handleWebViewMessage} />}</View>;
    }

    Add the page path to app.config.js:

    export default defineAppConfig({
      pages: [
        'pages/AliyuCaptcha/AliyunCaptcha'
      ],
    })
  2. Trigger navigation to the Captcha page from your service page:

    import { View, Button } from '@tarojs/components';
    import Taro from '@tarojs/taro';
    
    export default function Index() {
      const handleClickAliyunCaptcha = () => {
        Taro.navigateTo({
          url: '/pages/AliyuCaptcha/AliyunCaptcha',
          events: {
            getCaptchaVerifyParam: function(captchaVerifyParam) {
              console.log('Captcha return result:', captchaVerifyParam);
              // Initiate secondary authentication.
            },
          },
        });
      };
    
      return (
        <View>
          <Button onClick={handleClickAliyunCaptcha}>Trigger Alibaba Cloud Captcha</Button>
        </View>
      );
    }
  3. After verification succeeds, the H5 page navigates back and the service page receives captchaVerifyParam through the event channel. Use it to initiate secondary authentication.

Alipay Mini Program

H5 CAPTCHA page

Host this HTML file on your HTTPS server. It uses the Alipay JS SDK (appx/web-view.min.js) and, after the user passes the challenge, sends captchaVerifyParam back via my.postMessage().

<!doctype html>
<html>
    <head>
        <meta charset="utf-8"/>
        <meta name="data-spm" content="5176"/>
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
        <script>
            window.AliyunCaptchaConfig = {
                region: 'cn',
                prefix: 'xxxxxx',
            };
        </script>
        <script type="text/javascript" src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"></script>
        <script src="https://appx/web-view.min.js"></script>

    </head>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
        }

        #captcha-container {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background-color: #f5f5f5;
        }

        #captcha-element {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>

    <body>
        <div id="captcha-container">
            <div id="captcha-element"></div>
            <div id="captcha-button"></div>
        </div>

        <script type="text/javascript">
            var captcha;

            function initCaptcha() {
                window.initAliyunCaptcha({
                    SceneId: 'xxxxxx',
                    mode: 'embed',
                    element: '#captcha-element',
                    button: '#captcha-button',
                    success: success,
                    fail: fail,
                    getInstance: getInstance,
                    slideStyle: {
                        width: 360,
                        height: 40,
                    },
                    language: 'cn',
                    timeout: 5000,
                });
            }

            initCaptcha();

            function getInstance(instance) {
                console.log(instance)
                captcha = instance;
            }

            function success(captchaVerifyParam) {
                console.log(captchaVerifyParam);
                // Send captchaVerifyParam back to the mini program.
                my.postMessage({ data: captchaVerifyParam });
                my.navigateBack();
            }

            function fail(err) {
                console.error(err);
            }
        </script>
    </body>
</html>
The Alipay H5 page differs from the WeChat version in two ways: it loads appx/web-view.min.js instead of the WeChat JSSDK, and it uses my.postMessage() and my.navigateBack() instead of wx.miniProgram.*.

Native mini program

Download the full demo: alipay.zip

The Captcha page wraps the H5 page in a WebView. When the H5 page posts a message, onMessage reads captchaVerifyParam directly from e.detail.data (not e.detail.data[0] as in WeChat) and forwards it via the event channel.

  1. Create a mini program page for Alibaba Cloud Captcha:

    // pages/AliyunCaptcha/AliyuCaptcha.js
    Page({
      data: {
        webViewSrc: 'https://your-captcha-page/index.html'
      },
      onMessage(e) {
        const captchaVerifyParam = e.detail.data;
        // Forward captchaVerifyParam to the service page.
        this.eventChannel = this.getOpenerEventChannel();
        this.eventChannel && this.eventChannel.emit('getCaptchaVerifyParam', captchaVerifyParam);
      },
    })
    <!--main/AliyunCaptcha/AliyuCaptcha.axml-->
    <view>
      <web-view src="{{webViewSrc}}" onMessage="onMessage"></web-view>
    </view>

    Add the page path to page.json:

    {
      "pages": [
        "pages/AliyunCaptcha/AliyunCaptcha"
      ]
    }
  2. Trigger navigation to the Captcha page from your service page:

    // pages/index/index.js
    Page({
      openAliyunCaptcha() {
        my.navigateTo({
          url: "/pages/AliyunCaptcha/AliyuCaptcha",
          events: {
            getCaptchaVerifyParam: (captchaVerifyParam) => {
              console.log('Captcha return result:', captchaVerifyParam)
              // Initiate secondary authentication.
            }
          }
        })
      }
    });
    <!--page/index/index.axml-->
    <button bindtap="openAliyunCaptcha">Redirect to Alibaba Cloud Captcha H5</button>
  3. After verification succeeds, the H5 page navigates back and the service page receives captchaVerifyParam through the event channel. Use it to initiate secondary authentication.

uni-app

Download the full demo: uniapp_alipay.zip

The integration is identical to the WeChat uni-app example, except that Alipay passes captchaVerifyParam as e.detail.data (not e.detail.data[0]).

  1. Create a mini program page for Alibaba Cloud Captcha:

    <template>
    	<web-view src="https://your-captcha-page/index.html" @message="onMessage"></web-view>
    </template>
    
    <script>
    	export default {
    		methods: {
    			onMessage(e) {
    			  const captchaVerifyParam = e.detail.data;
    			  const eventChannel = this.getOpenerEventChannel();
    			  // Forward captchaVerifyParam to the service page.
                  eventChannel && eventChannel.emit('getCaptchaVerifyParam', captchaVerifyParam);
    			}
    		}
    	}
    </script>

    Add the page path to page.json:

    {
    	"pages": [
    		{
    			"path": "pages/AliyunCaptcha/AliyunCaptcha",
    			"style":
    			{
    				"navigationBarTitleText": "Alibaba Cloud Captcha Mini Program H5"
    			}
    		}
    	]
    }
  2. Trigger navigation to the Captcha page from your service page:

    <template>
    	<button @click="handleClickAliyunCaptcha">Trigger Alibaba Cloud Captcha</button>
    </template>
    
    <script>
    	export default {
    		methods: {
    			handleClickAliyunCaptcha(){
    				uni.navigateTo({
    					url:'/pages/AliyunCaptcha/AliyunCaptcha',
    					events: {
    						getCaptchaVerifyParam: (captchaVerifyParam) => {
    						  console.log('Captcha return result:', captchaVerifyParam)
    						  // Initiate secondary authentication.
    						}
    					}
    				});
    			}
    		}
    	}
    </script>
  3. After verification succeeds, the H5 page navigates back and the service page receives captchaVerifyParam through the event channel. Use it to initiate secondary authentication.

Taro

Download the full demo: taro_alipay.zip

The integration is identical to the WeChat Taro example, except that Alipay passes captchaVerifyParam as event.detail.data (not event.detail.data[0]).

  1. Create a mini program page for Alibaba Cloud Captcha:

    import { View, WebView } from '@tarojs/components';
    import Taro from '@tarojs/taro';
    
    export default function Index() {
      const webViewSrc = 'https://your-captcha-page/index.html';
    
      const handleWebViewMessage = (event) => {
        const captchaVerifyParam = event.detail.data;
        // Forward captchaVerifyParam to the service page.
        const eventChannel = Taro.getCurrentInstance().page.getOpenerEventChannel();
        eventChannel && eventChannel.emit('getCaptchaVerifyParam', captchaVerifyParam);
      };
    
      return <View>{webViewSrc && <WebView src={webViewSrc} onMessage={handleWebViewMessage} />}</View>;
    }

    Add the page path to app.config.js:

    export default defineAppConfig({
      pages: [
        'pages/AliyuCaptcha/AliyunCaptcha'
      ],
    })
  2. Trigger navigation to the Captcha page from your service page:

    import { View, Button } from '@tarojs/components';
    import Taro from '@tarojs/taro';
    
    export default function Index() {
      const handleClickAliyunCaptcha = () => {
        Taro.navigateTo({
          url: '/pages/AliyuCaptcha/AliyunCaptcha',
          events: {
            getCaptchaVerifyParam: function(captchaVerifyParam) {
              console.log('Captcha return result:', captchaVerifyParam);
              // Initiate secondary authentication.
            },
          },
        });
      };
    
      return (
        <View>
          <Button onClick={handleClickAliyunCaptcha}>Trigger Alibaba Cloud Captcha</Button>
        </View>
      );
    }
  3. After verification succeeds, the H5 page navigates back and the service page receives captchaVerifyParam through the event channel. Use it to initiate secondary authentication.

Platform differences

AspectWeChatAlipay
H5 JS SDKjweixin-1.3.2.js from res.wx.qq.comweb-view.min.js from appx
Post-verification callbackwx.miniProgram.postMessage() + wx.miniProgram.navigateBack()my.postMessage() + my.navigateBack()
Navigate to Captcha pagewx.navigateTo()my.navigateTo()
Message binding (native)bindmessage="onMessage"onMessage="onMessage"
Data extractione.detail.data[0]e.detail.data

Troubleshooting

IssueCauseSolution
CAPTCHA page fails to load in WebViewH5 page domain not whitelistedAdd the H5 page domain as a service domain in the mini program admin console (step 2 of the integration steps).
captchaVerifyParam is undefined after verificationIncorrect data extraction pathWeChat uses e.detail.data[0]; Alipay uses e.detail.data. Verify you are using the correct path for your platform.
WebView shows a blank pageH5 page not served over HTTPS or wrong content typeMake sure the H5 page URL uses HTTPS and the server returns text/html as the content type.
Event channel does not receive captchaVerifyParamgetOpenerEventChannel() called at wrong timeFor WeChat native mini programs, call getOpenerEventChannel() in onLoad, not in onMessage.