java实现短信验证码登录

java实现短信验证码登录

我这里是用的云片网发送短信,所以你在看代码的时候要看清楚你用的什么服务器发短信。
下面看代码,我这个不需要引入其他的jar包

controller 层

这个是获取验证码和用验证码登录

 /**
     * 获取验证码
     * @param wxUser
     * @return
     */
    @GetMapping("/getCode")
    public String getCode(WxUserModel wxUser) throws IOException, URISyntaxException {
        if(wxUser.getPhone()==null ||  wxUser.getPhone().equals("")){
            return "手机号不存在";
        }
        // 这里是工具类里面的方法,我这里就不贴出来了
        if(!PhoneUtils.isValidChinesePhone(wxUser.getPhone())){
            return  "手机号无效";
        }
        String code = SendCode.getCode(wxUser.getPhone());
        if("".equals(code)){
            return "获取验证码失败";
        }
        // 将验证码和手机号存到数据库
        wxUser.setPhoneCode(code);
        wxUserService.addPhoneCode(wxUser);
        return "获取验证码成功";
    }
  /**
     * 手机号登录
     * @param wxUser
     * @return
     */
    @GetMapping("/phone")
    public JSONObject loginPhone(WxUserModel wxUser, HttpServletResponse resp) throws UploaderTypeNotExistException, IOException, FileMetaNotValidException {
        JSONObject jsonObject = new JSONObject();
        if(wxUser.getPhone()==null ||  wxUser.getPhone().equals("")){
            jsonObject.put("message","手机号不存在");
            return jsonObject;
        }
        if(!PhoneUtils.isValidChinesePhone(wxUser.getPhone())){
            jsonObject.put("message","手机号无效");
            return  jsonObject;
        }
        if(wxUser.getPhoneCode().equals("")){
            jsonObject.put("message","请输入验证码");
            return  jsonObject;
        }
        // 查询验证码
        WxUserModel wu = wxUserService.getCode(wxUser.getPhone());
        if(!wu.getPhoneCode().equals(wxUser.getPhoneCode())){
            jsonObject.put("message","验证码错误");
            return  jsonObject;
        }
        jsonObject.put("wxUser",wxUserService.getPhone(wxUser,resp));
        return jsonObject;
    }

发送验证码工具类

注意下面的配置是需要到云片网获取的比如apikey 模板的 tpl_id 不然肯定是用不了的



import com.alibaba.fastjson.JSONObject;
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 org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;


public class SendCode {
     //查账户信息的http地址
     private static String URI_GET_USER_INFO =
             "https://sms.yunpian.com/v2/user/get.json";
     //智能匹配模板发送接口的http地址
     private static String URI_SEND_SMS =
             "https://sms.yunpian.com/v2/sms/single_send.json";
     //模板发送接口的http地址
     private static String URI_TPL_SEND_SMS =
             "https://sms.yunpian.com/v2/sms/tpl_single_send.json";
     //发送语音验证码接口的http地址
     private static String URI_SEND_VOICE =
             "https://voice.yunpian.com/v2/voice/send.json";
     //绑定主叫、被叫关系的接口http地址
     private static String URI_SEND_BIND =
             "https://call.yunpian.com/v2/call/bind.json";
     //解绑主叫、被叫关系的接口http地址
     private static String URI_SEND_UNBIND =
             "https://call.yunpian.com/v2/call/unbind.json";
     //编码格式。发送编码格式统一用UTF-8
     private static String ENCODING = "UTF-8";
     //修改为您的apikey.apikey可在官网(http://www.yunpian.com)登录后获取
     private static String apikey = "";
     //设置模板ID,如使用1号模板:【#company#】您的验证码是#code#
     long tpl_id = 2937596;
     public static String getCode(String mobile) throws IOException,
             URISyntaxException {
            // 这里我是用的数字,当然你可以加其他的字符
          String str="0123456789";
          StringBuilder sb=new StringBuilder(4);
          // 设置验证码长度
          for(int i=0;i<6;i++)
          {
               char ch=str.charAt(new Random().nextInt(str.length()));
               sb.append(ch);
          }
          /**************** 查账户信息调用示例 *****************/
          /**************** 使用智能匹配模板接口发短信(推荐) *****************/
          //设置您要发送的内容(内容必须和某个模板匹配。以下例子匹配的是系统提供的1号模板)
          String text = "你的短信验证码是:"+sb.toString()+"。";
          //发短信调用示例
           System.out.println(SendCode.sendSms(apikey, text, mobile));
          /**************** 使用指定模板接口发短信(不推荐,建议使用智能匹配模板接口) ******/

          //设置对应的模板变量值
//          String tpl_value = URLEncoder.encode("#code#", ENCODING) + "=" +
//                  URLEncoder.encode("1234", ENCODING) + "&" + URLEncoder.encode(
//                  "#company#", ENCODING) + "=" + URLEncoder.encode("云片网",
//                  ENCODING);
//          //模板发送的调用示例
//          System.out.println(tpl_value);
          //System.out.println(SendCode.tplSendSms(apikey, tpl_id, tpl_value,mobile));

          /**************** 使用接口发语音验证码 *****************/
          String code = "1234";
          //System.out.println(SendCode.sendVoice(apikey, mobile ,code));
          /**************** 使用接口绑定主被叫号码 *****************/
          //String from = "+86130xxxxxxxx";
          //String to = "+86131xxxxxxxx";
          //Integer duration = 30 * 60; // 绑定30分钟
          //System.out.println(SendCode.bindCall(apikey, from ,to , duration));
          /**************** 使用接口解绑主被叫号码 *****************/
          //System.out.println(JavaSmsApi.unbindCall(apikey, from, to));
          code=sb.toString();
          return code;
     }
     /**
      * 取账户信息
      *
      * @return json格式字符串
      * @throws java.io.IOException
      */
     public static String getUserInfo(String apikey) throws IOException,
             URISyntaxException {
          Map < String, String > params = new HashMap < String, String > ();
          params.put("apikey", apikey);
          return post(URI_GET_USER_INFO, params);
     }
     /**
      * 智能匹配模板接口发短信
      *
      * @param apikey apikey
      * @param text    短信内容
      * @param mobile  接受的手机号
      * @return json格式字符串
      * @throws IOException
      */
     public static String sendSms(String apikey, String text,
                                  String mobile) throws IOException {
          Map < String, String > params = new HashMap < String, String > ();
          params.put("apikey", apikey);
          params.put("text", text);
          params.put("mobile", mobile);
          return post(URI_SEND_SMS, params);
     }
     /**
      * 通过模板发送短信(不推荐)
      *
      * @param apikey    apikey
      * @param tpl_id     模板id
      * @param tpl_value  模板变量值
      * @param mobile     接受的手机号
      * @return json格式字符串
      * @throws IOException
      */
     public static String tplSendSms(String apikey, long tpl_id, String tpl_value,
                                     String mobile) throws IOException {
          Map < String, String > params = new HashMap < String, String > ();
          params.put("apikey", apikey);
          params.put("tpl_id", String.valueOf(tpl_id));
          params.put("tpl_value", tpl_value);
          params.put("mobile", mobile);
          return post(URI_TPL_SEND_SMS, params);
     }
     /**
      * 通过接口发送语音验证码
      * @param apikey apikey
      * @param mobile 接收的手机号
      * @param code   验证码
      * @return
      */
     public static String sendVoice(String apikey, String mobile, String code) {
          Map < String, String > params = new HashMap < String, String > ();
          params.put("apikey", apikey);
          params.put("mobile", mobile);
          params.put("code", code);
          return post(URI_SEND_VOICE, params);
     }
     /**
      * 通过接口绑定主被叫号码
      * @param apikey apikey
      * @param from 主叫
      * @param to   被叫
      * @param duration 有效时长,单位:秒
      * @return
     public static String bindCall(String apikey, String from, String to,
     Integer duration) {
     Map < String, String > params = new HashMap < String, String > ();
     params.put("apikey", apikey);
     params.put("from", from);
     params.put("to", to);
     params.put("duration", String.valueOf(duration));
     return post(URI_SEND_BIND, params);
     }
      * 通过接口解绑绑定主被叫号码
      * @param apikey apikey
      * @param from 主叫
      * @param to   被叫
      * @return
     public static String unbindCall(String apikey, String from, String to) {
     Map < String, String > params = new HashMap < String, String > ();
     params.put("apikey", apikey);
     params.put("from", from);
     params.put("to", to);
     return post(URI_SEND_UNBIND, params);
     }
      */
     /**
      * 基于HttpClient 4.3的通用POST方法
      *
      * @param url       提交的URL
      * @param paramsMap 提交<参数,值>Map
      * @return 提交响应
      */
     public static String post(String url, Map < String, String > paramsMap) {
          CloseableHttpClient client = HttpClients.createDefault();
          String responseText = "";
          CloseableHttpResponse response = null;
          try {
               HttpPost method = new HttpPost(url);
               if (paramsMap != null) {
                    List< NameValuePair > paramList = new ArrayList<
                                                NameValuePair >();
                    for (Map.Entry < String, String > param: paramsMap.entrySet()) {
                         NameValuePair pair = new BasicNameValuePair(param.getKey(),
                                 param.getValue());
                         paramList.add(pair);
                    }
                    method.setEntity(new UrlEncodedFormEntity(paramList,
                            ENCODING));
               }
               response = client.execute(method);
               HttpEntity entity = response.getEntity();
               if (entity != null) {
                    responseText = EntityUtils.toString(entity, ENCODING);
               }
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               try {
                    response.close();
               } catch (Exception e) {
                    e.printStackTrace();
               }
          }
          return responseText;
     }
/**	这个是用的阿里云的服务器发送的验证码
*/
//     public static String getCode(String phone){
//          String code="";
//          try {
//               String str="0123456789";
//               StringBuilder sb=new StringBuilder(4);
//               for(int i=0;i<4;i++)
//               {
//                    char ch=str.charAt(new Random().nextInt(str.length()));
//                    sb.append(ch);
//               }
//               DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "填写你的AccessKey ID", "填写你的AccessKey Secret");
//               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");    //我选择sendSms
//               //自定义的参数(手机号,验证码,签名,模板)
//               request.putQueryParameter("PhoneNumbers", phone);
//               request.putQueryParameter("SignName", "你的签名名称");
//               request.putQueryParameter("TemplateCode", "你的模版CODE");
//               //构建一个短信验证码(一般都是传进来的随机数,我这里测试直接写死)
//               HashMap map = new HashMap<>();
//               map.put("code",sb.toString());
//               request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
//
//               CommonResponse response = client.getCommonResponse(request);
//               code=sb.toString();
//               //输出响应是否成功
//               System.out.println(response.getData());
//
//          } catch (ServerException e) {
//               e.printStackTrace();
//          } catch (ClientException e) {
//               e.printStackTrace();
//          }
//          return code;
//     }

}

service层


    /**
     *  根据手机号查询是否存在该用户
     * @param wxUser
     */
    public WxUserModel getPhone(WxUserModel wxUser , HttpServletResponse resp) throws IOException, UploaderTypeNotExistException, FileMetaNotValidException {
        UserIdentity ui = new UserIdentity();
        ui.setAccountName(wxUser.getPhone());
        String token = jwt.generateToken(ui);
        resp.setHeader("Authorization", token);
        WxUserModel wxUserModel = wxUserMapper.selectPhone(wxUser.getPhone());
        return wxUserModel;
    }
    
    // 将验证码和手机号存到数据库
    public void addPhoneCode(WxUserModel wxUse) {
        WxUserModel wu = wxUserMapper.selectPhone(wxUse.getPhone());
        if(wu!=null){
            wu.setPhoneCode(wxUse.getPhoneCode());
            wxUserMapper.updateById(wu);
        }else{
            wxUserMapper.insertWxUser(wxUse);
        }
    }
    // 验证验证码和手机号是否匹配
      public  WxUserModel getCode(String phone) {
        WxUserModel w = wxUserMapper.selectPhone(phone);
        Assert.notNull(w,"验证码与手机号不匹配");
        return wxUserMapper.selectPhone(phone);
    }
    ```

你可能感兴趣的:(java实现短信验证码登录)