import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import lombok.extern.slf4j.Slf4j; /** * 短信验证码发送工具类 */ @Slf4j public class SMSUtils { // 产品名称:云通信短信API产品 static final String product = "Dysmsapi"; // 产品域名 static final String domain = "dysmsapi.aliyuncs.com"; //此处需要替换成开发者自己的 private static final String accessKeyId = "********************"; private static final String accessKeySecret = "********************"; private static final String TEMPLATECODE = "********************"; //消息模板 private static final String SIGNNAME = "********************"; //签名 /** * 1、发送短信验证码 **/ public static SendSmsResponse sendSms(String telephone, String code) throws ClientException { //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); // 组装请求对象 SendSmsRequest request = new SendSmsRequest(); // 待发送手机号 request.setPhoneNumbers(telephone); // 必填:短信签名-可在短信控制台中找到 request.setSignName(SIGNNAME); // 短信模板-可在短信控制台中找到 request.setTemplateCode(TEMPLATECODE); // 模板中的变量替换JSON串 request.setTemplateParam("{\"code\":\"" + code + "\"}"); // hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){ log.info("短信发送成功!"); }else { log.info("短信发送失败!"); } return sendSmsResponse; } //获取六位数验证码 public static String getVerCode(){ return String.valueOf((int)(Math.random()*100000)+100000); } }
云通信短信验证码发送工具类
最新推荐文章于 2024-08-15 14:47:41 发布