当前位置:网站首页>Hazelnut cloud - SMS (tool)

Hazelnut cloud - SMS (tool)

2022-06-26 10:45:00 Slightly drunk CC

One 、 Introduce

Hazelnut cloud document ( Official website SDK)

Two 、 Add dependency

2.1 pom.xml file (SpringBoot project )

<!--  Reliance on hazelnut cloud SMS  -->
<dependency>
	<groupId>com.zhenzikj</groupId>
	<artifactId>zhenzisms</artifactId>
	<version>2.0.2</version>
</dependency>

2.2 Global configuration

# Hazelnut cloud SMS configuration 
zhenzi:
  apiUrl: https://sms_developer.zhenzikj.com # Pay attention to the difference between individual users and enterprise users 
  appId:  Fill in your own APPID
  appSecret:  Fill in your own APPSecret
  templateId:  Fill in your own template id # Templates id
  invalidTimer: 1 # Failure time 1 minute ( Tips )

2.3 Customize the tool class for reading SMS parameters

/** * @Description * @Author cb * @Date 2021-11-25 10:06 **/
@Component
@ConfigurationProperties(prefix = "zhenzi")
public class ZhenZiYunSMSUtils {
    

    private String apiUrl;          //apiUrl
    private String appId;           // application id
    private String appSecret;       // application secret
    private String templateId;      // Templates id
    private String invalidTimer;    // Failure time 

    /** *  Send SMS verification code  * * @param telNumber  Recipient mobile number  * @param validateCode  Random verification code ( Four or six ) * @return */
    public void sendSMS(String telNumber, String validateCode) throws Exception {
    
        // Hazelnut cloud SMS   client 
        // Request address , Individual developers use https://sms_developer.zhenzikj.com, Enterprise developers use https://sms.zhenzikj.com
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        // Store request parameters map aggregate 
        Map<String, Object> params = new HashMap<String, Object>();
        // Recipient mobile number 
        params.put("number", telNumber);
        // SMS template ID
        params.put("templateId", templateId);
        // SMS template parameters 
        String[] templateParams = new String[2];
        templateParams[0] = validateCode;
        templateParams[1] = invalidTimer;
        params.put("templateParams", templateParams);
        /** * 1.send Method is used to send a single SMS , All request parameters need to be encapsulated in Map in ; * 2. The return result is json strand :{ "code":0,"data":" Send successfully "} * 3. remarks :(code:  Send status ,0 For success . Not 0 Failed to send for , Can be obtained from data View error messages in ) */
        String result = client.send(params);
    }

    public String getApiUrl() {
    
        return apiUrl;
    }

    public void setApiUrl(String apiUrl) {
    
        this.apiUrl = apiUrl;
    }

    public String getAppId() {
    
        return appId;
    }

    public void setAppId(String appId) {
    
        this.appId = appId;
    }

    public String getAppSecret() {
    
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
    
        this.appSecret = appSecret;
    }

    public String getTemplateId() {
    
        return templateId;
    }

    public void setTemplateId(String templateId) {
    
        this.templateId = templateId;
    }

    public String getInvalidTimer() {
    
        return invalidTimer;
    }

    public void setInvalidTimer(String invalidTimer) {
    
        this.invalidTimer = invalidTimer;
    }
}

2.4 Random captcha generation ( Expanding tools )

/** * @author cb * @Description  Randomly generate verification code tool class  * @Date 2021/12/26 10:59 */
public class RandomUtil {
    

    /** *  Generate verification code randomly  * @param length  The length is 4 Bits or 6 position  * @return */
    public static String generateValidateCode(int length){
    
        Integer code =null;
        if(length == 4){
    
            code = new Random().nextInt(9999);// Generate random number , The maximum is 9999
            if(code < 1000){
    
                code = code + 1000;// Ensure that the random number is 4 Digit number 
            }
        }else if(length == 6){
    
            code = new Random().nextInt(999999);// Generate random number , The maximum is 999999
            if(code < 100000){
    
                code = code + 100000;// Ensure that the random number is 6 Digit number 
            }
        }else{
    
            throw new RuntimeException(" Can only generate 4 Bit or 6 Digit verification code ");
        }
        return String.valueOf(code);
    }

}

2.5 Regular expression validation data ( Expanding tools )

Common regular expressions —— Tool class ( cell-phone number , mailbox ,QQ, Fax )

3、 ... and 、 Case presentation

/** * @Description * @Author cb * @Date 2022-01-05 23:51 **/
@RestController
@RequestMapping("/api/sms")
@Api(tags = " Interface for SMS Management ")
public class SmsApiController {
    

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SmsService smsService;

    // Send mobile phone verification code 
    @ApiOperation(" Send mobile phone verification code ")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
    
        // Judge whether the mobile phone number is empty 
        if (StringUtils.isEmpty(phone)) {
    
            return Result.setResult(ResponseEnum.MOBILE_NULL_ERROR);
        }
        boolean flag = RegexValidateUtil.checkphone(phone);
// if (!flag) {
    
// return Result.setResult(ResponseEnum.MOBILE_ERROR);
// }
        // Generate verification code 
        String code = RandomUtil.generateValidateCode(4);
        // call service Method to send verification code SMS 
        boolean b = smsService.sendShortMessage(phone, code);
        if (b) {
    
            // Store the verification code in redis
            String key = "ymjr:sms:code:" + phone;
            redisUtils.set(key, code, 120);
            return Result.ok().message(" Message sent successfully ");
        }
        return Result.error().message(" SMS sending failed ");
    }

}


原网站

版权声明
本文为[Slightly drunk CC]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170528546928.html