天天看點

微信小程式中短信驗證碼登入全流程及代碼

短信驗證碼實作流程

1、構造手機驗證碼,生成一個6位的随機數字串;

2、使用接口向短信平台發送手機号和驗證碼,然後短信平台再把驗證碼發送到制定手機号上

3、将手機号驗證碼、操作時間存入Session,redis中,作為後面驗證使用;

4、接收使用者填寫的驗證碼、手機号及其他注冊資料;

5、對比送出的驗證碼與Session,redis中的驗證碼是否一緻,同時判斷送出動作是否在有效期内;

6、驗證碼正确且在有效期内,請求通過,處理相應的業務。

package com.foen.utils;


import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


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.HttpRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.foen.car.dto.BaseResultDto;
import com.foen.car.service.RedisService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 手機短信通信類
 * @auther: 作者 gzh
 * @description: 類說明
 * @Date: created in 9:45 2020/5/27
 */
public class MoblieMessageUtil {

    private static final Logger logger = LoggerFactory.getLogger(MoblieMessageUtil.class);
    // 産品名稱:雲通信短信API産品,開發者無需替換
    private static final String product = "Dysmsapi";
    private static final String domain = "dysmsapi.aliyuncs.com";

    // 此處需要替換成開發者自己的AK(在阿裡雲通路控制台尋找)
    private static String accessKeyId = "---";
    private static String accessKeySecret = "---";
    private static String signName = "--";
    private static String identifyingTempleteCode = "{\"code\":\"1111\"}";
    private static String registTempleteCode = "---";


    public static BaseResultDto sendSmsCode(String tel, String code, HttpServletRequest httpServletRequest) {
        BaseResultDto baseResultDto = Utils.baseDefaultResultMessageError();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        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");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", tel);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", registTempleteCode);
        request.putQueryParameter("TemplateParam","{\"code\":"+code+"}" );
        request.putQueryParameter("SmsUpExtendCode", code);
        try {
            CommonResponse response = client.getCommonResponse(request);

            logger.info("==>"+response.getData());
            if(response.getData().indexOf("OK")!=-1){
                baseResultDto=Utils.renderBaseResultDtoSuccess("短信發送成功");
            }else{
                baseResultDto=Utils.renderBaseResultDtoError(response.getData());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return  baseResultDto;
    }


    /**
     * 儲存資料到session
     * @param request
     * @param code
     * @param phone
     */
    private static void setSendSmsCode(HttpServletRequest request,String code,String phone){
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(Constants.CRM_STR+phone, code);
        try {
            final Timer timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    String yxcode1 =  (String) session.getAttribute(Constants.CRM_STR+phone);
                    if(StringUtils.isNotEmpty(yxcode1)){
                        session.removeAttribute(Constants.CRM_STR+phone);
                    }
                    timer.cancel();
                }
            },Constants.SIGN_EXPIRED_TIME);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void setRegistData(RedisService service, String phone, String code){
        service.setValue(Constants.CRM_STR+phone,code);
        service.setValue(Constants.CRM_TIME+phone,DateUtils.dateToStringFromat());
        try {
            //TimerTask實作5分鐘後從session.resdis中删除checkCode
            final Timer timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    String phone_ =  service.getValue(Constants.CRM_STR+phone);
                    String vcode_ =  service.getValue(Constants.CRM_TIME+phone);
                    if(StringUtils.isNotEmpty(phone_)){
                        service.delete(Constants.CRM_STR+phone);
                    }
                    if(StringUtils.isNotEmpty(vcode_)){
                        service.delete(Constants.CRM_TIME+phone);
                    }
                    timer.cancel();
                }
            },Constants.SIGN_EXPIRED_TIME);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}      

短信通信類

短信驗證碼實作流程

1、構造手機驗證碼,生成一個6位的随機數字串;

2、使用接口向短信平台發送手機号和驗證碼,然後短信平台再把驗證碼發送到制定手機号上

3、将手機号驗證碼、操作時間存入Session,redis中,作為後面驗證使用;

4、接收使用者填寫的驗證碼、手機号及其他注冊資料;

5、對比送出的驗證碼與Session,redis中的驗證碼是否一緻,同時判斷送出動作是否在有效期内;

6、驗證碼正确且在有效期内,請求通過,處理相應的業務。

//構造手機驗證碼,生成一個6位的随機數字串;
public static String runNumber() {
   String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   StringBuilder sb=new StringBuilder(4);
   for(int i=0;i<6;i++)
   {
      char ch=str.charAt(new Random().nextInt(str.length()));
      sb.append(ch);
   }
   System.out.println(sb.toString());
   String code = sb.toString();
   return code;
}      

參考:

阿裡短信通

​​https://help.aliyun.com/document_detail/101893.html?spm=a2c4g.11186623.6.649.37f460e2WewZdf​​