1. 程式人生 > >java發送短信驗證碼

java發送短信驗證碼

json ppi com arraylist get commons uri 接口 map

本文作者:回頭不是岸


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,到這裏就搞定了!

java發送短信驗證碼