使用阿里云手机短信验证方式实现登录注册--详细教程

app端获取验证码接口 此处将随机验证码存到Redis中

 @ApiOperation(value = "获取验证码")
    @ApiImplicitParams({
    })
    @PostMapping("isCode")
    public AjaxResult isCode(String phone) {
		//生成随机4位验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        try {
            String flag= SmsUtil.sendSms(phone, code);
        }catch (Throwable e){
            e.printStackTrace();
            log.error("调用验证码接口失败");
            return AjaxResult.error("调用验证码接口失败!");
        }
        log.info("验证码");
        //使用手机号加验证码的方式,防止重复
        ValueOperations<String, String> opsForValue = template.opsForValue();
        opsForValue.set(phone+code, phone+code, 2, TimeUnit.MINUTES);
        if (opsForValue.get(phone+code) == null) {
            return AjaxResult.error("存入redis失败");
        }
        return AjaxResult.success();
    }

注册接口

@ApiOperation(value = "注册")
    @ApiImplicitParams({
    })
    @PostMapping("signUp")
    public AjaxResult signUp(String username, String password, String phone ,String code) {
        ValueOperations<String, String> opsForValue = template.opsForValue();
        QueryWrapper<WeixinUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", phone);
        WeixinUser user = weixinUserService.getOne(userQueryWrapper);
        if(user!=null){
            return AjaxResult.error("此手机号已注册");
        }
        if ((phone+code).equals(opsForValue.get(phone+code))) {
            String password1=(Utility.QuickPassword(password));//密码加密
            weixinUserService.insertUser(username,password1,phone);
            return AjaxResult.success();
        }
        else{
            return AjaxResult.error("验证码错误或失效");
        }
    }

密码登录

@ApiOperation(value = "密码直接登录")
    @ApiImplicitParams({
    })
    @PostMapping("directLogin")
    public AjaxResult directLogin(String phone, String password) {
        QueryWrapper<WeixinUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", phone);
        WeixinUser user = weixinUserService.getOne(userQueryWrapper);
        if(user == null){
            return AjaxResult.error("此手机尚未注册");
        }
        else{  //校验密码
            if (user != null && BCrypt.checkpw(password, user.getPassword())) {
                Cache cache = cacheManager.getCache("serviceCacheToken");
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                cache.put(uuid, user);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put(serviceToken, uuid);//生成token
                AjaxResult json = new AjaxResult();
                json.put("msg", "登录成功");
                json.put("code", 1);
                json.put("token", resultMap);
                return json;
            }
        }
        return AjaxResult.error("密码错误");
    }

短信验证登录

@ApiOperation(value = "短信验证登录(可用)")
    @ApiImplicitParams({
    })
    @PostMapping("messageLogin")
    public AjaxResult messageLogin(String phone, String code) {
        QueryWrapper<WeixinUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", phone);
        WeixinUser user = weixinUserService.getOne(userQueryWrapper);
        if(user == null){
            return AjaxResult.error("此手机尚未注册");
        }
        else {
            ValueOperations<String, String> opsForValue = template.opsForValue();
            if ((phone + code).equals(opsForValue.get(phone + code))) {
                Cache cache = cacheManager.getCache("serviceCacheToken");
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                cache.put(uuid, user);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put(serviceToken, uuid);//生成token
                AjaxResult json = new AjaxResult();
                json.put("msg", "登录成功");
                json.put("code", 1);
                json.put("token", resultMap);
                return json;
            } else {
                return AjaxResult.error("验证码错误或失效");
            }
        }
    }

这里使用的阿里云的短信云服务器,辅助的配置类

import xxxx.SmsUtil;  //这是哥工具类在下面介绍
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * @ClassName: SmsProerties
 * @Description: 短信工具类 配置类
 * @Author: lxt
 * @Date: 2019-02-14 09:37
 * @Version 1.0
 **/
@ConfigurationProperties(prefix = "sms.aliyun")
@Component
public class SmsProerties {

    private  String regionId;
    private  String accessKeyId;
    private  String accessSecret;
    private  String templateCode;
    private  String signName;
    private  String messageType;
    private  String queueName;


    @PostConstruct
    public void init(){
        //短信具类配置初始化
        SmsUtil.initConfig(this);
    }

    public String getRegionId() {
        return regionId;
    }

    public SmsProerties setRegionId(String regionId) {
        this.regionId = regionId;
        return this;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public SmsProerties setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
        return this;
    }

    public String getAccessSecret() {
        return accessSecret;
    }

    public SmsProerties setAccessSecret(String accessSecret) {
        this.accessSecret = accessSecret;
        return this;
    }

    public String getTemplateCode() {
        return templateCode;
    }

    public SmsProerties setTemplateCode(String templateCode) {
        this.templateCode = templateCode;
        return this;
    }

    public String getSignName() {
        return signName;
    }

    public SmsProerties setSignName(String signName) {
        this.signName = signName;
        return this;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public String getQueueName() {
        return queueName;
    }

    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }

    @Override
    public String toString() {
        return "SmsProerties{" +
                "regionId='" + regionId + '\'' +
                ", accessKeyId='" + accessKeyId + '\'' +
                ", accessSecret='" + accessSecret + '\'' +
                ", templateCode='" + templateCode + '\'' +
                ", signName='" + signName + '\'' +
                ", messageType='" + messageType + '\'' +
                ", queueName='" + queueName + '\'' +
                '}';
    }
}

短信的工具类

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import xxxx.SmsProerties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: SmsUtill
 * @Description: 短信工具类
 * @Author: james
 * @Version 1.0
 **/
public class SmsUtil {
    private final static Logger logger = LoggerFactory.getLogger(SmsUtil.class);
    /**
     * 发送异常结果
     */
    private final static String EXCEPTION = "发送短信异常!";
    /**
     * 验证码发送成功结果
     */
    public final static String OK = "OK";

    private static SmsProerties smsProerties;

    /**
     * @Title: initConfig
     * @Description: 配置初始化
     * @Author: james
     * @param: smsProertiesInit
     * @throws:
     */
    public static void initConfig(SmsProerties smsProertiesInit){
        smsProerties = smsProertiesInit;
    }

    /**
     * @Title: sendSms
     * @Description: 发送短信验证码
     * @Author: james
     * @param: phoneNumbers 手机号,多个手机号用英文逗号隔开,最多支持1000个
     * @param: phoneNumbers,name,meeting,address,time 短信内容
     * @return: java.lang.String 返回调用结果 成功=>"OK";失败=>错误信息
     * @throws:
     */
    public  static  String sendSms(String phoneNumbers,String code)  {
        DefaultProfile profile = DefaultProfile.getProfile(smsProerties.getRegionId(), smsProerties.getAccessKeyId(), smsProerties.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        System.out.println("+++++++++++++++++++++++++++++++++++");
        System.out.println(smsProerties);
        System.out.println("+++++++++++++++++++++++++++++++++++");
        request.putQueryParameter("TemplateCode", smsProerties.getTemplateCode());
        request.putQueryParameter("SignName", smsProerties.getSignName());
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            return JSON.parseObject(response.getData()).getString("BizId");
        } catch (ServerException e) {
            logger.error(EXCEPTION,e);
        } catch (ClientException e) {
            logger.error(EXCEPTION,e);
        }catch (Exception e){
            logger.error(EXCEPTION,e);
        }
        return EXCEPTION;
    }
}

一起加油,进步!!!

你可能感兴趣的:(Spring,boot)