SpringBoot整合阿里云短信服務的案例代碼
1. 準備工作
- 注冊阿里云賬號:首先確保你有一個阿里云賬號,并且已經(jīng)開通了短信服務。
- 獲取AccessKey ID和AccessKey Secret:在阿里云控制臺的安全管理頁面創(chuàng)建AccessKey,這是訪問阿里云API的憑證。
- 申請短信簽名和模板:在阿里云短信服務控制臺申請短信簽名和短信模板,簽名用于標識發(fā)送者的身份,模板用于定義短信內(nèi)容,需要審核通過才能使用。
2. 添加依賴
在Spring Boot項目的pom.xml
文件中添加阿里云短信服務SDK的依賴。例如:
<dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.6.0</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>2.1.0</version> </dependency>
3. 配置阿里云短信服務
在application.yml
或application.properties
中配置AccessKey ID、AccessKey Secret以及其他可能需要的參數(shù),例如:
sms: aliyun: accessKeyId: your-access-key-id accessKeySecret: your-access-key-secret signName: #### # 是否開啟短信服務 pushSms: true templateCode: SMS_#########
4. 創(chuàng)建配置類
package com.example.demo.config.sms; import com.aliyun.teaopenapi.models.*; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author xueyaoxuan */ @Data @Component @ConfigurationProperties(prefix = "sms.aliyun") public class AliYunSmsConfig { private String accessKeyId; private String accessKeySecret; private String signName; private boolean isPushSms; /** * 使用AK&SK初始化賬號Client * * @return Client * @throws Exception */ public com.aliyun.dysmsapi20170525.Client createClient() throws Exception { Config config = new Config() // AccessKey ID .setAccessKeyId(this.getAccessKeyId()) // AccessKey Secret .setAccessKeySecret(this.getAccessKeySecret()); // 訪問的域名 config.endpoint = "dysmsapi.aliyuncs.com"; return new com.aliyun.dysmsapi20170525.Client(config); } }
5. 創(chuàng)建服務類
創(chuàng)建一個服務類來封裝發(fā)送短信的邏輯
package com.example.demo.sms; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.aliyun.dysmsapi20170525.Client; import com.aliyun.dysmsapi20170525.models.SendSmsRequest; import com.aliyun.dysmsapi20170525.models.SendSmsResponse; import com.example.demo.config.sms.AliYunSmsConfig; import com.example.demo.config.ResultCode; import com.example.demo.exception.base.BaseException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; /** * 阿里云短信服務實現(xiàn) * @author xueyaoxuan */ @Slf4j @Component public class AliYunSmsServiceImpl implements SmsService { @Autowired AliYunSmsServiceImpl (AliYunSmsConfig aliYunSmsConfig) { this.aliYunSmsConfig = aliYunSmsConfig; } private AliYunSmsConfig aliYunSmsConfig; @Override public void sendSms(List<String> mobiles, String message, String code) { SendSmsResponse sendSmsResponse = null; try{ //調(diào)用阿里云api手機號上限1000 if (mobiles.size()>1000){ throw new BaseException(ResultCode.EM_SMS_MAX_LIMIT); } //檢驗手機號格式 mobiles.forEach(mobile->{ if (StrUtil.isAllEmpty(mobile)){ throw new BaseException(ResultCode.EM_SMS_INVALID_MOBILE); } }); sendSmsResponse = sendALiYunSms(mobiles.stream().collect(Collectors.joining(",")), message, code); log.info("阿里云短信服務響應:[{}]",JSON.toJSONString(sendSmsResponse)); } catch (Exception e) { e.printStackTrace(); } } /** * 發(fā)送阿里云短信 * * @param mobiles 手機號列表 * @param message json格式的模板參數(shù) * @param code 阿里云短信模板code * @return * @throws Exception */ private SendSmsResponse sendALiYunSms(String mobiles,String message,String code) throws Exception { //初始化Client對象 Client client = aliYunSmsConfig.createClient(); //構建請求參數(shù) SendSmsRequest sendSmsRequest = new SendSmsRequest() .setPhoneNumbers(mobiles) .setSignName(aliYunSmsConfig.getSignName()) .setTemplateCode(code) .setTemplateParam(message); //發(fā)送短信 return client.sendSms(sendSmsRequest); } }
6.自定義異常
package com.example.demo.config; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import java.io.Serializable; /** * ResultCode : 響應封裝實現(xiàn)類 * * @author zyw * @create 2023/6/15 */ @AllArgsConstructor @NoArgsConstructor public enum ResultCode implements IResultCode, Serializable { //短信發(fā)送次數(shù)超過限制 EM_SMS_MAX_LIMIT("10001","短信發(fā)送次數(shù)超過限制"), //無效的手機號碼 EM_SMS_INVALID_MOBILE("10002","無效的手機號碼"); @Override public String getCode() { return code; } @Override public String getMsg() { return msg; } private String code; private String msg; @Override public String toString() { return "{" + "\"code\":\"" + code + '\"' + ", \"msg\":\"" + msg + '\"' + '}'; } // 默認系統(tǒng)執(zhí)行錯誤 public static ResultCode getValue(String code) { for (ResultCode value : values()) { if (value.getCode().equals(code)) { return value; } } return ECEPTION; } }
7.使用服務類發(fā)送短信
在需要發(fā)送短信的地方注入SmsService
并調(diào)用其方法發(fā)送短信。
package com.example.demo.controller; import com.alibaba.fastjson.JSON; import com.example.demo.sms.SmsService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.annotation.Resource; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.Map; /** * SmsController : 短信控制器 * * @author zyw * @create 2024-06-11 15:56 */ @RestController @Tag(name = "短信控制器") @RequestMapping("sms") public class SmsController { @Resource private SmsService smsService; @Value("${sms.aliyun.templateCode}") private String templateCode; //發(fā)送短信 @Operation(summary = "單個手機號發(fā)送短信驗證碼") @PostMapping("/SendATextMessageByhone") public String SendATextMessageByhone(String mobile, String message) { Map<String, String> tempContentMap = new HashMap<>(); tempContentMap.put("code", String.valueOf(message)); smsService.sendSms(List.of(mobile), JSON.toJSONString(tempContentMap), templateCode); return "短信發(fā)送成功"; } }
請確保替換成你自己的AccessKey信息、簽名、模板CODE等,以及根據(jù)實際情況調(diào)整參數(shù)。此外,考慮到安全性,不要直接在版本控制系統(tǒng)中提交敏感信息,如AccessKey ID和AccessKey Secret,應使用環(huán)境變量或外部配置管理服務來管理這些信息。
8.測試短信
到此這篇關于SpringBoot整合阿里云短信服務的文章就介紹到這了,更多相關SpringBoot阿里云短信服務內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Mybatis時SqlSessionFactory對象總是報空指針
本文主要介紹了使用Mybatis時SqlSessionFactory對象總是報空指針,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-09-09Spring aop 如何通過獲取代理對象實現(xiàn)事務切換
這篇文章主要介紹了Spring aop 如何通過獲取代理對象實現(xiàn)事務切換的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07