阿里云短信服务实现
首先,引入依赖:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.24</version>
</dependency>
下面演示的是阿里云的短信服务
先写一个配置类:
package com.etc.thridparty.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SmsConfig {
@Value("${aliyun.accessKey.id}")
private String accessKeyId;
@Value("${aliyun.accessKey.secret}")
private String accessKeySecret;
@Value("${aliyun.accessKey.endpoint}")
private String endpoint;
@Bean
public com.aliyun.dysmsapi20170525.Client smsClient() throws Exception{
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
config.endpoint = endpoint;
return new com.aliyun.dysmsapi20170525.Client(config);
}
}
发送短信功能前,需要在阿里云上获取短信模版的templateCode,以及签名signName
package com.etc.thridparty.service.impl;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.etc.thridparty.service.ISmsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class SmsServiceImpl implements ISmsService {
@Value("${aliyun.sms.signName}")
private String signName;
@Value("${aliyun.sms.templateCode}")
private String templateCode;
@Autowired
private Client smsClient;
@Override
public void sendSmsCode(String phone, String code) {
com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
.setSignName(signName)
.setTemplateCode(templateCode)
.setPhoneNumbers(phone)
.setTemplateParam("{\"code\":\""+code+"\"}");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
SendSmsResponse response = smsClient.sendSmsWithOptions(sendSmsRequest, runtime);
ObjectMapper mapper =new ObjectMapper();
String json = mapper.writeValueAsString(response.getBody());
System.out.println(json);
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}