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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值