Yandex SmartCaptcha in Android apps
To embed SmartCaptcha in an Android app:
- Create JavaScript Interface.
- Configure WebView to work with CAPTCHA.
- Retrieve the CAPTCHA test results.
Getting started
- Add HTML code to work with SmartCaptcha (or use a ready-made
https://smartcaptcha.yandexcloud.net/webview
). - Create a CAPTCHA following this guide.
- Retrieve the CAPTCHA keys. Copy the Client key and Server key field values from the Overview tab of the CAPTCHA you created. You will need the Client key to load web pages using CAPTCHA and the Server key, to get the CAPTCHA test results.
Create a JavaScript Interface
-
Create a class to receive messages using a callback function from your web page with CAPTCHA.
-
Define the
onGetToken(token: String)
method with the@JavascriptInterface
annotation. It is called when the web page returns a token for passing CAPTCHA verification:class WebJsInterface { @JavascriptInterface fun onGetToken(token: String) { //your code } }
Configure WebView to work with CAPTCHA
-
Create a WebView and add it to the screen.
-
Upload the URL of the web page with CAPTCHA to the WebView.
-
Add the
sitekey=<client_key>
query parameter to the URL:val webView = findViewById<WebView>(R.id.webViewCaptcha) webView.loadUrl("URL of the page with CAPTCHA?sitekey=<client_key>")
-
Add the created JavaScript Interface object to the WebView. Specify
NativeClient
as the second parameter (this is where the web page will send messages using a callback function):settings.javaScriptEnabled = true // Enables Javascript execution addJavascriptInterface(WebJsInterface(), "NativeClient")
Retrieve the CAPTCHA test results
-
Save the token for passing CAPTCHA verification. It is returned in the
onGetToken(token: String)
method once the service handles an attempt. -
To validate the token, send a GET request to
https://smartcaptcha.yandexcloud.net/validate
with the following parameters:secret
: Server key.token
: One-time token received after passing the check.ip
: IP address of the user that originated the request to validate the token. This is an optional parameter, but we ask you to provide the user IP when making requests. This helps improve SmartCaptcha performance.
Note
This logic must be implemented on the backend. Make sure the
secret
key does not get to the Android app.Sample request:
https://smartcaptcha.yandexcloud.net/validate?secret=<server_key>&ip=<user_IP>&token=<token>
-
Get a server response. It contains a JSON object with the
status
and themessage
fields. For example:-
It is a human:
{ "status": "ok", "message": "" }
-
It is a robot:
{ "status": "failed", "message": "" }
-