Short message service

The SMS verification code service is mainly used for mobile phone number + verification code login, registration, mobile phone number binding, and password change. This project takes the SMS verification code service as a public service and realizes two interfaces: creating and sending verification codes and checking verification codes. Use of ali cloud SMS service dysms.console.aliyun.com/ implementation.

The premise to prepare

Register SMS signature and SMS template on Aliyun’S SMS service.

Create AliYun AccessKey

The specific implementation

Ali cloud SMS service is relatively simple to use, just call the corresponding interface and bring parameters.

    /** * The specific logic for sending SMS verification codes **@paramPhone Mobile number *@paramAuthCode Indicates the verification code *@returnSend the result */
    private Result<Void> sendSmsAuthCode(String phone, String authCode) {
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId"."cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", sign here); request.putQueryParameter("TemplateCode", fill in template number); request.putQueryParameter("TemplateParam"."{\"code\":\"" + authCode + "\"}");
        try {
            client.getCommonResponse(request);
            return Result.success();
        } catch (ClientException e) {
            logger.warn("Send sms auth code fail");
            return Result.fail(ErrorCode.INTERNAL_ERROR, "Send sms auth code fail."); }}Copy the code

Add aliyun SMS service dependency.

<! -- Aliyunku -->  
<dependency>  
	<groupId>com.aliyun</groupId>  
	<artifactId>aliyun-java-sdk-core</artifactId>  
</dependency>  
Copy the code

Service encapsulation

In order to make it easier to use the verification code function, the SMS service of Ali Cloud is further encapsulated. To create and send verification code and check verification code two methods.

Create and send the captcha method implementation

Here a random 6-bit verification code is generated, sent to the phone, and added to the Redis cache.

    /** * Send SMS verification code service * this service caches the SMS verification code **@paramSmsAuthCodeDTO SMS verification code object *@returnResult<Void> Return Result If result.issuccess () is true, the message is sent successfully; otherwise, the message fails */
    @Override
    public Result<Void> createAndSendSmsAuthCode(SmsAuthCodeDTO smsAuthCodeDTO) {
        // Send the VERIFICATION code to the mobile phone
        String authCode = AuthCodeUtils.randomAuthCode();
        Result<Void> sendSmsAuthCodeResult = sendSmsAuthCode(smsAuthCodeDTO.getPhone(), authCode);
        if(! sendSmsAuthCodeResult.isSuccess()) {return sendSmsAuthCodeResult;
        }

        // Add the SMS verification code to the cache
        String redisKey = SMS_AUTH_CODE_REDIS_PREFIX
                + ":" + smsAuthCodeDTO.getSubject() + ":" + smsAuthCodeDTO.getPhone();
        redisTemplate.opsForValue().set(redisKey, authCode, smsAuthCodeDTO.getExpiredTime(), TimeUnit.MINUTES);

        return Result.success();
    }
Copy the code

Check the verification code method implementation

This method is mainly used to verify the use of captcha. First take out the corresponding verification code from Redis, and then determine whether the verification code is correct. If the verification succeeds, delete the verification code if you need to delete it.

/** * SMSAuthCodedto. delete == true a verification code can be used only once@paramSmsAuthCodeDTO SMS verification code object *@returnIf result.issuccess () is true, verification succeeds; otherwise, verification fails */
    @Override
    public Result<Void> checkSmsAuthCode(SmsAuthCodeDTO smsAuthCodeDTO) {
        // Fetch the captcha from the cache
        String redisKey = SMS_AUTH_CODE_REDIS_PREFIX
                + ":" + smsAuthCodeDTO.getSubject() + ":" + smsAuthCodeDTO.getPhone();
        String authCode = (String) redisTemplate.opsForValue().get(redisKey);

        // The verification code does not exist
        if (authCode == null) {
            return Result.fail(ErrorCode.INVALID_PARAMETER, "Auth code not exists.");
        }

        // The verification code is incorrect
        if(! authCode.equals(smsAuthCodeDTO.getAuthCode())) {return Result.fail(ErrorCode.INVALID_PARAMETER, "Auth code error.");
        }

        // The verification is successful. If the verification code needs to be deleted, delete it
        if (smsAuthCodeDTO.getDelete()) {
            redisTemplate.delete(redisKey);
        }

        return Result.success();
    }
Copy the code

Other code

AuthCodeUtils

Used to generate a verification code.

import org.apache.commons.lang3.RandomStringUtils;

/** * Description: Verification code tools, such as mobile verification code, email verification code **@author: xhsf
 * @create: 2020/11/19 16:08 * /
public class AuthCodeUtils {

    /** * Random verification code in the format of 6 digits *@returnCaptcha * /
    public static String randomAuthCode(a) {
        return RandomStringUtils.randomNumeric(6); }}Copy the code

SmsAuthCodeDTO

SMS verification code data transfer object.

/** * Description: SMS verification code, used to send SMS verification code with information **@author: xhsf
 * @create: 2020/11/19 13:42 * /
public class SmsAuthCodeDTO implements Serializable {
    @NotBlank
    @Phone
    private String phone;

    /** * The topic must be unique to the business and must not conflict, otherwise it is inaccurate ** to be used as a prefix for the key when caching * The recommended format is {service name}:{specific business name} */
    @NotBlank
    private String subject;

    / * * * cache key expiration time, unit minutes * * recommended 5 or 10 minutes in the calling SmsService. CreateAndSendSmsAuthCode () need to take a * /
    @NotNull(groups = SmsService.CreateAndSendSmsAuthCode.class)
    @Positive
    @Max(10)
    private Integer expiredTime;

    / message authentication code * * * * in the calling SmsService. CheckSmsAuthCode () need to take a * /
    @NotBlank(groups = SmsService.CheckSmsAuthCode.class)
    @AuthCode
    private String authCode;

    / * * * * check whether after a successful delete the key in the calling SmsService. CheckSmsAuthCode () need to take a * /
    @NotNull(groups = SmsService.CheckSmsAuthCode.class)
    private Boolean delete;
    
    // getters and setters
}
Copy the code