The Java backend uses Tencent Cloud SMS service to send text messages

It is very common to use the mobile phone verification code to register or proceed to the next step. This article will teach you how to use the Tencent Cloud SMS service to send the mobile phone verification code.

Article directory

1. Preconditions

2. Code implementation

1. Introduce dependencies

2. Java code implementation

3. Code improvement

4. Realize the effect 

3. About sharing verification code verification logic in the project

1. Send the mobile phone verification code and store it in Redis

2. Verification logic


1. Preconditions

 Tencent Cloud official website account, SMS service has been activated

Parameters to be used 1. SMS signature id, (requires review)

2. SMS text signature template, (need to create a review)

3. Application id, (created)

4. There are remaining SMS packages (200 free for new users after activation, which can be purchased)

 The above are the prerequisites that need to be met. Tencent Cloud can also set a limit on the number of entries. Code development needs to use the above parameters. If you don’t know how to get the parameters, you can watch this video https://www.bilibili.com/video/BV1KE411K7Sd

2. Code implementation

1. Introduce dependencies

        <!--腾讯云手机验证码-->
		<dependency>
			<groupId>com.github.qcloudsms</groupId>
			<artifactId>qcloudsms</artifactId>
			<version>1.0.6</version>
		</dependency>

2. Java code implementation

package com.liyingjie.lyjalipay.controller;

import cn.hutool.core.util.RandomUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.liyingjie.lyjalipay.domain.Sms;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class SmsControllerTest {

    @Test
    public void sms(){
        //腾讯云固定参数
        int appid = 1400655460;   //腾讯云应用id
        String appkey="133213";  //腾讯云应用Key
        int templateId= 1354718;  //模板id
        String smsSign="杰杰不会hellowor";  //签名内容

        //可变参数
        String phoneNumber ="123456";//手机号码
        String code="131";//手机验证码
        String min="5";//有效时长
        try {
            String[] params = {code,min}; //param1,手机验证码;param2,有效时长,配合正文模板参数
            SmsSingleSender smsSingleSender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult smsSingleSenderResult = smsSingleSender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");
            System.out.println(smsSingleSenderResult);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (HTTPException | JSONException e) {
            e.printStackTrace();
        }
    }
}

3. Code improvement

package com.liyingjie.lyjalipay.controller;

import cn.hutool.core.util.RandomUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.liyingjie.lyjalipay.domain.Sms;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class SmsControllerTest {

    @Test
    public void sms(){
        //腾讯云固定参数
        int appid = 1400655460; //应用id
        String appkey="76bcf5ddb58******"; //应用Key
        int templateId= 222222;//模板id
        String smsSign="杰杰不会hellowor";

        //用户参数
        Sms sms =new Sms();
        sms.setPhoneNumber("132");
        sms.setCode(RandomUtil.randomNumbers(6));//验证码6位随机
        sms.setMin(5); //验证码有效时长

        try {
            String[] params = {sms.getCode(),Integer.toString(sms.getMin())};
            SmsSingleSender smsSingleSender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult smsSingleSenderResult = smsSingleSender.sendWithParam("86", sms.getPhoneNumber(), templateId, params, smsSign, "", "");
            System.out.println(smsSingleSenderResult);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (HTTPException | JSONException e) {
            e.printStackTrace();
        }
    }
}

4. Realize the effect 

3. About sharing verification code verification logic in the project

Only the verification code is sent above. To realize the verification code verification in the front-end and back-end projects, you can use the redis cache database to achieve

1. Send the mobile phone verification code and store it in Redis

Encapsulate the above sending mobile phone verification code into a method in a tool class SmsUtil. Return a random six-digit verification code

Store the returned verification code in redis, use the mobile phone number as the key, verify the code as the value, and unify the valid time.

    @ApiOperation("发送手机验证码")
    @GetMapping("/send/{phoneNumber}")
    public AjaxResult sendCode(@PathVariable("phoneNumber") String phoneNumber){
        String phoneCode = SmsUtil.send(phoneNumber);
        redisCache.setCacheObject(phoneNumber,phoneCode,5, TimeUnit.MINUTES);
        return AjaxResult.success(phoneCode);
    }

2. Verification logic

After the sending in the previous step is completed, when submitting the form parameters, carry the mobile phone number and verification code parameters,

String redisCode = redisCache.getCacheObject(phoneNumber);
Boolean flag = redisCode.equals(phoneCode)

 Proceed to the next step after the verification is successful, otherwise it will not be executed

Guess you like

Origin blog.csdn.net/liyingjie2001/article/details/126585224