1. 注册并实名认证
进入阿里云官网进行注册并实名认证:阿里云权益中心_助力学生、开发者、企业用云快速上云-阿里云
2. 注册 AccessKey
AccessKey ID 和 AccessKey Secret 是我们访问阿里云 API 的密钥,具有该账户完全的权限,需要妥善保管
3. 开通短信服务
阿里云短信服务申请官网:短信服务_企业短信营销推广_验证码通知-阿里云
购买完成后,进入短信控制台
需要将上图中的申请填写一遍
1) 申请资质
2) 申请签名
不要有汉字,否则可能会有错误
3) 申请模板
4. 两种测试方式
4.1 在测试之前需要先绑定手机号
4.2 测试发送
控制台发送:
API 发送:
5. 集成短信服务到项目
阿里云短信服务使用 API 文档:短信服务SDK下载和安装_短信服务(SMS)-阿里云帮助中心
这里以 Java SDK 为示例
如果是 Maven 项目的话,将上述代码片段拷贝到 pom.xml 中即可
6. 示例代码
配置 application.properties
## 短信 ##
sms.access-key-id=填写⾃⼰申请的
sms.access-key-secret=填写⾃⼰申请的
sms.sign-name=填写⾃⼰申请的,此处尽量不要有汉字
SMSUtil
package com.example.lotterysystem.common.utils;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class SMSUtil {
private static final Logger logger = LoggerFactory.getLogger(SMSUtil.class);
@Value(value = "${sms.sign-name}")
private String signName;
@Value(value = "${sms.access-key-id}")
private String accessKeyId;
@Value(value = "${sms.access-key-secret}")
private String accessKeySecret;
/**
* 发送短信
*
* @param templateCode 模板号
* @param phoneNumbers 手机号
* @param templateParam 模板参数 {"key":"value"}
*/
public void sendMessage(String templateCode, String phoneNumbers, String templateParam) {
try {
Client client = createClient();
com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setSignName(signName)
.setTemplateCode(templateCode)
.setPhoneNumbers(phoneNumbers)
.setTemplateParam(templateParam);
RuntimeOptions runtime = new RuntimeOptions();
SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
if (null != response.getBody()
&& null != response.getBody().getMessage()
&& "OK".equals(response.getBody().getMessage())) {
logger.info("向{}发送信息成功,templateCode={}", phoneNumbers, templateCode);
return;
}
logger.error("向{}发送信息失败,templateCode={},失败原因:{}",
phoneNumbers, templateCode, response.getBody().getMessage());
} catch (TeaException error) {
logger.error("向{}发送信息失败,templateCode={}", phoneNumbers, templateCode, error);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
logger.error("向{}发送信息失败,templateCode={}", phoneNumbers, templateCode, error);
}
}
/**
* 使用AK&SK初始化账号Client
* @return Client
*/
private Client createClient() throws Exception {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
// 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
}
SMSTest
package com.example.lotterysystem;
import com.example.lotterysystem.common.utils.SMSUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class SMSTest {
@Autowired
private SMSUtil smsUtil;
@Test
void smsTest() {
smsUtil.sendMessage("SMS_478385001", "在阿里云短信控制台绑定过的手机号", "{\"code\":\"1234\"}");
}
}
运行结果: