心向天空

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

Java实现阿里云短信接口

1.首先,把JS代码拿出来看看

$(".btn-submit").click(function(){
            var phone = $('#phone').val();
            //手机号码验证
            if(!(/^1[3456789]\d{9}$/.test(phone))){
                layer.msg("手机号码输入有误", {icon : 2,time:1000});
                return false;
            }else{
                //触发定时器
                settime(this);
                //异步发请求调用接口
                var phone = $("#phone").val();
                $.ajax({
                    url: '${baseurl }/getBizId',
                    data:{phone:phone},
                    dataType: 'json',
                    success: function(data){

                    },error : function(data) {

                    }
                });
            }
        });

首先验证手机号码格式。然后使用ajax提交请求


2.接下来展示后台代码

2.1

阿里云短信接口工具类
package com.muen.util;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.muen.pojo.SendSmsRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 阿里云短信接口工具类
 *
 */
public class SMSUtil {

    private static Logger logger = LoggerFactory.getLogger(SMSUtil.class);

    //产品名称
    static final String product = "";
    /**
     * 产品域名
     */
    static final String domain = "";
    /**
     * 对应你阿里云账户的 accessKeyId
     */
    private static final String accessKeyId = "";

    /**
     * 对应你阿里云账户的 accessKeySecret
     */
    private static final String accessKeySecret = "";
    /**
     * 对应签名名称
     */
    private static final String signName = "";
    /**
     * 对应模板代码
     */
    public static final String templateCode = "";

    /**
     * 短信发送
     *
     * @param telphone 发送的手机号
     * @throws ClientException
     */
    public static SendSmsResponse SendMessage(String telphone) throws ClientException {
        // 生成六位随机数
        StringBuffer stringBuffer = new StringBuffer();
        for (int x = 0; x <= 5; x++) {
            /**默认值为1*/
            int random = 1;
            if (x == 0) {
                /**第一个数 1到9*/
                random = (int) (Math.random() * 9 + 1);
            } else {
                /**其它的 0到9*/
                random = (int) (Math.random() * (10 - 1));
            }
            stringBuffer.append(random);
        }
        String string = stringBuffer.toString();
        //随机六位数的验证码
        int mobile_code = Integer.parseInt(string);
        System.out.println(mobile_code);
        // 设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient client = new DefaultAcsClient(profile);

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //请求方式:post
        request.setMethod(MethodType.POST);
        //待发送手机号
        request.setPhoneNumbers(telphone);
        //短信签名
        request.setSignName(signName);
        //短信模板code
        request.setTemplateCode(templateCode);
        //模板内容${code}参数值
        request.setTemplateParam("{\"code\":\"" + mobile_code + "\"}");
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = client.getAcsResponse(request);
            sendSmsResponse.setBizId(String.valueOf(mobile_code));
            return sendSmsResponse;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
            logger.debug("SMSUtil", e.getMessage());
        }
        return sendSmsResponse;
    }

}

2.2

 用户登录相关操作
package com.muen.controller.personalManage;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;

import com.muen.pojo.SendSmsRecord;
import com.muen.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.muen.controller.BaseController;
import com.muen.pojo.PersonalBaseInfo;
import com.muen.util.SMSUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户登录
 *
 */
@Controller
public class PersonalController extends BaseController {

    private Logger logger = Logger.getLogger(PersonalController.class);

    /**
     * 调用工具类获取验证码
     */
    @RequestMapping(value = "/getBizId")
    @ResponseBody
    public void getBizId(String phone) throws ClientException {
        logger.info(phone + " <获取验证码开始");
        if (phone != null) {
            SendSmsResponse sendMessage = SMSUtil.SendMessage(phone);
            if (sendMessage != null) {
                logger.info(phone + " <获取验证码成功");
                logger.info(phone + " <短信记录开始");
                //发送验证码成功,记录短信发送信息
                SendSmsRecord sendSmsRecord = new SendSmsRecord();
                sendSmsRecord.setTemplateID(SMSUtil.templateCode);
                sendSmsRecord.setAuthCode(String.valueOf(sendMessage.getBizId()));
                sendSmsRecord.setReceiveAccount(phone);
                sendSmsRecord.setSendTime(new Date());
                sendSmsRecord.setStatus(1);
                //插入发送短信信息
                sendSmsRecordService.addSendSmsRecord(sendSmsRecord);
                logger.info(phone + " <短信记录结束");
                HttpSession session = request.getSession();
                //验证码
                String bizId = sendMessage.getBizId();
                session.setAttribute("phone", phone);
                session.setAttribute("bizId", bizId);
                //设置session的有效时间 24小时
                session.setMaxInactiveInterval(60 * 60 * 24);
                try {
                    //TimerTask实现10分钟后从session中删除bizId
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            //移除session存的验证码
                            session.removeAttribute("bizId");
                            timer.cancel();
                        }
                    }, 60 * 1000 * 10);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //发送验证码失败,记录短信发送信息
                SendSmsRecord sendSmsRecord = new SendSmsRecord();
                sendSmsRecord.setTemplateID(SMSUtil.templateCode);
                //失败默认验证码值000000
                sendSmsRecord.setAuthCode("000000");
                sendSmsRecord.setReceiveAccount(phone);
                sendSmsRecord.setSendTime(new Date());
                sendSmsRecord.setStatus(0);
                //插入发送短信信息
                sendSmsRecordService.addSendSmsRecord(sendSmsRecord);
                logger.info(phone + " <获取验证码失败");
            }

        }
        logger.info(phone + " <获取验证码结束");
    }

    /**
     * 用户验证码登录验证
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Map<String, Object> personalCenter(String phone, String code) throws ClientException, InterruptedException{
        String openId = null;
        //从Cookie中获取Openid
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("openId")){
                 openId = cookie.getValue();
            /*    String username = loginInfo.split(",")[0];
                String password = loginInfo.split(",")[1];
                request.setAttribute("username", username);
                request.setAttribute("password", password);*/
            }
        }
        logger.info(phone + " <登录开始");
        Map<String, Object> data = null;
        if (phone != null && code != null) {
            //先判断用户是否已注册
            PersonalBaseInfo personal = personalService.getPersonalBaseInfo(phone);
            if (personal != null) {
                //判断openid是否为空
                if(personal.getOpenid() == null || personal.getOpenid() == ""){
                    personalService.updatePersonalOpenid(phone,openId);
                }
                //验证登录信息
                data = validateLogon(phone, code);
            } else {
                //添加用户信息
                personalService.addPersonal(phone);
                //判断openid是否为空
                if(personal.getOpenid() == null || personal.getOpenid() == ""){
                    personalService.updatePersonalOpenid(phone,openId);
                }
                //验证登录信息
                data = validateLogon(phone, code);
            }
        }
        return data;
    }

    /**
     * 登录信息验证
     */
    public Map<String, Object> validateLogon(String phone, String code) {

        Map<String, Object> data = new HashMap<String, Object>();
        //返回给前台判断登录是否成功
        boolean flag = false;
        boolean yzmflag = false;
        //session中存的用户电话和验证码
        String userPhone = (String) getSession().getAttribute("phone");
        String bizId = (String) getSession().getAttribute("bizId");
        //前台用户输入的电话和验证码和session中存的做对比
        if (phone.equals(userPhone) && code.equals(bizId)) {
            PersonalBaseInfo personalInfo = personalService.getPersonalBaseInfo(phone);
            String idCard = personalInfo.getIdCard();
            if (idCard != null) {
                personalInfo.setIdCard(idCard);
            }
            //session保存用户信息
            getSession().setAttribute("personalInfo", personalInfo);
            getSession().setAttribute("code", code);
            //设置session的有效时间 24小时
            getSession().setMaxInactiveInterval(60 * 60 * 24);
            flag = true;
            //获取用户最后访问的路径地址
            String path = request.getHeader("referer");
            String headerPath = path.substring(path.indexOf('/', 7) + 1, path.length());
            data.put("flag", flag);
            data.put("headerPath", headerPath);
            logger.info(phone + " >登录成功");
        } else {
            if (bizId == null) {
                yzmflag = true;
                data.put("yzmflag", yzmflag);
                data.put("flag", flag);
                logger.info(phone + " >验证码失效  >登录失败");
            } else {
                data.put("yzmflag", yzmflag);
                data.put("flag", flag);
                logger.info(phone + " >验证码错误  >登录失败");
            }
        }
        return data;
    }

    /**
     * 判断是否登录  登录回到主页,没有登录就返回登录页面
     */
    @RequestMapping("/admin")
    public String indexPage(HttpServletRequest request, HttpServletResponse response) {
        PersonalBaseInfo personalInfo = (PersonalBaseInfo) getSession().getAttribute("personalInfo");
        PersonalBaseInfo personalBaseInfo = (PersonalBaseInfo) getSession().getAttribute("PersonalBaseInfo");
        if (StringUtils.isBlank(personalInfo)) {
            if (StringUtils.isBlank(personalBaseInfo)) {
                return "login";
            } else {
                return "Home/Index";
            }
        } else {
            return "Home/Index";
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/loginout")
    public String loginout(HttpServletRequest request, HttpServletResponse response) {
        //销毁session
        getSession().invalidate();
        return "login";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping("/personal/login")
    public String replaceBind() {
        return "login";
    }

}

~~~~~~~~~~~~到这就完了。。。。。。

 

posted on 2020-05-14 16:13  心向天空❤  阅读(664)  评论(0编辑  收藏  举报

导航