Quick Start

You will need to have a registered account (Free Trial available) and your <SiteKey> to use MTCaptcha on your own website.

The best place to start and find out how to embed MTCaptcha captcha JavaScript plugin in to your website is to use our MTCaptcha CODE GENERATOR.

 
 

OR

Embed Code Snippet

You can copy the javascript code snippet below. Please make sure to replace the <SiteKey> with your sitekey from the Admin Portal.

<html>
<head>

    <!-- MTCaptcha configuration and import -->
    <script>
    var mtcaptchaConfig = {
      "sitekey": "<SiteKey>"
    };
   (function(){var mt_service = document.createElement('script');mt_service.async = true;mt_service.src = 'https://service.mtcaptcha.com/mtcv1/client/mtcaptcha.min.js';(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(mt_service);
   var mt_service2 = document.createElement('script');mt_service2.async = true;mt_service2.src = 'https://service2.mtcaptcha.com/mtcv1/client/mtcaptcha2.min.js';(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(mt_service2);}) ();
   </script>
    
</head>
<body>    
    
    <!-- MTCaptcha Anchor DOM -->
    <div class="mtcaptcha"></div>
  
</body>
</html>

Verified Token

On successful captcha verification, a token will be created and held in a HTML hidden input

<input type=’hidden’ name=’mtcaptcha-verifiedtoken’ value=’<token>’ />

CHECK Token (Server Side) API

To check the token is actually valid, use the HTTP API below

URL: https://service.mtcaptcha.com/mtcv1/api/checktoken?privatekey=<privatekey>&token=<token>

HTTP METHOD: GET

Parameters

  • privatekey : The PrivateKey secret (Required)

  • token : The verified token string. (Required)

Validate MTCaptcha Success Token

A Verified-Token will be created once a user is verified via captcha. This token must be checked on server side using the corresponding PrivateKey to insure its validity. The standard approach is to use the CheckToken API, for more customized and network sensitive usecases, the token can also be decrypted directly on server side.


Getting the Token

This Verified-Token can be found commonly via

  • HTML hidden input form with name ‘mtcaptcha-verifiedtoken’.

      <input type=’hidden’  name=’mtcaptcha-verifiedtoken’  …  />

and can also be found via

  • Javascript method

       mtcaptcha.getVerifiedToken()

  • part of the status callback argument via verified-callback (see JS Callbacks for more details)

       function mtcaptchaVerifiedCallback( status )  
       {  console.log( status.verifiedToken );  }


Token CONSTRAINTS

Each verifiedToken is normally valid for a few minutes, and can only be verified once via the CheckToken API to prevent replay attacks.

After you get the verifiedToken, you need to check it within the time limit to ensure the token is still valid. The MTCaptcha javascript widget will insure at least 50 seconds is available for the server to verify.



CheckToken API

URL: https://service.mtcaptcha.com/mtcv1/api/checktoken

HTTP METHOD: GET

Parameters:

  • privatekey : The shared PrivateKey secret between your server and MTCaptcha. (Required)

  • token : The VerifiedToken string. (Required)

    eg:

    https://service.mtcaptcha.com/mtcv1/api/checkton?privatekey=<your_privatekey>&token=<verified-token>

NOTE: To insure the PrivateKey is kept secret this API should only be called from server side.

For server side environemtsn that require explicit firewall ACLs for outbound traffic, see:



CheckToken API Response

The API response is a JSON object, sample responses below

{
  "success": true,
  "tokeninfo": {
    "v": "1.0",
    "code": 201,
    "codeDesc": "valid:captcha-solved",
    "tokID": "ae1e60a1e249c217cb7b05c4dba8dd0d",
    "timestampSec": 1552185983,
    "timestampISO": "2019-03-10T02:46:23Z",
    "hostname": "some.example.com",
    "isDevHost": false,
    "action": "",
    "ip": "10.10.10.10"
  }
}

Sample Failure Response

{
  "success": false,
  "fail_codes": [
    "token-expired"
  ],
  "tokeninfo": {
    "v": "1.0",
    "code": 201,
    "codeDesc": "valid:captcha-solved",
    "tokID": "25eff0c56a227781408a95a053c36b65",
    "timestampSec": 1552185729,
    "timestampISO": "2019-03-10T02:42:09Z",
    "hostname": "some.example.com",
    "isDevHost": false,
    "action": "",
    "ip": "10.10.10.10"
  }
}

CheckToken API Response Fields

FIELD DESCRIPTION
success ‘true’ if the token is valid. ‘false’ otherwise.

fail_codes

The code (reason) for validation failure, This field will only exist if success: false.
tokeninfo JSON object with the token metadata decrypted. This field may not exist on certain failures.
tokeninfo.v The version of the token format, should be “1.0”
tokeninfo.code The tokencode describing the method of verification. For full list of possible tokeninfo codes, see below.
tokeninfo.codeDesc The tokencode description. For full list of possible codes and descriptions, see below.
tokeninfo.tokID The unique GUID for the token, 128bits Hex/Base16 encoded.
tokeninfo.timestampSec     The time stamp when the token was created, in Unix epoch time (in seconds).
tokeninfo.timestampISO     The time stamp when the token was created, in ISO 8601 UTC format.
tokeninfo.hostname The hostname of the webpage the captcha was served under.
tokeninfo.isDevHost ‘true’ if the hostname matches ‘development domains’ configured for the site.
Tokeninfo.action The action string used on initialization of the captcha. If not defined defaults to empty string.
tokeninfo.ip The client IP of the user. In String format.


Response TokenInfo Codes & Descriptions

The codes for tokeninfo.code and tokeninfo.codeDesc

Token Codes Code Description Description
201 valid:captcha-solved Verified via the captcha challenge was solved.
211 valid:ip-whitelisted Verified via the client coming from an IP matching the IP whitelist for the site.
212 valid:low-friction Verified via the client deemed low risk, and the site has low-friction invisible captcha enabled.
301 valid-test:captcha-solved-via-testkey Verified via the TestKey (for automated testing).


Response Fail Codes

Possible response fail_codes

Fail Codes DESCRIPTION
token-expired The token has expired
token-duplicate-cal The token has been checked already, and thus should not be used.  
bad-request General error for unexpected bad/malformed requests.
missing-input-privatekey The parameter ‘privatekey’ is missing
missing-input-token The parameter ‘token’ is missing
invalid-privatekey The privatekey provided is not valid
invalid-token The token is not valid
invalid-token-faildecrypt The token is not valid and failed during decryption
privatekey-mismatch-token The token and the privatekey does not match. ie, the token was crated from another sitekey
expired-sitekey-or-account The sitekey/privatekey is no longer valid due to expiration or account closure.




Check Token via Server Side Decryption (Without External API Call)

The standard and easiest method of validating the MTCaptcha verifiedToken is via the checktoken API, but you can decrypt and decode the token directly on server side without making any external API calls to mtcaptcha.com. You will need the site PrivateKey and the ability to calculate MD5 hash and decrypt with AES cipher. Additional checks for timeout and single use will be needed on the server side to insure proper security.

Decrypt Sample Code

The sample java code to decrypt and decode the token can be found at the github project here :

https://github.com/mtcaptcha-public/MTCaptcha-Direct-Token-Decryption/



Verified-Token String Structure

"v1(" [MTCaptcha CheckSum] , [Customer Checksum] , [Sitekey] , [Random Seed] , [Encrypted TokenInfo] ")"


eg:

“v1(2f03cc7d,1058dfde,MTPublic-hal9000uJ,34715559cd42d3955114303c925c3582,kSdkIYA..…qOCQ**)”

[MTCaptcha CheckSum] : 2f03cc7d
[Customer Checksum] : 1058dfde
[Sitekey] : MTPublic-hal9000uJ
[Random Seed] : 34715559cd42d3955114303c925c3582
[Encrypted TokenInfo] : kSdkIYA..…qOCQ**

Verified Token Decryption Logic

[CalculatedCustomerCheckSum] = MD5( [Privatekey] + [SiteKey] + [Random Seed] + [Encrypted TokenInfo] ) .toHexLowercase() .substring(0,8)
[EncryptedTokenInfoBinary] = URLSafeBase64.decode( [Encrypted TokenInfo].replace("*","=") );
[SingleUseDecryptionKey128bit] = MD5( [Privatekey] + [Random Seed] )
[AesIV] = [SingleUseDecryptionKey128bit]
[DecryptedTokenInfoJson] = AES.decrpyt( "CBC/PKCS5Padding", [SingleUseDecryptionKey128bit], [AesIV], [EncryptedTokenInfoBinary] )

Textual Encoding / Decoding Format: UTF-8

Automated HTML Form Validation

When Auto Form Validation is enabled, the MTCaptcha widget will automatically prevent the HTML form submission unless the captcha is solved. It will also show a ‘please complete’ prompt message as below if captcha is not solved on attempted form submission.

mt-required.png

To enable auto form validation, us the ‘autoFormValidate’ javascript config param.

<script>
var mtcaptchaConfig = {
  "sitekey": "<YOUR SITE KEY>",
  "autoFormValidate": true
}
...
</script>

Captcha Action

For sites that need to use captcha on multiple pages or for different workflows, an (optional) ‘action’ parameter can be set on MTCaptcha initialization. This has the advantage of better analytics via the Admin Portal - dashboard and improved security.

<script>
var mtcaptchaConfig = {
  "sitekey": "<YOUR SITE KEY>",
  "action": "login"              // other examples: "register"  or "write-feedback" etc
}
...
</script>


Captcha Action FORMAT & Constraints

The ‘action’ parameter string can be up to a maximum of 30 characters long and may contain any of the following chars

  • Alphanumeric (a-zA-Z0-9)

  • Dash ‘ - ’

  • Underscore ‘ _ ’

  • Dot ‘ . ’

  • Comma ‘ , ’

or for those more Regex inclined, it should match the following regex:

  • (^[a-zA-Z0-9\-\_\.\,]{0,30}$)

Note: The Admin Portal Dashboard only makes available the top 10 most used actions, It must not contain any user specific or privacy sensitive information.


Check Action on Token Validate

See Development Guide - Validate Token for complete documentation on how to validate the VerifiedToken.

The tokeninfo.action field from a successful CheckToken API response (JSON Object) will contain the action string the captcha was initialized with. For improved security this action string should be checked for expected value.

{
  "success": true,
  "tokeninfo": {
    ...
    "action": "login",      // the action this captcha was initialized with 
    ...
  }
}

JavaScript Callbacks

The MTCaptcha widget supports the following callbacks

Callback Description
jsloaded-callback The MTCaptcha JavaScript library has loaded
rendered-callback The MTCaptcha widget is rendered (made visible). This may not be called if captcha is kept invisible via the use of Low Friction or IP Whitelist invisible captcha in site settings.
verified-callback The user has been verified. A verifiedToken will always be available on callback.
verifyexpired-callback The last verifiedToken has expired.
error-callback Some kind of error has occured, such as bad sitekey, or internet connection lost.

To enable callbacks, us the following pattern and config params .

<script>
  function mt_jsloadedcb()
  {
    console.log("mt_jsloadedcb()");
  }
    
  function mt_renderedcb(state)
  {
    console.log("mt_renderedcb(state)");
    console.log("state => "+JSON.stringify(state));
  }
  function mt_verifiedcb(state)
  {
    console.log("mt_verifiedcb(state)");
    console.log("state => "+JSON.stringify(state));
  }  
  function mt_verifyexpiredcb(state)
  {
    console.log("mt_verifyexpiredcb(state)");
    console.log("state => "+JSON.stringify(state));
  }    
  function mt_errorcb(state)
  {
    console.log("mt_errorcb(state)");
    console.log("state => "+JSON.stringify(state));
  }   
</script>

<script>
  var mtcaptchaConfig = {
  "sitekey": "<YOUR SITEKEY>",
    
  "jsloaded-callback": "mt_jsloadedcb",
  "rendered-callback": "mt_renderedcb",
  "verified-callback": "mt_verifiedcb",
  "verifyexpired-callback": "mt_verifyexpiredcb",
  "error-callback": "mt_errorcb"
  };
   ...
</script>

The callback config params also support javascript function as value. eg:

<script>
  var mtcb = {};
  mtcb.jsloaded = function(){
    console.log("mtcb.jsloaded()");
  }
</script>

<script>
  var mtcaptchaConfig = {
  "sitekey": "<YOUR SITEKEY>",
  "jsloaded-callback": mtcb.jsloaded
  };
  ...
</script>    

The Callback State Argument & Fields

All callbacks that contains a ‘state’ argument has the following properties. eg

<script>
function mt_renderedcb(state)
{
  console.log("state => "+JSON.stringify(state));
}
</script>

/*
output in console:

state => 
{  
   "element": <element>,
   "domID":"mtcaptcha",
   "verifiedToken":null,
   "isVerified":false,
   "isVisible": true,
   "statusCode":2200,     
   "statusDesc":"Captcha rendered"
}
*/


The callback state argument fields explained

State Field Description
element The MTCaptcha DIV anchor DOM element.
domID The dom ID of the MTCaptcha DIV anchor DOM element.
verifiedToken The verifiedToken string. null if not verified.
isVerified Boolean indicating if the captcha is currently verified. If true, field verifiedToken will contain the token string.
isVisible Boolean indicating if the captcha is currently visible. See Developers Guide - Invisible Captcha to learn more about invisible captcha settings.
statusCode The current status of the captcha
statusDesc The current status of the captcha in description.




MTCaptcha Javascript APIs

A window.mtcaptcha object will be created once the MTCaptcha javascript library has loaded. This mtcaptcha object supports the following APIs.

API Description
enableTestMode ( ) To enable Automated Test mode with the TestKey. For more details see Developers Guide - Automated Testing
getConfiguration ( )
Returns a copy of the configuration object for the captcha. This is primarily used for debugging config settings.
getStatus ( ) Returns the current state of the captcha. For more details of the state object, see Developers Guide - JS Callbacks - State Argument
getVerifiedToken ( ) Returns the current verifiedToken string, null if not verified.
renderUI ( ) Explicit call to render the captcha, when initialized with config render='explicit'. See Developers Guide - Explicit Render for asynchronous safe method explicitly render the widget.
resetUI ( ) Resets the widget and all its state.
showMandatory ( ) Shows the message and styling to indicate the captcha is mandatory. This is intended for use with custom form validation. See Developers Guide - Auto Form Validate to have the captcha automatically check and enforce completion on form submit.

ExplicitLY Render MTCaptcha

MTCaptcha widget will automatically render on load as default behavior. To explicitly control when the widget is rendered.

Use the ‘render’ and ‘renderQueue’ javascript config params.

<script>
  var mtcaptchaConfig = {
      "sitekey": "<YOUR SITE KEY>",
      "render": "explicit",     // or "auto"
      "renderQueue": []
   }
   ...
</script>
...
<div id="someMTCaptchaID"></div>

...
<script>
   //Explict MTCaptcha (async) call to initialize and render captcha widget 
   mtcaptchaConfig.renderQueue.push("someMTCaptchaID");
</script>

Asynchronous JavaScript Load

The explicit render call via the config queue push() is async safe,

mtcaptchaConfig.renderQueue.push("<targetDivID>")

The captcha widget will render as soon as possible after the queue push, whether the MTCaptcha javascript library has loaded or not at the time of invocation.

Timing of target DIV IN DOM

The MTCaptcha will only look for the target DIV (with id=’<targetDivID>’) after call of mtcaptchaConfig.renderQueue.push().

Invisible Captcha

Invisible Captcha is where no visible captcha is shown while a verifiedToken is still created by the MTCaptcha widget as proof of verification.

MTCaptcha currently supports 2 types of Invisible Captcha:

  • Low Friction Invisible Captcha

    Where the user is only shown a captcha if MTCaptcha’s Risk Engine evaluates the user/request to be of risk. Most real users can proceed without solving any captcha challenge. In this scenario the captcha may or may not be visible for any user at any given time.

    Low Friction Invisible Captcha can be enabled per site using the Admin Portal > Sites Module, it can not be enabled or disabled from browser side via JavaScript configuration.


  • IP Whitelist Invisible Captcha

    Where users will not see any visible captcha if they visit from an internet IP address that matches the IP White list configured for the site. In this scenario all users within these IPs whitelisted will never see captcha.

    IP Whitelist Invisible Captcha can be enabled per site using the Admin Portal > Sites Module, it can not be enabled or disabled from browser side via JavaScript configuration.

Invisible Captcha and JS Callbacks

See Developers Guide - JS Callbacks for complete documentation on supported callbacks.

The standard callback sequence of a visible captcha is usually in the sequence

jsloaded > rendered > verified (standard sequence)

In situations where the captcha is invisible, ‘rendered’ callback would be skipped.

jsloaded > verified (invisible sequence)

Under conditions where the initial (invisible) verifiedToken expires, you may see

jsloaded > verified > verifyexpired > verified (invisible sequence with expiration)
jsloaded > verified > verifyexpired > rendered > verified (invisible expired to visible)


How to check if current Captcha is visible

The javascript object state.isVisible (boolean) field indicates if the captcha is currently visible or invisible.

The state object can be found in


How to check a VerifiedToken is The result of Invisible Captcha

The tokeninfo.code and tokeninfo.codeDesc from the CheckToken API response can provide information on how the token was verified.

Specifically tokeninfo.code

  • 211 is verified via IP Whitelist

  • 212 is verified via Low Friction

See Developers Guide - Validate Token for more information on CheckToken API and response.

Automated Testing via TestKey

MTCaptcha supports automated browser UI/UX testing via tools like Selenium, without having to disable the captcha plugin.

mtcaptcha-auto-test-screenshot.png

There are two methods to enable automation test scripts to consistently solve the captcha:

Method 1:

  • Call javascript function mtcaptcha.enableTestMode with the TestKey, once the MTCaptcha plugin is loaded. eg:

 
<script>
  mtcaptcha.enableTestMode(<TestKey>); 
</script>
  • Than enter the text ‘11111111’ into the captcha widget text form

    (entering any other string eg ‘22222222’ will result in verification failure)

Method 2:

  • Set the <TestKey> via the ‘enableTestMode javascript config param

 
<script>
   var mtcaptchaConfig = {
         “sitekey”:           <SiteKey>,
         “enableTestMode” :   <TestKey>
   };
   ...
</script>
  • Then enter the text ‘11111111’ into the captcha widget text form

    (entering any other string eg ‘22222222’ will result in verification failure)



Where Can I Find The TestKey

The TestKey for each site can be found in the Admin Portal along with the SiteKey and PrivateKey. Usually with the prefix ‘MTPrivQA-’. Note: The TestKey should be kept secret.


Check if VerifiedToken is Result of Automated Testing

The captcha will create a VerifiedToken once solved using a TestKey, the same as if a user solved the captcha manually.

To check if a VerifiedToken is the result of using the TestKey, the decoded token information (JSON) will have the corresponding TokenInfo.code of 301 and codeDesc ‘valid-test:captcha-solved-via-testkey’. CheckToken API Response:

{
  "success": true,
  "tokeninfo": {
    "code": 301,
    "codeDesc": "valid-test:captcha-solved-via-testkey",
    ...
  }
}

See our Developers Guide - Validate Token - for more information on VerifiedToken, CheckToken API, and TokenInfo Codes

NOTE:

The purpose of this feature is to support automated unit tests for user interface and interactions. It is not intended to support long running load or performance tests. The captcha may temporarily block test server IP(s) is loaded for long periods of time.

REFERENCES

Stack Overflow: How to call a JavaScript function from within Selenium

Stack Overflow: Selenium : Call javascript function on page.

Custom Style

MTCaptcha supports full customization of style and color to match the look and feel of your website. This can be done via pre-defined themes as well as detailed style settings, using the javascript initialization config object.

For specifics on how to do this, please see the Code Builder, Custom Style tab.

mtcaptcha-custom-theme-examples.png
mtcaptcha-custom-css-styles-code-builder.png

Customize Text Messages and Localization

MTCaptcha supports localization (internationalization) for different languages out of the box, as well as customization of specific messages. Both can be done using JavaScript via the initialization config object.

For specifics on how to do this, please see the Code Builder, Custom Language tab.

custom-language.png

Multiple Captcha Per Web Page

MTCaptcha widget supports the user of multiple captcha per webpage.

To render more than one captcha, use the ‘renderQueue’ javascript config param

<script>
var mtcaptchaConfig = {
  "sitekey": "<YOUR SITE KEY>",
  "renderQueue": ['mtcaptcha-1', 'mtcaptcha-2', 'mtcaptcha-3']
}
...
</script>

<div id="mtcaptcha-1"></div>
<div id="mtcaptcha-2"></div>
<div id="mtcaptcha-3"></div>

MTCaptcha APIs and Multiple Captchas

All window.mtcaptcha javascript APIs supports domID as param to target individual captchas loaded on the page.

<script>
  // get the status of the first captcha
  mtcaptcha.getStatus();      
  // get the status of the captcha with id='mtcaptcha-1'
  mtcaptcha.getStatus('mtcaptcha-1')  
  
  
  // get the current verifiedToken of the first captcha
  mtcaptcha.getVerifiedToken();
  // get the current verifiedToken of the captcha with id='mtcaptcha-2'
  mtcaptcha.getVerifiedToken('mtcaptcha-2');
</script>

To learn more about all the mtcaptcha APIs see Developers Guide - Javascript APIs



Custom Configuration per Captcha

Configuration can be customized per captcha instance by using the element ‘data-<configparam>’ attributes in the target DIV.

<script>
var mtcaptchaConfig = {
  "renderQueue": ['mtcaptcha-1', 'mtcaptcha-2']
}
...
</script>

<div id="mtcaptcha-1" data-sitekey='<sitekey1>' data-action='login' data-lang='zh'></div>
...
<div id="mtcaptcha-2" data-sitekey='<sitekey2>' data-action='register' data-lang='fr'></div>



Multiple Captcha and Callbacks

MTCaptcha JavaScript callbacks provides an argument with field state.domID to indicate specifically which captcha instance the callback is for.

<script>
  function mt_verifiedcb(state)
  {
    console.log("mt_verifiedcb(state)");
    console.log("state.domID => "+state.domID);  // either 'mtcaptcha-1' or 'mtcaptcha-2'
  }  
</script>

<script>
  var mtcaptchaConfig = {
  "sitekey": "<YOUR SITEKEY>",
  "verified-callback": "mt_verifiedcb",
  "renderQueue": ['mtcaptcha-1', 'mtcaptcha-2']
  };
   ...
</script>
...

<div id="mtcaptcha-1"></div>
<div id="mtcaptcha-2"></div>

To learn more about the different callbacks see Developers Guide - JS Callbacks