我用的是榛子云短信来实现短信验证码的功能的
1,引入依赖
<dependency>
<groupId>com.zhenzikj</groupId>
<artifactId>zhenzisms</artifactId>
<version>2.0.2</version>
</dependency>
2,SmsConfig类
/**
* 短信网关配置类
* @author linan
* @since 2.0
*/
public class SmsConfig {
public static final String apiUrl = "https://sms_developer.zhenzikj.com";
public static final String appId = "xx";
public static final String appSecret = "xx";
}
3,Service层
import org.json.JSONException;
import javax.servlet.http.HttpServletRequest;
/**
* 短信服务网关
* @author linan
* @since 2.0
*/
public interface SmsService {
/**
* 向手机号发送验证码
* @param number
* @param request
* @return 发送结果
*/
String sendMsgToNumber(String number, HttpServletRequest request);
/**
* 查看验证码是否有效
* @param code
* @param request
* @return
*/
String verifyCode(String code, HttpServletRequest request) throws JSONException;
}
4,CodeUtil工具类
import java.util.Random;
public class CodeUtil {
/** 自定义进制(0,1没有加入,容易与o,l混淆) */
private static final char[] r=new char[]{'q', 'w', 'e', '8', 'a', 's', '2', 'd', 'z', 'x', '9', 'c', '7', 'p', '5', 'i'
, 'k', '3', 'm', 'j', 'u', 'f', 'r', '4', 'v', 'y', 'l', 't', 'n', '6', 'b', 'g', 'h'};
/** (不能与自定义进制有重复) */
private static final char b= 'o';
/** 进制长度 */
private static final int binLen=r.length;
/** 序列最小长度 */
private static final int s=6;
/**
根据ID生成六位随机码
@param id ID
@return 随机码
*/
public static String toSerialCode(int id) {
char[] buf=new char[32];
int charPos=32;
while((id / binLen) > 0) {
int ind=(int)(id % binLen);
// System.out.println(num + “–>” + ind);
buf[--charPos] = r[ind];
id /= binLen;
}
buf[--charPos]=r[(int)(id % binLen)];
// System.out.println(num + “–>” + num % binLen);
String str=new String(buf, charPos, (32 - charPos));
// 不够长度的自动随机补全
if(str.length() < s) {
StringBuilder sb=new StringBuilder();
sb.append(b);
Random rnd=new Random();
for(int i=1; i < s - str.length(); i++) {
sb.append(r[rnd.nextInt(binLen)]);
}
str+=sb.toString();
}
return str;
}
public static long codeToId(String code) {
char chs[]=code.toCharArray();
long res=0L;
for(int i=0; i < chs.length; i++) {
int ind=0;
for(int j=0; j < binLen; j++) {
if(chs[i] == r[j]) {
ind=j;
break;
}
}
if(chs[i] == b) {
break;
}
if(i > 0) {
res=res * binLen + ind;
} else {
res=ind;
}
// System.out.println(ind + “–>” + res);
}
return res;
}
/**
* 生成6位数短信验证码
* @return 短信验证码
*/
public static String toVerifyCode (){
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
return verifyCode;
}
public static void main(String[] args) {
String val = "abcde";
for(int i = val.length() - 1 ; i >= 0; i-- ){
System.out.print(val.charAt(i));
}
}
}
5,Impl实现类
import com.smxy.config.SmsConfig;
import com.smxy.service.SmsService;
import com.smxy.util.CodeUtil;
import com.zhenzi.sms.ZhenziSmsClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 验证码服务实现
* @author linan
* @since 2.0
*/
@Service
public class SmsServiceImpl implements SmsService {
@Override
public String sendMsgToNumber(String number, HttpServletRequest request) {
String verifyCode = CodeUtil.toVerifyCode();
ZhenziSmsClient client = new ZhenziSmsClient(SmsConfig.apiUrl, SmsConfig.appId, SmsConfig.appSecret);
Map<String, Object> params = new HashMap<String, Object>();
//手机号码
params.put("number",number);
//模板id
params.put("templateId",3939);
String[] templateParams = new String[2];
templateParams[0] = verifyCode;
templateParams[1] = "1";
params.put("templateParams",templateParams);
JSONObject json = null;
try {
//发送短信
String result = client.send(params);
//结果转为json格式
json = new JSONObject(result);
result = json.get("code").toString();
if (!result.equals("0")){
return result;
}else{
json = new JSONObject();
json.put("mobile", number);
json.put("verifyCode", verifyCode);
json.put("createTime", System.currentTimeMillis());
// 将认证码存入SESSION
request.getSession().setAttribute("verifyCode", json);
return "验证码发送成功";
}
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
@Override
public String verifyCode(String code, HttpServletRequest request) throws JSONException {
JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
if ( json == null ){
return "验证码错误";
}
if ( !json.get("verifyCode").toString().equals(code) ){
return "验证码错误";
}
if ( (System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 ){
return "验证码超时";
}
return "验证成功";
}
}
6,Controller使用
@PostMapping("/sendVerifyCode")
@ApiOperation("向手机发送验证码")
public Map sendVerifyCode(@RequestParam("number") String number, HttpServletRequest request){
HttpSession session = request.getSession(true);
Map<String, Object> map = new HashMap<>();
map.put("sessionId", session.getId());
String result = userService.sendVerifyCode(number, request);
map.put("result", result);
return map;
}