JAVA-阿里云短信服务
执断剑披荆斩棘 人气:21、引入相关依赖
<!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <https://img.qb5200.com/download-x/dependency> <!--hutool--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.5.2</version> <https://img.qb5200.com/download-x/dependency> <!--短信--> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.0.6</version> <!-- 注:如提示报错,先升级基础包版,无法解决可联系技术支持 --> <https://img.qb5200.com/download-x/dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.1.0</version> <https://img.qb5200.com/download-x/dependency>
2、JAVA代码
import cn.hutool.json.JSONUtil; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.ruoyi.kkxapi.common.service.H5CommonService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.Map; @Slf4j @Service public class H5CommonServiceImpl implements H5CommonService { /** * 发送短信 * * @return */ @Override public SendSmsResponse sendSms(String phoneNumbers, String templateCode, Map<String, Object> map) throws Exception { //设置超时时间-可自行调整 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); final String product = "Dysmsapi"; final String domain = "dysmsapi.aliyuncs.com"; final String accessKeyId = "----"; final String accessKeySecret = "----"; IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); //组装请求对象 SendSmsRequest sendSmsRequest = new SendSmsRequest(); sendSmsRequest.setMethod(MethodType.POST); //必填:待发送手机号。支持以逗号分隔的形式进行批量调用 sendSmsRequest.setPhoneNumbers(phoneNumbers); sendSmsRequest.setSignName("----"); sendSmsRequest.setTemplateCode(templateCode); sendSmsRequest.setTemplateParam(JSONUtil.toJsonStr(map)); SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(sendSmsRequest); log.info("------" + phoneNumbers + "--------" + templateCode + "---短信返回结果---" + sendSmsResponse.getCode() + sendSmsResponse.getMessage()); return sendSmsResponse; } }
3、测试
map中的key对应短信模板中的变量属性
@Test public void smsTest() throws Exception {
//获取短信模板CODE String appConfigCode = "SMS_PSM"; AppConfig appConfig = appConfigService.getConfigByCode(appConfigCode);
//短信模板参数 Map<String, Object> map = new HashMap<>(); String code = String.valueOf((int) (Math.random() * 900000 + 100000)); map.put("code", code); map.put("name", "李四"); commonService.sendSms("----", appConfig.getAValue(), map); }
加载全部内容