tencent cloud

All product documents
Web Integration
Last updated: 2025-03-25 11:16:49
Web Integration
Last updated: 2025-03-25 11:16:49

Service Process Diagram



Prerequisites

Before client integration, you need to create a new verification and obtain the required CaptchaAppId and AppSecretKey from the Validation List. The steps are as follows:

1. Log in to the Captcha Console, select Verification Management in the left sidebar, and enter the Verification Management page.
2. Click Create Captcha, and set parameters such as verification name according to business scenario needs.
3. Click Yes to complete the creation of a new Captcha, and then you can view the CaptchaAppId and AppSecretKey in the Validation List.
Note:
Starting from December 2024, Captcha will offer two versions of the service. The architecture of the old version's user console remains unchanged, and the user experience is not affected. Customers using the old version who wish to use the new version need to create a new CaptchaAppid to ensure the smooth use of the Captcha feature in the future. If you have any queries, feel free to contact us.

Sample Code

In the following example code, click Verification to activate the Captcha and display the verification result in a pop-up.
Note:
This example does not show the logic of calling the invoice verification API. After the business client completes the Captcha integration, the business server needs to perform a secondary check on the Captcha ticket result (without invoice verification, it will allow the black industry to easily forge verification results, losing the human robot confrontation effect of Captcha). For details, see: Integrate Invoice Verification (Web and App).
<!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 function
function 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 clipboard
var 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 function
function loadErrorCallback() {
var appid = 'CaptchaAppId';
// Generate disaster recovery tickets or perform other processing as needed
var 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 event
window.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 Captcha
captcha.show();
} catch (error) {
// Loading exception, call Captcha JS loading error handling function
loadErrorCallback();
}
}
}
</script>

</html>

Connection Instructions

Step 1: Dynamically Import Captcha JS

The web page needs to dynamically import Captcha JS, and when verification is required, the Captcha is invoked for verification.
<!-- Example of Dynamically Importing Captcha JS -->
<script src="https://ca.turing.captcha.qcloud.com/TJNCaptcha-global.js"></script>
Note:
Captcha JS must be dynamically loaded. If dynamic loading is evaded by other means, the captcha may not update properly, its anti-attack capability cannot be guaranteed, and may even occur.

Step 2: Create a Captcha Object

After introducing Captcha JS, a 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.
Note:
The element that triggers the captcha should not use id="TencentCaptcha". TencentCaptcha is a system default id and cannot be used.

Constructor

new TencentCaptcha(DOM, CaptchaAppId, callback, options);
Parameter Description
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
Captcha callback function. For details, see callback function.
options
Object
Captcha appearance configuration parameters. For details, see options appearance configuration parameters.

Callback Function

After verification, the callback function passed in by the business will be called, and the callback result will be passed in as the first parameter. The fields of the callback result are described as follows:
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
Error code. For details, see callback function error code description.
errorMessage
String
Error information.

Callback Function Error Code Description

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.

Appearance Configuration Parameters For Options

The options parameter is used to customize the appearance settings of the Captcha, which can be set to empty by default.
Note:
The style size inside the Captcha popup cannot be adjusted. If adjustment is needed, you can set 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.
If the mobile phone native end has a left and right swipe gesture setting, it needs to be disabled before calling the Captcha show method and enabled after verification is completed to prevent conflicts with the Captcha swipe event.
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.

userLanguage configuration parameter

The userlanguage parameter can be set to empty, which means it defaults to adapting to the browser language.
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

Step 3: Invoke the Captcha Instance Method

TencentCaptcha instances provide some common methods for operating Captchas:
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

Step 4: Disaster Recovery

To ensure that the customer's website business process is not blocked when the Captcha server-side exception occurs, it is recommended to integrate the Captcha in the following way.
1. Define JS loading error handling function.
// 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 loading
function loadErrorCallback() {
var appid = ''
// Generate disaster recovery tickets or handle other tasks as needed
var 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',
});
}
2. When a Captcha instance catches an error, call the JS loading error handling function.
try {
// Generate a Captcha object
`var captcha = new TencentCaptcha(document.getElementById('cap_iframe'), 'Your CaptchaAppId', callback, {});`
// Calling method to display the Captcha
captcha.show();
} catch (error) {
// Loading exception, call Captcha JS loading error handling function
loadErrorCallback();
}
3. When defining the Captcha callback function, handle it according to the ticket and errorCode (instead of ret). For the definition of errorCode, refer to "Callback Function errorCode Description" in Step 2.
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 situation
if(res.errorCode === xxxxx){
//Customize disaster recovery logic (for example, skip this verification)
}
}
}
Complete disaster recovery solution. For details, see Business Disaster Recovery Solution.
Note:
After the business client completes the Captcha integration, the server needs to perform a secondary check on the Captcha invoice result (without invoice verification, it will be easy for the black industry to forge the verification result, losing the effect of human robot confrontation of Captcha). For details, see Integrate Invoice Verification (Web and App).


CaptchaAppid Encryption Verification Capability Access Guide

By passing an encrypted string through the frontend (optional capability, can be selectively integrated based on security requirements), it can effectively prevent resource fraud caused by the leakage of CaptchaAppid.

Encryption Rules

The API supports passing the verification code business CaptchaAppid in encryption mode for verification through the aidEncrypted parameter (i.e., the encrypted string identifier).
When the console's forced verification is enabled, the encryption mode is triggered. The customer's server encrypts it and sends the corresponding encrypted string to the customer's frontend, which then passes the encrypted string as a parameter to the Captcha side.
The encryption procedure is as follows:
1. Log in to the Captcha Console, in the left sidebar, select Verification Management > Captcha Details, click Integration.
2. On the Manage CAPTCHA page, select the required AppSecretKey as the key. When the key is less than 32 bytes, cycle fill the same AppSecretKey to make up to 32 bytes as the key.



3. Randomly generate a 16-byte IV. Combine the obtained key Key in step 1 to perform AES256 encryption on the business data object. The encryption mode is CBC/PKCS7Padding. The encrypted business data object is the verification code business CaptchaAppid & timestamp & Encrypted Text Expiry Time. The timestamp is the current Unix timestamp at the second level and cannot be a future time. The unit of Encrypted Text Expiry Time is seconds, and the maximum value is 86400 seconds. The encrypted string obtained is CaptchaAppidEncrypted.
4. Perform Base64 encoding on the byte array CaptchaAppidEncrypted obtained by AES256 encryption of IV in step 2, that is, Base64 (IV + CaptchaAppidEncrypted), with no hyphen in the middle, and the final encrypted business parameter request string obtained is aidEncrypted.
5. Regarding the validity time and expiration time of Captcha encryption processing, customers can set them according to their own needs. It should be noted here that the timing mechanism starts when the Captcha begins to load. If the set timing duration is too short, the following situation may occur: After the Captcha is loaded, the user does not perform any operations for a period of time, and when the user performs related operations later, the encryption information corresponding to the Captcha has expired and become invalid.

Example Of Encryption Result

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

Sample Code

Server-side encryption
The encryption rule is: Base64(IV + AES256(CaptchaAppid & timestamp & Encrypted Text Expiry Time, IV, Key)), that is, using a randomly generated 16-byte IV and a 32-byte encryption Key obtained by cyclic filling according to AppSecretKey, using AES256 algorithm encryption mode CBC/PKCS7Padding to encrypt the plaintext data CaptchaAppid & timestamp & Encrypted Text Expiry Time.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
import time


def encrypt(plaintext, key, iv):
cipher = AES.new(key, AES.MODE_CBC, iv) # Create a new AES cipher in CBC mode
ciphertext = 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 Encryption
AppSecretKey = 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 supplemented
key = AppSecretKey + AppSecretKey[:remainder] # Final encryption key, padded to 32 bits.

CaptchaAppId = "123456789" # Customer's own Captcha application ID
curTime = 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 Time

iv = "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) # Encrypt
print("Ciphertext (Base64):", ciphertext) # The sample data in this example will output MDEyMzQ1Njc4OTAxMjM0NWvZ11atw+1uzYmoIyt5rAQVPyMK9ZDavskPw5hcayeT



Frontend Integration Example


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);
}
};

FAQs

For details, see Integration-related Issues.

Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback

Contact Us

Contact our sales team or business advisors to help your business.

Technical Support

Open a ticket if you're looking for further assistance. Our Ticket is 7x24 available.

7x24 Phone Support