1.选择一个短信平台,因为之前项目用的是赛邮云通信(submail),所以在这里以此为例。
2.需要到平台上创建账号,先参阅api文档研究入参。
(1)需要用到应用Id和密钥进行身份鉴权,在应用集成-》应用页面进行创建
(2)创建短信模板,短信-》新建 页面可以创建新的短信模板
3.接口调用
用到的jar包:commons-logging.jar gson.jar httpclient.jar httpcore.jar json-simple.jar
HttpPost httpPost = new HttpPost();
CloseableHttpClient client = HttpClientBuilder.create().build();
httpPost.setURI(new URI("https://api.submail.cn/message/xsend.json"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("appid", "*****")); //(1)中创建的appid
params.add(new BasicNameValuePair("to", "***********")); //发送的手机号
params.add(new BasicNameValuePair("project", "****")); //(2)中创建的短信模板标识
params.add(new BasicNameValuePair("signature", "*****************")); //(1)中创建的密钥
Map<String,String> vars = new HashMap<>();
vars.put("code","5555");
params.add(new BasicNameValuePair("vars", JSONObject.toJSONString(vars))); //模板中可设可变参数,这里为传参。 在模板中的设置为@var(code)
httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
HttpResponse response = client.execute(httpPost);
String s = EntityUtils.toString(response.getEntity());
System.out.println(s);
4.一般短信验证码会有时间限制,即几分钟内有效。这里用到的是redis来存取验证码及控制时间。
话不多说,上源码!
@Resource
private RedisTemplate redisTemplate;
BoundValueOperations valueOps = redisTemplate.boundValueOps(phone);
String code = (String) valueOps.get();
//发送短信间隔时间1分钟,验证码有效时间2分钟
int timeout = 1;
int expireMinute = 2;
int codeLength = 6;
if (StringUtils.isNotEmpty(code)) {
Long expire = valueOps.getExpire();
if (expire >= (expireMinute - timeout) * 60) {
throw new ServiceException(StatusCode.ERROR_COMMON, "发送验证码间隔不能小于" + timeout + "分钟");
} else {
code = RandomStringUtils.getRandomNumberStr(codeLength); //此方法为创建一个随机六位数,即验证码。
valueOps.set(code);
valueOps.expire(expireMinute, TimeUnit.MINUTES);
}
} else {
code = RandomStringUtils.getRandomNumberStr(codeLength);
valueOps.set(code);
valueOps.expire(expireMinute, TimeUnit.MINUTES);
}
OK,到这里就搞定了!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。