Play Tencent slider verification code from zero

Posted by wiley on Wed, 19 Jan 2022 09:35:26 +0100

Play Tencent slider verification code from zero

At present, the front end of most companies use slider verification codes to verify robot behavior, and the back end also has them, but almost all of them are graphic verification codes or mobile phone verification codes, which directly enter the theme. The next technology we want to play with is the slider verification code produced by Tencent cloud (you can receive more than 5W free times for free, and the validity period is one year)

Show Time:

Step 1: enter Tencent cloud official website

https://console.cloud.tencent.com/captcha/graphical

1. Clicking the graphic verification code may need to be opened. Clicking to receive the free package will give you the number of times to use the verification code, which can be viewed in the package management.

2. Click Add verification

3. Fill in information

3.0 after new creation, you can view the verification code CaptchaAppId and AppSecretKey in the verification list

3.1 access to official documents

https://cloud.tencent.com/document/product/1110/36839

3.2 we will see a fast access. The first step is to obtain our own Tencent cloud key

3.3 copy the key yourself first

APPID: xxxxxxxxxxxxxxxxxxx

SecretId: xxxxxxxxxxxxxxxxxxxxxxxxxxxx

SecretKey: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Step 2: create a front-end page

<!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>Yang is not easy-Web Front end access example</title>
  <!-- Verification code program dependency(must) -->
  <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
</head>
<body>
  <!--Clicking this element will automatically activate the verification code, This example uses button element, You can also use div,span etc.-->
  <!--id :            (Immutable) Elemental ID, Value must be 'TencentCaptcha'-->
  <!--data-appid :    (must) Verification Code CaptchaAppId, Get the verification code from Tencent cloud's verification code console, [graphic verification] on the verification code console page>[Verification list. If no verification is created, please select the appropriate verification channel and verification scenario according to the business needs-->
  <!--data-cbfn :     (must) Callback function name, The function name should be the same as data-cbfn identical-->
  <!--data-biz-state :(Optional) Business custom transparent parameters, It will be obtained in the callback function( res.bizState)-->
  <button id="TencentCaptcha" data-appid="Your verification code CaptchaAppId" data-cbfn="callbackName" data-biz-state="data-biz-state"
      type="button">verification</button>
</body>
<script>
  // The callback function needs to be placed under the global object window
  window.callbackName = function (res) {
      // Return results
      // RET int validation result, 0: validation succeeded. 2: The user actively turns off the verification code.
      // Ticket string the ticket that has been verified successfully. If and only if ret = 0, the ticket has a value.
      // Captchaappid string verification code application ID.
      // Bizstate any custom transparent parameters.
      // Randstr string the random string of this verification, which needs to be brought when requesting the background interface.
      console.log('callback:', res);

      // res (user actively closes verification code) = {ret: 2, ticket: null}
      // res (successful verification) = {ret: 0, ticket: "String", randstr: "String"}
      if (res.ret === 0) {
          // Copy results to clipboard
          let str = `[randstr]->[${res.randstr}]      [ticket]->[${res.ticket}]`;
          let ipt = document.createElement('input');
          ipt.value = str;
          document.body.appendChild(ipt);
          ipt.select();
          document.execCommand("Copy");
          document.body.removeChild(ipt);
          alert('1. Return results( randstr,ticket)Copied to the clipboard, ctrl+v see.\n2. Open the browser console to view the complete returned results.');
        }
  }
</script>
</html>

1. Write the verification code CaptchaAppId and get it from the verification code console of Tencent cloud. View the verification code in [graphic verification] > [verification list] on the verification code console page

<button id="TencentCaptcha" data-appid="2071484082" data-cbfn="callbackName" data-biz-state="data-biz-state"  type="button">verification</button>

2. Open the page to view the effect

3. Slide the slider to the end point for calibration

// Return results
// RET int validation result, 0: validation succeeded. 2: The user actively turns off the verification code.
// Ticket string the ticket that has been verified successfully. If and only if ret = 0, the ticket has a value.
// Captchaappid string verification code application ID.
// Bizstate any custom transparent parameters.
// Randstr string the random string of this verification, which needs to be brought when requesting the background interface.

[randstr]>[@uKe]
[ticket]>[t03vNwGSyE5PYZpSALqZsjsr7M5Z8lzRMhzgC7UExz7_DSmmxq_B1iLBB_VYhxp76wY5jQXVOdq_K2Ye8jjx7XiDSRmDAT3sJAME9NUlgxqQoyVOyDpdOUjbA**]

4. Then Tencent verification code access has been completed. Next, we will verify the connection with the back end

Step 3: create describecaptcharesult Maven backend project

1. Add dependency

    <dependencies>
        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java</artifactId>
            <!-- go to https://search.maven.org/search?q=tencentcloud-sdk-java and get the latest version. -->
            <!-- succeed in inviting sb. https://search. maven. org/search? Q = tencentcloud SDK Java query all versions. The latest version is as follows -- >
            <version>3.1.217</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>nexus-tencentyun</id>
            <name>Nexus tencentyun</name>
            <url>https://mirrors.tencent.com/nexus/repository/maven-public/</url>
        </repository>
    </repositories>

2. Create the tool class DescribeCaptchaResultUtils

public class TencentCaptchaUtils {
	/**
	 * Verification of Tencent verification code
	 * @param randStr The random string returned by the front-end callback function
	 * @param token(Ticket)   User authentication ticket returned by the front-end callback function 
	 * @return
	 */
	public static boolean tencentCaptcha(String randStr, String token) {
		try {
			/*
			Action	yes 	 String 	 Public parameter, value of this interface: DescribeCaptchaResult.
			Version	yes 	 String 	 Public parameter, value of this interface: July 22, 2019.
			Region	no 	 String 	 Public parameter. This interface does not need to pass this parameter.
			CaptchaType	yes 	 Integer 	 Fixed filling value: 9. Different verification code types can be configured on the console.
			Ticket	yes 	 String 	 User authentication ticket returned by the front-end callback function
			UserIp	yes 	 String 	 The IP of the verification code user obtained from the transparent service side
			Randstr	yes 	 String 	 The random string returned by the front-end callback function
			CaptchaAppId	yes 	 Integer 	 Verification code application ID
			AppSecretKey	yes 	 String 	 The verification key used to verify the verification code ticket on the server side should be kept confidential and should not be disclosed to a third party
			BusinessId	no 	 Integer 	 Business ID, a website or application uses this service in multiple businesses, and statistics are distinguished by this ID
			SceneId	no 	 Integer 	 Scenario ID: there are multiple scenarios using this service under the business of the website or application. Statistics are distinguished by this ID
			MacAddress	no 	 String 	 mac address or unique device ID
			Imei	no 	 String 	 Mobile device number
			NeedGetCaptchaTime	no 	 Integer 	 Whether to return the time when the front end obtains the verification code. Value 1: it needs to be returned
			* */
			Credential cred = new Credential("Your Tencent cloud key", "Your Tencent cloud key");

			HttpProfile httpProfile = new HttpProfile();
			httpProfile.setEndpoint("captcha.tencentcloudapi.com");

			ClientProfile clientProfile = new ClientProfile();
			clientProfile.setHttpProfile(httpProfile);

			CaptchaClient client = new CaptchaClient(cred, "", clientProfile);
			DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
			// 	Fixed filling value: 9. Different verification code types can be configured on the console
			req.setCaptchaType(9L);
			// 	User authentication ticket returned by the front-end callback function
			req.setTicket(token);
			// Please obtain the ip address of the requester through the service by transmitting the ip of the verification code user obtained by the service side
			req.setUserIp("127.0.0.1");
			// The random string returned by the front-end callback function
			req.setRandstr(randStr);
			// Verification code application ID
			req.setCaptchaAppId(You added verified CaptchaAppId);
			// The verification key used to verify the verification code ticket on the server side should be kept confidential and should not be disclosed to a third party
			req.setAppSecretKey("You added a new authentication key AppSecretKey");
			// Whether to return the time when the front end obtains the verification code. Value 1: it needs to be returned
			req.setNeedGetCaptchaTime(1L);
			// Scenario ID: there are multiple scenarios using this service under the business of the website or application. Statistics are distinguished by this ID
			req.setSceneId(1L);
			DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
			Gson gson = new Gson().newBuilder().create();
			Map map = gson.fromJson(DescribeCaptchaResultResponse.toJsonString(resp), Map.class);
			System.out.println(map);
			if ("ok".equalsIgnoreCase(map.get("CaptchaMsg").toString())){
				// success
				return true;
			} else {
				return false;
			}
		} catch (TencentCloudSDKException e) {
			System.out.println(e.toString());
			return false;
		}
	}
	/**
	verification
	*/
	public static void main(String[] args) {
				boolean b = tencentCaptcha("@UP0", "t03cnXnT-SNq8jywYVz4h22VFkNbQxXiShmEomvQRUAXaF9UWJBkLWDyCqZcONCjlYAC3-ytSkQ2IJtrG7xNJwfvvyD-QxgnNL0iSSkXyXGd3ePHFfLI_8FfA**", null);
		System.out.println(b);
	}

}

3. Start synchronous verification with the front end

4. Verification succeeded ok

Use VUE to access Tencent slider

1. Copy the slider js to the global html page

2. Write display slider method

tencentCaptcha() {
      const captchaId = 'Yours appid' // Tencent slider verification code appid
      // Generate a slider verification code object
      const _this = this// Processing here is because calling the slider verification code verification method fails
      // eslint-disable-next-line no-undef
      var captcha = new TencentCaptcha(captchaId,
        function(res) {
          // Background verification method
          _this.handleLoginMe(res)// Verification of graphic verification code
        })
      // Slider display
      captcha.show()
}

3. Call the backend interface tool class verification method to pass two parameters

 handleLoginMe(res) {
      // Back end verification parameters ()
      this.loginForm.params.randStr = res.randstr
      this.loginForm.params.token = res.ticket
      // Start login request
      this.$store.dispatch('user/login', this.loginForm).then(() => {
       	// Your business logic
      }).catch(() => {
      })
    }

2. The backend login logic is used in conjunction with the DescribeCaptchaResultUtils tool class created earlier

Wuhu slipped away