<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Web Frontend Integration Example</title><!-- Captcha program dependency (required). Do not modify the following program dependencies. If loading is evaded by other means, the captcha may not update properly, its anti-attack capability cannot be guaranteed, and misinterception may even occur. --><script src="https://ca.turing.captcha.qcloud.com/TJNCaptcha-global.js"></script></head><body><div id="cap_iframe"></div><button id="CaptchaId" type="button">Verification</button></body><script>// Define a callback functionfunction callback(res) {// The first parameter is the callback result, as shown below:// ret Int Verification result, 0: Verification successful. 2: User actively closes the Captcha.// ticket String The invoice for successful validation, which has a value only when ret = 0.// CaptchaAppId String Captcha application ID.// bizState Any Custom pass-through parameters.// randstr String Random string for this verification, which needs to be passed during subsequent invoice verification.console.log('callback:', res);// res (user actively turns off Captcha) = {ret: 2, ticket: null}// res (successfully validated) = {ret: 0, ticket: "String", randstr: "String"}// res (error occurred when requesting Captcha, and a disaster recovery ticket with the prefix "terror_" is automatically returned) = {ret: 0, ticket: "String", randstr: "String", errorCode: Number, errorMessage: "String"}// This code is only an example of showing the verification result. For real business integration, it is recommended to handle different businesses based on the ticket and errorCode situations.if (res.ret === 0) {// Copy the result to the clipboardvar str = '[randstr]->[' + res.randstr + '] [ticket]->[' + res.ticket + ']';var ipt = document.createElement('input');ipt.value = str;document.body.appendChild(ipt);ipt.select();document.execCommand("Copy");document.body.removeChild(ipt);alert('1. The return result (randstr, ticket) has been copied to the clipboard, press ctrl+v to view.\\n2. Open the browser console to view the full return result.');}}// Define Captcha JS loading error handling functionfunction loadErrorCallback() {var appid = 'CaptchaAppId';// Generate disaster recovery tickets or perform other processing as neededvar ticket = 'terror_1001_' + appid + '_' + Math.floor(new Date().getTime() / 1000);callback({ret: 0,randstr: '@'+ Math.random().toString(36).substr(2),ticket,errorCode: 1001,errorMessage: 'jsload_error',});}// Define Captcha trigger eventwindow.onload = function(){document.getElementById('CaptchaId').onclick = function(){try {// Generate a Captcha object// CaptchaAppId: Log in to the Captcha console and view it from the [Verification management] page. If no verification has been created, please create one first.//callback: Defined callback function`var captcha = new TencentCaptcha(document.getElementById('cap_iframe'), 'Your CaptchaAppId', callback, {});`// Calling method to display the Captchacaptcha.show();} catch (error) {// Loading exception, call Captcha JS loading error handling functionloadErrorCallback();}}}</script></html>
<!-- Example of Dynamically Importing Captcha JS --><script src="https://ca.turing.captcha.qcloud.com/TJNCaptcha-global.js"></script>
TencentCaptcha
class will be globally registered. The business side can use this class to initialize the captcha by itself and display or hide the captcha.id="TencentCaptcha"
. TencentCaptcha is a system default id and cannot be used. new TencentCaptcha(DOM, CaptchaAppId, callback, options);
Parameter Name | Value Type | Description |
DOM | Element Nodes | Container that handles the Robot checkbox. |
CaptchaAppId | String | CaptchaAppId: Log in to the Captcha Console, and view it on the Verification Management page. If no verification has been created, please create one first. Note: Do not use CaptchaAppId with the client type of mini program, as it may lead to data statistics errors. |
callback | Function | |
options | Object | Captcha appearance configuration parameters. For details, see options appearance configuration parameters. |
Field Name | Value Type | Description |
ret | Int | Verification result, 0: Verification successful. 2: User actively closes the Captcha. |
ticket | String | The invoice for successful validation, which has a value only when ret = 0. |
CaptchaAppId | String | Captcha Application ID. |
bizState | Any | Custom transparent transmission parameters. |
randstr | String | The random string for this verification, which needs to be passed during subsequent invoice verification. |
errorCode | Number | |
errorMessage | String | Error information. |
ErrorCode | Description |
1001 | Loading error of TJNCaptcha - global.js. |
1002 | Call to the show method times out. |
1003 | Loading timeout of intermediate JS |
1004 | Loading error of intermediate JS. |
1005 | Execution error of intermediate JS |
1006 | Pull Captcha configuration error/timeout |
1007 | Iframe loading timeout |
1008 | Iframe loading error |
1009 | Loading error of jQuery. |
1010 | Loading error of slider JS. |
1011 | Slider JS execution error |
1012 | Refresh three consecutive errors |
1013 | Network verification failed three consecutive times. |
transform:scale();
with the element of class=tcaptcha-transform
at the outermost layer of the popup. The update of the Captcha may change the attributes such as the id and class of the element. Do not rely on the attribute values of other Captcha elements to override the style.Configuration Name | Value Type | Description |
bizState | Any | Custom pass-through parameters. The business can use this field to transmit a small amount of data, and the content of this field will be carried into the object of the callback. |
enableDarkMode | Boolean/String | Enable adaptive late-night mode or force late-night mode. Enable adaptive late-night mode: {"enableDarkMode": true} Force late-night mode: {"enableDarkMode": 'force'} |
ready | Function | The callback when the Captcha loading is completed, and the callback parameter is the actual width and height of the Captcha: {"sdkView": {<br>"width": number,<br>"height": number<br>}} This parameter is only used for viewing the width and height of the Captcha, please do not use this parameter to directly set the width and height. |
needFeedBack | String | Custom help link: {"needFeedBack": 'URL address'} |
enableAutoCheck | Boolean | After it is enabled, the verification can be automatically checked for secure requests without user operation, and it is closed by default. Enable: {"enableAutoCheck": true} |
userLanguage | String | Specify the language of the Captcha prompt text, which has a higher priority than the console configuration. Supports input values the same as navigator.language user preferred language, case-insensitive. |
type | String | Define the Captcha display method. Popup (default): The Captcha is displayed in a floating layer that pops up and centers. Embed: Display the Captcha by embedding it into a specified container element. |
aidEncrypted | String | CaptchaAppId encrypted verification string, optional parameter. For details, see CaptchaAppid Encryption Verification Capability Integration Guide. |
showFn | Function | Duration of rendering time + SID callback function. |
Parameter Name | Description |
zh-cn | Simplified Chinese |
zh-hk | Traditional Chinese (Hong Kong (China)) |
zh-tw | Traditional Chinese (Taiwan (China)) |
en | English |
ar | Arabic |
my | Burmese |
fr | French |
de | German |
he | Hebrew |
hi | Hindi |
id | Indonesian |
it | Italian |
ja | Japanese |
ko | Korean |
lo | Lao |
ms | Malay |
pl | Polish |
pt | Portuguese |
ru | Russian |
es | Spanish |
th | Thai |
tr | Turkish |
vi | Vietnamese |
Method Name | Description | Input Parameter | Returned Content |
show | Display the Captcha, which can be called repeatedly. | No | No |
destroy | Hide the Captcha, which can be called repeatedly. | No | No |
getTicket | Obtain the ticket after successful verification. | No | Object:{"CaptchaAppId":"","ticket":""} |
reload | Reinitialize the checkbox, which can be called repeatedly. | No | No |
// Function of the error handling function: Ensure the normal event process when JS loading or initialization errors occur.// Function definition needs to be before script loadingfunction loadErrorCallback() {var appid = ''// Generate disaster recovery tickets or handle other tasks as neededvar ticket = 'terror_1001_' + appid + Math.floor(new Date().getTime() / 1000);callback({ret: 0,randstr: '@'+ Math.random().toString(36).substr(2),ticket,errorCode: 1001,errorMessage: 'jsload_error',});}
try {// Generate a Captcha object`var captcha = new TencentCaptcha(document.getElementById('cap_iframe'), 'Your CaptchaAppId', callback, {});`// Calling method to display the Captchacaptcha.show();} catch (error) {// Loading exception, call Captcha JS loading error handling functionloadErrorCallback();}
function callback(res) {// res (user actively turns off Captcha) = {ret: 2, ticket: null}// res (successfully validated) = {ret: 0, ticket: "String", randstr: "String"}// res (request error, returning a disaster recovery ticket with the prefix "terror_") = {ret: 0, ticket: "String", randstr: "String", errorCode: Number, errorMessage: "String"}if (res.ticket){// Perform special handling based on the errorCode situationif(res.errorCode === xxxxx){//Customize disaster recovery logic (for example, skip this verification)}}}
Type | Sample Value |
Captchaappid | 123456789 |
Timestamp | 1710144972 |
Expiration Time | 86,400 sec |
iv | 0123456789012345 |
AppSecretKey | 1234567891011121314151516 |
Recursively filled key | 12345678910111213141515161234567 |
Encrypted business data object. | 123456789&1710144972&86400 |
The final encrypted string aidEncrypted | MDEyMzQ1Njc4OTAxMjM0NWvZ11atw+1uzYmoIyt5rAQVPyMK9ZDavskPw5hcayeT |
#!/usr/bin/env python# -*- coding: utf-8 -*-from Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadimport base64import timedef encrypt(plaintext, key, iv):cipher = AES.new(key, AES.MODE_CBC, iv) # Create a new AES cipher in CBC modeciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size)) # Pad the data and then encrypt it. pad(plaintext.encode(), AES.block_size) checks whether the plaintext length is a multiple of 16 bytes. If not, it will pad the plaintext to a multiple of 16 bytes using the PKCS7 padding method.ciphertextBase64 = base64.b64encode(iv + ciphertext).decode('utf-8') # Concatenate iv with the encrypted data and perform Base64 encoding before transmission.return ciphertextBase64# Example of EncryptionAppSecretKey = b'1234567891011121314151516' # The customer obtains the AppSecretKey under the corresponding Captcha account from the console, 25 characters.remainder = 32 % len(AppSecretKey) # Calculate the key length to be supplementedkey = AppSecretKey + AppSecretKey[:remainder] # Final encryption key, padded to 32 bits.CaptchaAppId = "123456789" # Customer's own Captcha application IDcurTime = 1710144972 # Obtain the current timestamp; for the example, it is temporarily set to a fixed timestamp. The customer should set it to the latest timestamp, using int(time.time())expireTime = 86400 # Expiration time setting, temporarily set to this value here, the customer should set it according to their needs.plaintext = CaptchaAppId + "&" + str(curTime) + "&" + str(expireTime) # Concatenate the business data object to be encrypted, CaptchaAppId & timestamp & Encrypted Text Expiry Timeiv = "0123456789012345".encode() # Randomly generate a 16-byte IV; for now, it is set to this value. Customers should use randomly generated data, using os.urandom(16)ciphertext = encrypt(plaintext, key, iv) # Encryptprint("Ciphertext (Base64):", ciphertext) # The sample data in this example will output MDEyMzQ1Njc4OTAxMjM0NWvZ11atw+1uzYmoIyt5rAQVPyMK9ZDavskPw5hcayeT
const encryptAppid = async () => {/** Get the encrypted appid string from the backend */const { aidEncrypted } = await fetch('/api/encryptAppid');/** Callback function */const callBack = (ret) => {console.log('ret', ret);};/** Error Callback Function */const errorCb = (error) => {console.log('error', error);};try {/** Pass the obtained encrypted string to the aidEncrypted parameter */const captcha = new TencentCaptcha('123456789', callBack, { aidEncrypted: aidEncrypted });captcha.show();} catch (error) {errorCb(error);}};