之前做过网易云信和无极限提供的SMS服务,有需要可以参考下:Java使用网易云信短信验证 demo(完整教程)
因项目需要,需利用阿里云SMS服务实现短信服务。下面给初次使用的朋友们分享记录一下。
帮助文档
- 阿里云官网 >>
- 阿里云短信服务文档使用指引 >>
- 短信签名与短信模板审核标准 >>
- 官方文档 >>
- 官方SDK&Dome下载 >>
操作实现
- 1、开通短信服务 >>
- 2、创建AccessKey >>
- 3、AccessKey ID 和 AccessKeySecret >>
- 4、添加签名 >>
- 5、添加模板 >>
- 6、Maven导入jar包 >>
- 7、封装工具类 >>
- 8、调用测试 >>
- 9、PostMan测试结果 >>
1、开通短信服务
2、创建AccessKey
3、AccessKey ID 和 AccessKeySecret
注意:保存AccessKeySecret,页面关闭后将无法再次获取信息 !
4、添加签名
5、添加模板
审核通过基本上就配置好了,接下来看下如何实现
6、Maven导入jar包
<dependency>
<groupId>aliyun.java.sdk</groupId>
<artifactId>core</artifactId>
<version>3.3.1</version>
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aliyun-java-sdk-core-3.3.1.jar</systemPath>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>aliyun.java.sdk</groupId>
<artifactId>dysmsapi</artifactId>
<version>1.0.0</version>
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aliyun-java-sdk-dysmsapi-1.0.0.jar</systemPath>
<scope>compile</scope>
</dependency>
7、封装工具类
package com.giantfind.common.util;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
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 java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Package: com.giantfind.common.util
* @ClassName: SmsUtils
* @Author: liuyaolong
* @Description: 短信API
* @Date: 2019/11/9 0009上午 10:49
* @Version: 1.0
*/
public class SmsUtils {
static final String system_name = "xxx系统";
//产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
//产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
static final String accessKeyId = "生成的accessKeyId";
static final String accessKeySecret = "生成的accessKeySecret";
private static int newcode;
public static int getNewcode() {
return newcode;
}
public static void setNewcode() {
newcode = (int) (Math.random() * 9999) + 100;
}
/**
* 发送手机验证码
* @param telephone
* @return
* @throws ClientException
*/
public static Map<String,String> sendSms(String telephone) throws ClientException {
Map<String,String> map = new HashMap<>();
map.put("telephone",telephone);
setNewcode();
String code = Integer.toString(getNewcode());
map.put("code",code);
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化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("输入签名名称");
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode("输入短信模板CODE");
//可选:模板中的变量替换JSON串,如模板内容为"您的验证码为${code}"时,您正在登录${product}。此处的值为
request.setTemplateParam("{\"code\":\""+code+"\",\"product\":\""+system_name+"\"}");
//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//request.setOutId("yourOutId");
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
map.put("result",sendSmsResponse.getCode());
return map;
}
/**
* "短信明细查询接口
* @param bizId (sendSms 返回 sendSmsResponse 里)
* @return
* @throws ClientException
*/
public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
QuerySendDetailsRequest request = new QuerySendDetailsRequest();
//必填-号码
request.setPhoneNumber("15000000000");
//可选-流水号
request.setBizId(bizId);
//必填-发送日期 支持30天内记录查询,格式yyyyMMdd
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
request.setSendDate(ft.format(new Date()));
//必填-页大小
request.setPageSize(10L);
//必填-当前页码从1开始计数
request.setCurrentPage(1L);
//hint 此处可能会抛出异常,注意catch
QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
return querySendDetailsResponse;
}
}
8、调用测试
package com.giantfind.business.web;
import com.aliyuncs.exceptions.ClientException;
import com.giantfind.business.model.sms.TelephoneInfo;
import com.giantfind.common.message.RequestMsg;
import com.giantfind.common.message.ResponseHead;
import com.giantfind.common.message.ResponseMsg;
import com.giantfind.common.util.SmsUtils;
import com.giantfind.common.util.ValidationUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* @Package: com.giantfind.business.web
* @ClassName: SmsController
* @Author: liuyaolong
* @Description: 短信消息推送
* @Date: 2019/11/9 0009下午 2:38
* @Version: 1.0
*/
@RestController
@RequestMapping("sms")
public class SmsController {
private static final Logger logger = Logger.getLogger(SmsController.class);
/**
* 发送手机短信验证码
* @param in
* @return
*/
@PostMapping("sendSms")
public ResponseMsg<Map<String,String>> sendSms(@RequestBody RequestMsg<TelephoneInfo> in) throws ClientException {
ResponseMsg<Map<String,String>> response = new ResponseMsg<>();
//自定义效验手机号
if(StringUtils.isBlank(in.getData().getTelephone())){
response.setHead(ResponseHead.buildFailedHead("手机号码不能为空!"));
return response;
}
if(in.getData().getTelephone().length() != 11){
response.setHead(ResponseHead.buildFailedHead("手机号码应为11位数!"));
return response;
}
if(ValidationUtils.isPhone(in.getData().getTelephone()) == false){
response.setHead(ResponseHead.buildFailedHead("手机号码有误!"));
return response;
}
Map<String,String> map = SmsUtils.sendSms(in.getData().getTelephone());
String code = map.get("result");
if(code!= null && code.equals("OK")){
response.setHead(ResponseHead.buildSuccessHead());
}else {
response.setHead(ResponseHead.buildFailedHead("短信发送失败!"));
}
response.setData(map);
return response;
}
}
9、PostMan测试结果
"data": {
"result": "OK",
"code": "5165",
"telephone": "13302943855"
}
以上就是本文的全部内容,希望对大家的学习有所帮助,欢迎评论交流。能get到知识点不要忘了关注点个赞~ 拒绝白嫖从我们做起hh~