1. 程式人生 > >Java 手機驗證碼

Java 手機驗證碼

傳送簡訊驗證碼+登陸功能

置頂 2017年12月14日 19:39:55 Elsa曉冰 閱讀數:5100 標籤: 簡訊驗證碼登陸更多

個人分類: ❤【技術點們】…………技術積累

版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/binggetong/article/details/78805992

       業務:

       手機端點擊發送驗證碼,呼叫第三方平臺(我們用的是“任信了”平臺)的介面,去給手機發簡訊驗證碼。

 

  過程:   

                    

 

       程式碼:

           

 
  1. /**

  2. * 傳送簡訊驗證碼

  3. * @param json 前臺傳入電話號碼

  4. * @return 返回傳送結果向前臺

  5. */

  6. @RequestMapping("/getTestCode")

  7. @ResponseBody

  8. public GetTestCodeResult sendTestCode(@RequestParam(value="phone",defaultValue="") String phoneNumber ){

  9.  
  10. GetTestCodeResult result = new GetTestCodeResult();

  11. if(phoneNumber == null || phoneNumber.length()==0 ){

  12. result.setState(Result.ERROR);

  13. result.setMessage("手機號為空");

  14. return result;

  15. }

  16. String code =TestCode.getCode();

  17. if( code== null || code.length()==0){

  18. result.setState(Result.ERROR);

  19. result.setMessage("無效的驗證碼");

  20. return result;

  21. }

  22.  
  23. try {

  24. SMS.batchsendsm(phoneNumber,code);

  25. } catch (Exception e) {

  26. result.setState(Result.ERROR);

  27. result.setMessage("驗證碼傳送失敗");

  28. return result;

  29. }

  30. TestCodeInforVo testCodeInfor = new TestCodeInforVo();

  31. testCodeInfor.setCode(code);

  32. testCodeInfor.setPhone(phoneNumber);

  33. testCodeInfor.setDate(System.currentTimeMillis());

  34. testCodeInforMap.put(phoneNumber,testCodeInfor);

  35. result.setState(Result.SUCCESS);

  36. result.setMessage("驗證碼傳送成功");

  37. result.setData(code); //測試

  38. return result;

  39. }

 

 

        上面這個是傳送驗證碼的方法,其中包括了2個工具類:

 

        No.1 生成5位隨機數

        

 
  1. public class TestCode {

  2.  
  3. private final static int codeLength =5;

  4.  
  5. /**

  6. * @see 產生隨機驗證碼

  7. * @return 驗證碼字串

  8. */

  9. public static String getCode(){

  10.  
  11. Random rand = new Random();

  12. int a ;

  13. String result ="";

  14. for( int j =0; j<codeLength; j++ ){

  15. a = Math.abs( rand.nextInt()%9 );

  16. result += String.valueOf(a);

  17. }

  18. return result;

  19. }

  20. }

 

 

        No.2 呼叫第三方傳送簡訊介面

        

 
  1. package com.cn.zhongcai.util.app.util;

  2.  
  3. import java.io.BufferedReader;

  4. import java.io.IOException;

  5. import java.io.InputStreamReader;

  6. import java.io.OutputStreamWriter;

  7. import java.net.HttpURLConnection;

  8. import java.net.URL;

  9. import java.net.URLEncoder;

  10. import java.security.MessageDigest;

  11. import java.security.NoSuchAlgorithmException;

  12.  
  13. public class SMS {

  14.  
  15. //把介面地址和引數賦值,之後呼叫SMS3方法,引數photo是手機號,code是之前生成的驗證碼。

  16. public static void batchsendsm(String phone,String code)

  17. {

  18. try{

  19. String userid = URLEncoder.encode("15732622061","UTF-8"); //188

  20.  
  21. String url = "http://apis.renxinl.com:8080/smsgate/varsend.do?";

  22. String para = "user="+userid+"&pwd=9fa41ab9c5352bc29babd621a73d¶ms="+phone+","+code+"&mid=15552";

  23.  
  24. String str="";

  25. str=SMS3(para,url);

  26. System.out.println(str);

  27. }catch (Exception e) {

  28. e.printStackTrace();

  29. }

  30. }

  31.  
  32.  
  33. //postData是上面拼接的引數值,postURL 是介面的地址。我覺得這個方法是能訪問到第三方介面的方法。

  34. public static String SMS3(String postData,String postUrl){

  35. try{

  36. URL url = new URL(postUrl);

  37. HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  38. conn.setRequestMethod("POST");

  39.  
  40. conn.setRequestProperty("accept", "*/*");

  41. conn.setRequestProperty("connection", "Keep-Alive");

  42. conn.setRequestProperty("user-agent",

  43. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

  44. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

  45.  
  46. conn.setUseCaches(false);

  47. conn.setDoOutput(true);

  48. conn.setDoInput(true);

  49. OutputStreamWriter out= new OutputStreamWriter(conn.getOutputStream(),"UTF-8");

  50. out.write(postData);

  51. out.flush();

  52. out.close();

  53. if(conn.getResponseCode()!=HttpURLConnection.HTTP_OK){

  54. System.out.println("connect failed!");

  55. return "";

  56. }

  57. String line,result = "";

  58. BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));

  59. while((line= in.readLine()) != null){

  60. result += line+"\n";

  61. }

  62. in.close();

  63. return result;

  64. }catch(IOException e){

  65. e.printStackTrace(System.out);

  66. }

  67. return "";

  68. }

  69.  
  70.  
  71.  
  72. }

 

 

        其中:

        1、我從第三方那要了一個demo,從中摘出來自己需要用的程式碼。

        2、簡訊介面有固定模板和變數模板, 這裡我們用到的是變數模板,因為驗證碼是個變數。

           

         3、介面文件裡給的很清楚:

            

            

 

         4、其中最後一步儲存,該手機號的驗證碼和傳送時間,用到了一個Map儲存。

           

private final static Map<String, TestCodeInforVo> testCodeInforMap = new HashMap<String,TestCodeInforVo>();

  

 

          傳送完驗證碼之後:

          

testCodeInforMap.put(phoneNumber,testCodeInfor);

         儲存到了map裡面,到時候找驗證碼和時間,也從這個map裡面找,手機號是key,這個儲存著驗證碼和時間的實體是value。

 

 

         簡訊驗證碼就到此告一段落。接下來看登陸的邏輯:

 

 

   登陸的過程:

                                      

 

          登陸程式碼:

           

 
  1. /**

  2. * 使用者登入介面

  3. * @param json 登入引數

  4. * @return 登入成功返回使用者資訊

  5. */

  6. @RequestMapping("/login")

  7. @ResponseBody

  8. public LoginResult login(@RequestParam(value="testCode",defaultValue="") String testCode,

  9. @RequestParam(value="identity",defaultValue="") String identity,

  10. @RequestParam(value="phone",defaultValue="") String phone, HttpServletRequest request){

  11.  
  12. //String serverPath = request.getScheme() + "://"+ request.getServerName() + ":" +

  13. // request.getServerPort()+request.getContextPath() + "/";

  14.  
  15. LoginResult result = new LoginResult();

  16. if( identity == null || identity.length() == 0 ){

  17. result.setState(Result.ERROR);

  18. result.setMessage("證件號為空");

  19. return result;

  20. }

  21. if(phone== null || phone.length() == 0 ){

  22. result.setState(Result.ERROR);

  23. result.setMessage("手機號為空");

  24. return result;

  25. }

  26. if( testCode == null || testCode.length() == 0 ){

  27. result.setState(Result.ERROR);

  28. result.setMessage("驗證碼為空");

  29. return result;

  30. }

  31. TestCodeInforVo testCodeInfor = (TestCodeInforVo) testCodeInforMap.get(phone);

  32. if( testCodeInfor == null || testCodeInfor.getCode() == null || testCodeInfor.getCode().length()==0 ){

  33. result.setState(Result.ERROR);

  34. result.setMessage("驗證碼不存在");

  35. return result;

  36. }

  37.  
  38. if(!testCode.equals(testCodeInfor.getCode())){

  39. result.setState(Result.ERROR);

  40. result.setMessage("驗證碼錯誤");

  41. return result;

  42. }

  43. testCodeInforMap.remove(phone);

  44. //驗證驗證碼是否過期

  45. if( System.currentTimeMillis()- testCodeInfor.getDate() > testCodeOutDate ){

  46. result.setState(Result.ERROR);

  47. result.setMessage("驗證碼已過期");

  48. return result;

  49. }

  50.  
  51. List<UserEntity> users = userService.getUserByPhoneIdentity(phone,identity);

  52. if( users.isEmpty()){

  53. result.setState(Result.ERROR);

  54. result.setMessage("使用者不存在");

  55. return result;

  56. }

  57. if( users.size() != 1){

  58. result.setState(Result.ERROR);

  59. result.setMessage("認證使用者不唯一");

  60. return result;

  61. }

  62. if( users.get(0).getAccountStatus() != null && users.get(0).getAccountStatus().equals("0")){

  63. result.setState(Result.ERROR);

  64. result.setMessage("該使用者被凍結");

  65. return result;

  66. }

  67. UserEntity user = users.get(0);

  68. user.setQrCode(user.getQrCode());

  69. user.setPersonalPhotos(user.getPersonalPhotos());

  70. user.setIdCardAvatarFace(user.getIdCardAvatarFace());

  71. user.setIdCardNationalEmblem(user.getIdCardNationalEmblem());

  72. String siteID="";

  73. //根據user的role去判斷該使用者所在的站點ID

  74. if (user.getRole()==0) {

  75. //0是管理員

  76. //根據使用者的ID去站點表裡查詢站點的最早新增的哪一個站點Id

  77. siteID=userService.findSiteIDByTimeAdmin(user.getId());

  78. }

  79. if(user.getRole()==2)//2是業主

  80. {

  81. //根據使用者的ID去站點表裡查詢站點的最早新增的哪一個站點Id

  82. siteID=userService.findSiteIDByTimeOwner(user.getId());

  83. }

  84. if (user.getRole()==1) {//1是營業員

  85. //營業員對應的,最早新增的哪一個站點Id

  86. siteID=userService.findSiteIDByTimeOwnerSale(user.getId());

  87. }

  88. user.setSiteID(siteID);

  89. result.setState(Result.SUCCESS);

  90. result.setMessage("登入成功");

  91. AppLoginUser appUser=new AppLoginUser();

  92. HttpSession session=request.getSession();

  93. appUser.setUserID(user.getId());

  94. appUser.setUserName(user.getName());

  95. appUser.setUserNum(user.getUserNumber());

  96. OrgStructure org=orgService.getOrgByAccount(user.getName());

  97. //appUser.setOrgId(org.getOrgId());

  98. session.setAttribute("appLoginUser", appUser);

  99. result.setData(user);

  100. return result;

  101. }

 

 

 

        其中:

        1、判斷驗證碼是否正確:(從剛才那個map裡面,根據手機號取值)

          

TestCodeInforVo testCodeInfor =  (TestCodeInforVo) testCodeInforMap.get(phone);

 

 

         從這個實體裡面取出驗證碼和時間。

 

         2、驗證碼是否過期:

          過期時間:

          

private final static long testCodeOutDate = 5*60*1000;  //驗證碼過期時間

 

 
  1. //驗證驗證碼是否過期

  2. if( System.currentTimeMillis()- testCodeInfor.getDate() > testCodeOutDate ){

  3. result.setState(Result.ERROR);

  4. result.setMessage("驗證碼已過期");

  5. return result;

  6. }

 

 

            驗證完之後刪除他:

         

testCodeInforMap.remove(phone);

 

 

          3、當初想的是存到session裡面會怎麼寫,還沒想好,希望路過的大神指導。

 

 

 小結:

      傳送驗證碼和登陸的邏輯之前覺得挺複雜的,當畫圖總結一遍之後,思路就清楚多了,還是要靜下心來多總結。