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
- Host an HTML page on your server or use the
https://smartcaptcha.yandexcloud.net/webview
page on the Yandex Cloud server. - Create a CAPTCHA.
- See the Overview tab to get the CAPTCHA keys:
- Client key: To load the page with CAPTCHA.
- Server key: To get the CAPTCHA challenge 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.
-
Insert this query parameter into the URL:
sitekey=<client_side_key>
:val webView = findViewById<WebView>(R.id.webViewCaptcha) webView.loadUrl("CAPTCHA_page_URL?sitekey=<client_side_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 CAPTCHA verification passed token. It will be returned in the
onGetToken(token: String)
method after the service processes an attempt. -
To validate the token, send a POST request to
https://smartcaptcha.yandexcloud.net/validate
, providing the following parameters inx-www-form-urlencoded
format: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
secret key does not end up in the Android app itself.Request example:
https://smartcaptcha.yandexcloud.net/validate?secret=<server_key>&ip=<user_IP_address>&token=<token>
-
Get a server response. It contains a JSON object with the
status
andmessage
fields.Here is an example:
- It is a human:
{ "status": "ok", "message": "" }
- It is a robot:
{ "status": "failed", "message": "" }