美文网首页
阿里云短信验证码发送

阿里云短信验证码发送

作者: 雨易辰木 | 来源:发表于2020-05-20 09:56 被阅读0次

    亲测可用,需要先申请短信签名喝模板,模板的参数一定要设

    /**

    *

    * 阿里短信验证码发送

    * */

    public Map send(String mobile)throws Exception, ServerException {

    Map map =new HashMap();

    //accessKeyId,secret填入自己的

    DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",accessKeyId,secret);

    IAcsClient client =new DefaultAcsClient(profile);

    CommonRequest request =new CommonRequest();

    request.setMethod(MethodType.POST);

    request.setDomain("dysmsapi.aliyuncs.com");

    request.setVersion("2017-05-25");

    request.setAction("SendSms");

    request.putQueryParameter("RegionId","cn-hangzhou");

    //mobile 手机号

    request.putQueryParameter("PhoneNumbers", mobile);

    //自己的签名

    request.putQueryParameter("SignName","XXXXX");

    //短信模板签名

    request.putQueryParameter("TemplateCode","SMS_XXXXX");

    //随机生成6位数验证码

    String randomCode = getRandomCode();

    request.putQueryParameter("TemplateParam","{\"code\":\""+randomCode+"\"}");

    String code ="";

    try {

    CommonResponse response = client.getCommonResponse(request);

            code = com.alibaba.fastjson.JSONObject.parseObject(response.getData()).getString("Code");

    }catch (com.aliyuncs.exceptions.ServerException e) {

    e.printStackTrace();

    }catch (ClientException e) {

    e.printStackTrace();

    }

    if(code!=null && code.equals("OK")){

    map.put("randomCode",randomCode);

    map.put("code","0000");

    map.put("codemsg","短信发送成功");

    }else {

    map.put("randomCode",randomCode);

    map.put("code","9999");

    map.put("codemsg","短信发送失败");

    }

    return map;

    }

    /**

    * 随机生成6位验证码

    * @return

    */

    private String getRandomCode(){

    Random random =new Random();

    StringBuffer result=new StringBuffer();

    for (int i=0;i<6;i++){

    result.append(random.nextInt(10));

    }

    return result.toString();

    }

    相关文章

      网友评论

          本文标题:阿里云短信验证码发送

          本文链接:https://www.haomeiwen.com/subject/fgiquctx.html