当前位置:网站首页>Hazelnut cloud - SMS (tool)
Hazelnut cloud - SMS (tool)
2022-06-26 10:45:00 【Slightly drunk CC】
Hazelnut cloud —— SMS ( Tools )
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 ");
}
}
边栏推荐
- Global and Chinese market of electronic pet door 2022-2028: Research Report on technology, participants, trends, market size and share
- JS reverse | four libraries and one platform response data encryption
- [online simulation] Arduino uno PWM controls the speed of DC motor
- Solution to the problem of compilation error due to repeated third-party package names
- Notes - simple but adequate series_ KVM quick start
- Redis中执行Lua脚本
- Vscode environment setup: synchronous configuration
- Oracle sqlplus query result display optimization
- MySQL backup and restore command
- MySQL 8th job
猜你喜欢
Using foreach to loop two-dimensional array
Selection of webrtc video codec type VP8 H264 or other? (openh264 encoding, ffmpeg decoding)
工程数学概率论统计简明教程第二版复习大纲
How to start the learning journey of webrtc native cross platform development?
Small example of SSM project, detailed tutorial of SSM integration
String constant pool, class constant pool, and runtime constant pool
MySQL 9th job - connection Query & sub query
Opencv image processing - grayscale processing
【Leetcode】76. Minimum covering substring
[echart] II. User manual and configuration item reading notes
随机推荐
[echart] i. how to learn echart and its characteristic document reading notes
Common interview questions of binary tree
[online simulation] Arduino uno PWM controls the speed of DC motor
Basic MySQL
MySQL Chapter 6 Summary
appliedzkp zkevm(8)中的Plookup Table
Function run time
六月集训(第26天) —— 并查集
About multi table query of MySQL
[untitled]
MySQL 11th job - view application
Concise course of probability theory and statistics in engineering mathematics second edition review outline
What is LSP
[difficult and miscellaneous diseases] @transitional failure summary
MySQL job 11 - application de la vue
DataBinding使用与原理分析
Global and Chinese market for change and configuration management software 2022-2028: Research Report on technology, participants, trends, market size and share
MySQL第十次作业-视图
MySQL第六次作业-查询数据-多条件
Pit record_ TreeSet custom sorting results in less data loss