SmsController.java 1.7 KB
Newer Older
m1991's avatar
m1991 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
package cn.wisenergy.web.sms;

import cn.wisenergy.common.utils.RedisUtils;
import cn.wisenergy.common.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/sms")
@RestController
public class SmsController {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/verifyCode")
    public Result verifyCode(String phone,Integer codeType) throws Exception {
        //判断phone和codeType是否符合输入类型
        if(!phone.matches(Constants.RegConstant.PHONE_REGSTR)){
            throw new BaseException(ResultEnum.PHONE_ERROR);
        }
        if(codeType!=Constants.Sms.CodeType.LOGIN_OR_REGISTER && codeType!=Constants.Sms.CodeType.PASS_UPDATE && codeType!=Constants.Sms.CodeType.ORDER_NOTICE){
            throw new BaseException(ResultEnum.CODETYPE_ERROR);
        }
        String key= StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.SMS_PRIFIX,phone,codeType+"");
        //判断是否超过60S
        String oldCode=redisUtils.getValue(key);
        if(!StringUtils.isBlank(oldCode)){
            throw new BaseException(ResultEnum.CODESEND_ERROR);
        }
        //生成随机数
        String code= MathUtils.random();
        //保存至Redis
        redisUtils.set(key,code,Constants.Duration.MINUTE_INT);
        boolean flag=smsUtils.sendMessage(phone,Constants.Sms.TemplateCode.LOGIN_OR_REGISTER,code);
        return flag? ResultUtils.returnSuccess():ResultUtils.returnFail();
    }
}