java阿里雲發送短信驗證碼

記錄一下我項目中寫的 發送驗證碼的代碼。

    @RequestMapping(value = "org/verification",method = RequestMethod.GET)
    public void getVerificationCode(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "phone_number") String phoneNumber){
        String sessionVerificationCode = (String) request.getSession().getAttribute(phoneNumber);
        if(sessionVerificationCode!=null){
            String[] codes = sessionVerificationCode.split("-");
            Long createTime =Long.parseLong(codes[1]);
            Long nowTime = System.currentTimeMillis();
            if(nowTime-createTime>60000){
                response.setHeader("status","400");
                return;
            }
        }
        DefaultProfile profile = DefaultProfile.getProfile("default", AliConstans.ACCESS_KEY_ID, AliConstans.ACCESS_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        String code = AliConstans.getVerificationCode();
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setMethod(MethodType.POST);
        commonRequest.setDomain("dysmsapi.aliyuncs.com");
        commonRequest.setVersion("2019-08-12");
        commonRequest.setAction("SendSms");
        commonRequest.putQueryParameter("RegionId", "default");
        commonRequest.putQueryParameter("PhoneNumbers", phoneNumber);
        commonRequest.putQueryParameter("SignName", AliConstans.SIGN_NAME);
        commonRequest.putQueryParameter("TemplateCode", AliConstans.TEMPLATE_CODE);
        commonRequest.putQueryParameter("TemplateParam","{\"code\":\""+code+"\"}");
        try{
            CommonResponse commonResponse = client.getCommonResponse(commonRequest);
            request.getSession().setAttribute(phoneNumber,code+"-"+System.currentTimeMillis());
            response.setHeader("status","200");
            System.out.println(commonResponse.getData());
        } catch (ClientException e){
            e.printStackTrace();
            response.setHeader("status","500");
        }
    }
package com.sansanhealth.content;

import java.util.Random;

public class AliConstans {
    /**
     * Ram賬號的AccessKey ID
     */
    public static final String ACCESS_KEY_ID="";
    /**
     * RAM賬號AccessKey Secret
     */
    public static final String ACCESS_SECRET="";
    /**
     * 短信簽名
     */
    public static final String SIGN_NAME="";

    /**
     * 短信模板id
     */
    public static final String TEMPLATE_CODE="";

    public static String getVerificationCode(){

        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章