1. 登录阿里云 - 搜索【短信服务】- 套餐【立即购买】
2. 添加签名
国内消息 - 签名管理 - 添加签名
3. 添加模板
国内消息 - 模板管理 - 添加模板
模板详细
4. 依赖
<!--阿里云短信服务-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.22</version>
</dependency>
5. SmsUtils
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
public class SmsUtils {
private static final String accessKeyId = "你的accessKeyId ";
private static final String accessKeySecret = "你的accessKeySecret ";
private static Client createClient() throws Exception {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// 固定
config.endpoint="dysmsapi.aliyuncs.com";
return new Client(config);
}
public static SendSmsResponse sendSms(String signName,String templateCode,String phoneNUmber,String templateParam) {
Client client = null;
try {
client = createClient();
SendSmsRequest sendSmsRequest = new SendSmsRequest();
// 模板code
sendSmsRequest.setTemplateCode(templateCode);
// 关联签名 (获取: 签名管理 - 签名名称)
sendSmsRequest.setSignName(signName);
// 用户手机号
sendSmsRequest.setPhoneNumbers(phoneNUmber);
// 发送的内容
sendSmsRequest.setTemplateParam(templateParam);
SendSmsResponse response = client.sendSms(sendSmsRequest);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
6. service
public void sendSms(){
// 用户手机号
String phoneNumber = wxUser.getPhoneNumber();
// 关联签名 (获取: 签名管理 - 签名名称)
String signName ="心理树服务通知";
// 模板code
String templateCode = "SMS_xxxxxxxxx";
// 发送内容
JSONObject param = new JSONObject();
param.set("name",wxUser.getAliasName());
param.set("time1",order.getSettingDate()+" "+startTime);
param.set("time2",endTime);
param.set("expert",order.getExpertName());
SendSmsResponse sendSmsResponse = SmsUtils.sendSms(signName,templateCode,phoneNumber,param.toString());
log.info("短信响应message: {},短信响应code: {}",sendSmsResponse.getBody().message,sendSmsResponse.getBody().code);
}
7. 短信通知