目录
三、获取账户的AccessKey ID 和 AccessKey Secret,并给予账户相应权限
一、关键点
- 获取阿里云短信服务依赖
- 获取账户的AccessKey ID 和 AccessKey Secret,并给予账户相应权限
- 添加短信模板,和公司签名
- 根据阿里云提供的代码进行测试
二、获取阿里云短信服务依赖
- 阿里云官网获取
三、获取账户的AccessKey ID 和 AccessKey Secret,并给予账户相应权限
- 创建子账号
创建完成后会提供账户的AccessKey ID 和 AccessKey Secret,只会提供一次记得保存 - 给账号添加短信服务的权限
四、添加短信模板,和签名
- 在阿里云主页搜索短信服务,打开短信控制台
- 创建短信模板获取短信CODE
- 获取签名名称
五、实操
- 在配置文件中加入相关信息
zxs: #阿里云短信登录相关参数 SMS: sccessKey-id: LTA*************** accessKey-secret: YV********* template-code: SMS_168****** #短信模板 sign-name: 我爱敲代码1 #签名名称
- 将相关信息填入阿里云提供的代码里,下面是我自己修改过的代码
@Component public class SMSUtils { @Value("${zxs.SMS.sccessKey-id}") private String accessKeyId; @Value("${zxs.SMS.accessKey-secret}") private String accessKeySecret; @Value("${zxs.SMS.template-code}") private String templateCode; @Value("${zxs.SMS.sign-name}") private String signName; /** * 使用AK&SK初始化账号Client * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception { com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config() // 必填,您的 AccessKey ID .setAccessKeyId(accessKeyId) // 必填,您的 AccessKey Secret .setAccessKeySecret(accessKeySecret); // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi config.endpoint = "dysmsapi.aliyuncs.com"; return new com.aliyun.dysmsapi20170525.Client(config); } /** * 发送短信验证码 * */ public boolean sendMessage(String phoneNumber,String code){ boolean flag=false; try { com.aliyun.dysmsapi20170525.Client client = createClient(accessKeyId, accessKeySecret); com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest() .setSignName(signName) .setTemplateCode(templateCode) .setPhoneNumbers(phoneNumber) .setTemplateParam("{\"code\":\""+code+"\"}"); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); System.out.println(accessKeyId); System.out.println(accessKeySecret); System.out.println(templateCode); System.out.println(signName); System.out.println(phoneNumber); // 复制代码运行请自行打印 API 的返回值 client.sendSmsWithOptions(sendSmsRequest, runtime); flag=true; } catch (TeaException error) { throw new BusinessRuntimeException(error.getCode(),error.getMessage()); } catch (Exception _error) { throw new BusinessRuntimeException(_error.getMessage()); } return flag; } }