java SMS captcha access limit instance

  • 2020-12-10 00:42:41
  • OfStack

Now, no matter what project, the use of SMS verification function, will be designed in the program to limit the number of times the SMS verification code can be obtained, which is mainly to avoid the SMS verification code interface being brushed.

The first paragraph is exactly to do a project of the user SMS verification code login function, I studied the following, the following post to share 1.

Here involves the SMS interface, with the third party SMS interface - dynamic thinking mind le letter (http: / / www. lx598. com /), if you want to understand the text interface access, can go to their website, look at the text interface API documentation, should refer to the following code will be able to understand.

User registration part, the main code is as follows:


// The main js Methods: 

// Obtain mobile phone verification code: 

function getRegCode() {
    if($.trim($('#inputCaptcha').val()) == ''){
       $('#imgRs').html(" The graphic captcha cannot be empty ");
       $('#inputCaptcha').select();
       return;
     }
    
    if (!isPhoneNum($('#phoneRe').val())) {
      document.getElementById('phoneReInfo').innerHTML = '<font color="red"> Please fill in the valid one 11 Mobile phone number </font>';
    } else {
      document.getElementById('phoneReInfo').innerHTML = ' Sign in with your mobile phone number ';
    

      $.ajax({
        url : "${path}/account/checkMob",
        type : "POST",
        data : "account.ACCMOB=" + $('#phoneRe').val(),
        contentType : "application/x-www-form-urlencoded;charset=utf-8",
        async : false,
        success : function(data) {
          res = data;
          if (data == 1) {
            document.getElementById('phoneReInfo').innerHTML = '<font color="red"> The phone number has been registered </font>';
            refreshYzm();
          } else {
            document.getElementById('phoneReInfo').innerHTML = '<font color="green"> The phone number is available </font>';
            $.ajax({
              url : "${path}/account/reAimcodeGetVeCode",
              type : "POST",
              data : "account.ACCMOB="
                  + $('#phoneRe').val()
                  + "&fromSource=4&smsCount="+$('#smsCount').val()
                  +"&searchName="+$.trim($('#inputCaptcha').val()),
              contentType : "application/x-www-form-urlencoded;charset=utf-8",
              async : false,
              success : function(data) {
                myArray = data.split("&");
                if (myArray[0] == ' Send a success !') {
                  canCaptcha = true;
                  document.getElementById('phoneReInfo').innerHTML = '<font color="green"> Verification code has been sent, please note that check! </font>
                  accountFID = myArray[1];
                  }else if(data == ' Restrictions apply '){
                  document.getElementById('phoneReInfo').innerHTML = '<font color="red">1 A cell phone number 1 Days is maximum 3 Times! </font>';
                  refreshYzm();
                }else if(data == ' Verification code error '){
                  document.getElementById('phoneReInfo').innerHTML = '<font color="red"> Verification code error! </font>';
                  refreshYzm();
                }
              },
              error : function() {
                alert(' abnormal , Internal validation error! '+data);
              }
            });

          }
        },
              error : function() {
              alert(' Exception, verification error! ');
            }
          });
    }
    var smsCount=parseInt($('#smsCount').val());
    smsCount=smsCount<3?smsCount+1:3;
    $('#smsCount').val(smsCount);
  }

//  Register a new user 
// account  For the user class 

  @Action(value = "reAimcodeGetVeCode")
  public void reAimcodeGetVeCode() {
    PrintWriter out;
    String result = " Verification code application failed! Please try again! ";
    try {
      smsUnit = new SmsUnit(ConfUtil.getProperty("sys_sms_server"));
      if (null != account.getACCMOB() && !account.getACCMOB().equals("")) {
        account.setACCSTATUS(new BigDecimal(1));// Set usage status : unused 
        String verifyCode = String
            .valueOf(new Random().nextInt(899999) + 100000);// Generate SMS verification code 
        account.setFSECURITYCODE(verifyCode);
        account.setACCCREATEDATE(new Date());
        
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 1); //  Set the verification code invalidation time as 24 hours 
        account.setFREGISTERSOURCE(fromSource);// Set the registration source 
        //  Determine if the phone has obtained a captcha 
        AccountCriteria accountCriteria = new AccountCriteria();
        accountCriteria.createCriteria().andACCMOBEqualTo(
            account.getACCMOB());
        List<Account> accs = accountService
            .selectByExample(accountCriteria);
        // Verification code application times 
        int re = 0;
        Integer cishu = 0;
        // If the user doesn't exist 
        if (accs == null || accs.isEmpty()) {
          cishu = 1;
          account.setSDKURL("1");
          account.setFSECURITYOUTTIME(c.getTime());// Set the validating time of the verification code 
          BigDecimal accid=accountService.getPrimaryKey();
          account.setFID(accid);
          re = accountService.insertSelective(account,IPUtil.getRealIP(request));
          Cookie cookie=new Cookie("id" , accid.toString());
          cookie.setMaxAge(Integer.MAX_VALUE);
          response.addCookie(cookie);
        } else {
          Account ac = accs.get(0);
          account.setFID(ac.getFID());
          Date date = new Date();
          //  Number of times to apply verification code through time determination 
          // If it's new 1 Day, then change the usage to 1
          if (date.getDate() >= ac.getFSECURITYOUTTIME().getDate()) {
            account.setSDKURL("1");
          } else {
            Integer count = Integer.parseInt(ac.getSDKURL());
            account.setSDKURL(count + 1 + "");// Is not a new 1 The number of day +1
          }
          cishu = Integer.parseInt(account.getSDKURL());
          account.setFSECURITYOUTTIME(c.getTime());
          if (cishu <= 3)
            re = accountService
                .updateByPrimaryKeySelective(account); // Use the modify method to save the verification code to send the information 
        }

        if (re > 0 && cishu <= 3) {
          request.getSession().removeAttribute(ConstValues.WEB_SESSION_PROMOTE);
          AccountCriteria ac = new AccountCriteria();
          ac.createCriteria().andACCMOBEqualTo(account.getACCMOB());
          List<Account> acList = new ArrayList<Account>();
          acList = accountService.selectByExample(ac);
          if (acList != null && acList.size() > 0) {
            //  Text message sending is performed here 
            
            String content = " Your captcha is :" + verifyCode+" , the code is valid for 24 Hour, this code can only be used 1 Times! [SMS signature] ";
            SendSmsReply sendSmsReply = smsUnit.sendSms(accName,accPwd ,account.getACCMOB(),content,"");
 
// Call the first 3 Side interface to send SMS messages             result = sendSmsReply.getReplyMsg() + "&"
                + acList.get(0).getFID() + "&"
                + acList.get(0).getSDKURL();
          }
        } else if (cishu > 3) {
          result = " Restrictions apply ";
        }
      }
    } catch (Exception e) {
      logger.error(" Failed to get captcha ", e);
    } finally {
      try {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        out = response.getWriter();
        out.write(result);
      } catch (IOException e) {
        logger.error("", e);
      }
    }
  }


// This is The power mind Letchington 3 Reference code of sending SMS function of the square SMS interface: 

/**
         *  Send a text message 
         * @param accName  Letxin account user name 
         * @param accPwd  Letxin account password 
         * @param seed  The current time   Format: YYYYMMDD HHMISS  Such as: 20130806102030
         * @param aimcodes  The phone number is separated by a comma 
         * @param content  Add signature to the content 
         * @param schTime  Timing time format is as follows: 2010-01-01 08:00:00
         * @return  The result returned by the server  ok: business id  or   The error code 
         */
        public static String sendSms(String accName,String accPwd,String mobies,String content,String schTime){
          StringBuffer sb = new StringBuffer("http://sdk.lx198.com/sdk/send2?");
          try {
            String seed=new SimpleDateFormat(dateFormatStr).format(new Date());
            sb.append("&accName="+accName); 
            sb.append("&seed="+seed);
            sb.append("&accPwd="+MD5.getMd5String(MD5.getMd5String(accPwd)+seed)); 
            sb.append("&aimcodes="+mobies);
            sb.append("&schTime="+URLEncoder.encode(schTime,"UTF-8")); // Space punctuation do encode conversion 
            sb.append("&content="+URLEncoder.encode(content,"UTF-8")); // The Chinese do encode conversion 
            URL url = new URL(sb.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            return in.readLine();
          } catch (Exception e) {
            e.printStackTrace();
          }
          return null;
        }


Related articles: