短信服务(Short Message Service)是阿里云为用户提供的一种通信服务的能力。
支持向国内和国际快速发送验证码、短信通知和推广短信,服务范围覆盖全球200多个国家和地区。国内短信支持三网合一专属通道,与工信部携号转网平台实时互联。电信级运维保障,实时监控自动切换,到达率高达99%。完美支撑双11期间20亿短信发送,6亿用户触达。
(1) 获取accessId, accessSecret
- 登录阿里云,点击AccessKey管理进入,进入该页面后点击开始使用子用户AccessKey,接着选择创建用户组的相关信息和添加相关的短信服务的权限
- 对用户组进行创建并添加权限后,则需要创建用户,
(2) 自定义签名,模板id,模板参数
-
进入短信服务管理控制台,在国内消息的模板管理中选择添加模板(按照给定提示添加即可)
-
在签名管理中点击添加签名,并在适用场景中选中验证码即可,最后等待审查结果通过就行了
(3) 调用相关的API接口进行发送数据
- 在快速学习中点击查看API,其中便有关于短信发送的API和相应的测试
- 添加相应的数据并进行测试
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
/*
pom.xml
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.3</version>
</dependency>
*/
public class SendSms {
public static void main(String[] args) {
//<accessKeyId>、<accessSecret>添加上第一步中生成好的id和secret即可
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
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");
request.putQueryParameter("PhoneNumbers", "18345226593");
request.putQueryParameter("SignName", "culture");
request.putQueryParameter("TemplateCode", "SMS_185455534");
request.putQueryParameter("TemplateParam", "{\"code\":\"2333\"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
注:如果发送失败,有可能是你的阿里云账号没有钱,我第一次测试发送时也是直接报错,结果充钱就可以发送了。或者可能是在创建用户组时没有添加上短信服务的相关权限