基于redis的短信验证码服务开发
目前可以提供的验证码服务平台有很多,这里选择阿里大于短信验证码服务平台,里面有10元体验卷可以免费试用,不多说上代码。写代码之前需要去阿里大于平台申请验证码服务,同时下载相应的SDK包,可以将下载下来的jar包导入到maven本地仓库:
mvn install:install-file -DgroupId=org.taobao.sdkjava -DartifactId=taobao-core -Dversion=1.0 -Dpackaging=jar -Dfile=taobao-sdk-java-auto_1455552377940-20160607.jar
只需要在pom文件依赖即可:
<dependency>
<groupId>org.taobao.sdkjava</groupId>
<artifactId>taobao-core</artifactId>
<version>1.0</version>
</dependency>
验证码服务接口:
public interface SmsVerificationCodeService {
/***
* 发送验证码
* @param phoneName
* @return
*/
String sendMessage(String phoneName);
/**
* 判断验证码是否正确
* @param phone
* @param code
* @return
*/
boolean checkIsCorrectCode(String phone,String code);
}
验证码服务实现:
public class SmsVerificationCodeServiceImpl implements SmsVerificationCodeService {
private static Logger LOGGER= LoggerFactory.getLogger(SmsVerificationCodeService.class);
//短信验证码过期时间
private static int EXPIRATIONTIME=3000;
@Resource
private RedisService redisService;
@Transactional
@Override
public String sendMessage(String phoneName) {
String rusult = null;
String url = "http://gw.api.taobao.com/router/rest";
// 成为开发者,创建应用后系统自动生成,带星号的地方可以通过阿里大于平台申请
String appkey = "*****";
String secret = "*******";
String code = getRandNum(6);
TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
req.setExtend("1234");
req.setSmsType("normal");
req.setSmsFreeSignName("****");
req.setSmsParamString("{\"code\":\""+code+"\"}");
req.setRecNum(phoneName);
req.setSmsTemplateCode("*****");
try {
AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
System.out.println(rsp.getBody());
rusult = rsp.getSubMsg();
} catc