话不多说,直接开弄
第一,使用maven仓库,直接在pom.xml加入
```
<!--七牛短信-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0,7.2.99]</version>
</dependency>
```
第二,负责调用七牛云短信接口的util
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author
*/
@Slf4j
@Component
public class SendMessageUtil {
/**
* 发送手机验证码
*/
public static boolean sendMessageCheck(String templateId,String[] phone,Map<String,String> map) {
String accessKey = "*********";
String secretKey = "*********";
Auth auth = Auth.create(accessKey, secretKey);
SmsManager smsManager = new SmsManager(auth);
try {
Response resp = smsManager.sendMessage(templateId, phone , map);
if(resp.statusCode == 200){
return true;
}else {
return false;
}
} catch (QiniuException e) {
log.info("发生短信异常 =======================" ,e);
}
return false;
}
}
其中accessKey(AK),secretKey(SK),TemplateId(模板id)可以在申请七牛云短信时获取。
第三,实现接口
1.controller
/**
* 发送短信验证码
*/
@RequestMapping(value = "/api", method = RequestMethod.POST)
@ApiOperation("发送短信验证码")
public boolean sendValidCode(@RequestParam("phone") String phone) throws Exception {
boolean b = studentService.sendSmsCode(phone);
return b;
}
2.service
public interface ILoginService extends IService<Student> {
/**
* 发送手机验证码
*/
boolean sendSmsCode(String phone) throws Exception;
}
3.serviceImpl
@Override
public boolean sendSmsCode(String phone) throws Exception {
//存入redis
// redisService.set(WhlConstants.Redis.MESSAGECODE_PHONE + phone, code , 60*3L);
String templateId = "*********";
Map<String , String> map = new HashMap<String , String>();
//生成短信验证码(随机6位)
map.put("code",StrUtils.getRandomString(6));
boolean b = SendMessageUtil.sendMessageCheck(templateId, new String[]{phone}, map);
System.out.println("============="+b);
return b;
}
4.生成随机数
public static String getRandomString(int length) {
String str = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(10);
sb.append(str.charAt(number));
}
return sb.toString();
}
参数phone是个数据,可放多个手机号。map就是前面说的map,也可以放多个参数。验证码存放在redis里,也可以存放在mysql数据库。建议存放在redis里。到此七牛发送短信验证码的流程就说完了,菜鸟一个还望各位见谅。