SpringBoot實現(xiàn)阿里云短信發(fā)送的示例代碼
阿里云accessID和secret請自行進入阿里云申請
sms.template.code
請進入阿里云,進行短信服務(wù)進行魔板添加
開源代碼地址在文章末尾
話不多說,直接上代碼:
application.properties:
server.port=8002 #server.servlet.context-path=/ spring.datasource.url=jdbc:mysql://localhost:3306/ssm_message?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=19961117Lhh spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #開啟駝峰命名 mybatis.configuration.map-underscore-to-camel-case=true #設(shè)置超時時間-可自行調(diào)整 sms.default.connect.timeout=sun.net.client.defaultConnectTimeout sms.default.read.timeout=sun.net.client.defaultReadTimeout sms.timeout=10000 #初始化ascClient需要的幾個參數(shù) #短信API產(chǎn)品名稱(短信產(chǎn)品名固定,無需修改) sms.product=Dysmsapi #短信API產(chǎn)品域名(接口地址固定,無需修改) sms.domain=dysmsapi.aliyuncs.com #替換成你的AK (產(chǎn)品密) #你的accessKeyId,填你自己的 上文配置所得 自行配置 sms.access.key.id=xxxx #你的accessKeyId,填你自己的 上文配置所得 自行配置 sms.access.key.secret=xxxx #阿里云配置你自己的短信模板填入 sms.template.code=SMS_238470888
messageController
package com.example.demo.controller;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.example.demo.service.MessageService;
import com.example.demo.utils.MessageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@Api(description = "短信接口")
@RequestMapping("/smsLogin")
@RestController
public class MessageController {
@Autowired
public MessageService messageService;
@Autowired
public MessageUtils messageUtils;
@ApiOperation(value = "獲取短信驗證碼接口", notes = "獲取短信驗證碼接口")
@GetMapping("/sendMessage")
public Map<String, Object> getSMSMessage(String phone) {
Map<String, Object> map = new HashMap<>();
if (phone == null || phone == "") {
map.put("code", "FAIL");
map.put("msg", "手機號為空");
return map;
}
Map smsMap = messageUtils.getPhoneMsg(phone);
if("OK".equals(smsMap.get("status"))){
Map data = messageService.selectSMSDataByPhone(phone);
map.put("phone", phone);
map.put("smsCode", smsMap.get("msg"));
// 將驗證碼存入數(shù)據(jù)庫 也可以考慮用redis等方式 這里就用數(shù)據(jù)庫做例子
if (data != null) {
messageService.updateSMSDataByPhone(map);
} else {
messageService.insert(map);
}
smsMap.put("msg", "成功");
}
return smsMap;
}
@ApiOperation(value = "短信校驗登錄接口", notes = "短信校驗登錄接口")
@GetMapping("/login")
public Map<String, Object> login(String phone, String smsCode) {
Map<String, Object> map = new HashMap<>();
if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(smsCode)) {
map.put("code", "FAIL");
map.put("msg", "請檢查數(shù)據(jù)");
return map;
}
// 取出對應(yīng)的驗證碼進行比較即可
Map smsMap = messageService.selectSMSDataByPhone(phone);
if (smsMap == null) {
map.put("code", "FAIL");
map.put("msg", "該手機號未發(fā)送驗證碼");
return map;
}
String code = (String) smsMap.get("sms_code");
if (!smsCode.equals(code)) {
map.put("code", "FAIL");
map.put("msg", "驗證碼不正確");
return map;
}
map.put("code", "OK");
map.put("msg", "success");
return map;
}
}
MessageUtils
package com.example.demo.utils;
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.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Component
public class MessageUtils {
@Autowired
RestTemplate restTemplate;
@Value("${sms.default.connect.timeout}")
private String DEFAULT_CONNECT_TIMEOUT;
@Value("${sms.default.read.timeout}")
private String DEFAULT_READ_TIMEOUT;
@Value("${sms.timeout}")
private String SMS_TIMEOUT;
@Value("${sms.product}")
private String SMS_PRODUCT;
@Value("${sms.domain}")
private String SMS_DOMAIN;
@Value("${sms.access.key.id}")
private String SMS_ACCESSKEYID;
@Value("${sms.access.key.secret}")
private String SMS_ACCESSKEYSECRET;
@Value("${sms.template.code}")
private String TEMPLATE_CODE;
private static String code;//code對應(yīng)你短信目標里面的參數(shù)
public Map getPhoneMsg(String phone) {
if (phone == null || phone == "") {
System.out.println("手機號為空");
return null;
}
// 設(shè)置超時時間-可自行調(diào)整
System.setProperty(DEFAULT_CONNECT_TIMEOUT, SMS_TIMEOUT);
System.setProperty(DEFAULT_READ_TIMEOUT, SMS_TIMEOUT);
// 初始化ascClient需要的幾個參數(shù)
final String product = SMS_PRODUCT;
final String domain = SMS_DOMAIN;
// 替換成你的AK
final String accessKeyId = SMS_ACCESSKEYID;
final String accessKeySecret = SMS_ACCESSKEYSECRET;
// 初始化ascClient,暫時不支持多region
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
accessKeyId, accessKeySecret);
Map map = new HashMap();
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product,
domain);
//獲取驗證碼
code = vcode();
IAcsClient acsClient = new DefaultAcsClient(profile);
// 組裝請求對象
SendSmsRequest request = new SendSmsRequest();
// 使用post提交
request.setMethod(MethodType.POST);
// 必填:待發(fā)送手機號。支持以逗號分隔的形式進行批量調(diào)用,批量上限為1000個手機號碼,批量調(diào)用相對于單條調(diào)用及時性稍有延遲,驗證碼類型的短信推薦使用單條調(diào)用的方式
request.setPhoneNumbers(phone);
// 必填:短信簽名-可在短信控制臺中找到
request.setSignName("java學(xué)習(xí)");
// 必填:短信模板-可在短信控制臺中找到
request.setTemplateCode(TEMPLATE_CODE);
// 可選:模板中的變量替換JSON串,如模板內(nèi)容為"親愛的${name},您的驗證碼為$[code]"時,此處的值為
// 友情提示:如果JSON中需要帶換行符,請參照標準的JSON協(xié)議對換行符的要求,比如短信內(nèi)容中包含\r\n的情況在JSON中需要表示成\\r\\n,否則會導(dǎo)致JSON在服務(wù)端解析失敗
request.setTemplateParam("{ \"code\":\"" + code + "\"}");
// 可選-上行短信擴展碼(無特殊需求用戶請忽略此字段)
// request.setSmsUpExtendCode("90997");
// 可選:outId為提供給業(yè)務(wù)方擴展字段,最終在短信回執(zhí)消息中將此值帶回給調(diào)用者
request.setOutId("yourOutId");
// 請求失敗這里會拋ClientException異常
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
map.put("status", sendSmsResponse.getCode());
if (sendSmsResponse.getCode() != null
&& sendSmsResponse.getCode().equals("OK")) {
// 請求成功
map.put("msg", code);
} else {
//如果驗證碼出錯,會輸出錯誤碼告訴你具體原因
map.put("msg", sendSmsResponse.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
map.put("status", "FAIL");
map.put("msg", "獲取短信驗證碼失敗");
}
return map;
}
/**
* 生成6位隨機數(shù)驗證碼
*
* @return
*/
public static String vcode() {
String vcode = "";
for (int i = 0; i < 6; i++) {
vcode = vcode + (int) (Math.random() * 9);
}
return vcode;
}
}
主要代碼已貼上
具體開源代碼:
以上就是SpringBoot實現(xiàn)阿里云短信發(fā)送的示例代碼的詳細內(nèi)容,更多關(guān)于SpringBoot阿里云短信發(fā)送的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java工廠實例BeanFactoryPostProcessor和BeanPostProcessor區(qū)別分析
這篇文章主要為大家介紹了BeanFactoryPostProcessor和BeanPostProcessor區(qū)別示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
WPF實現(xiàn)自定義一個自刪除的多功能ListBox
這篇文章主要為大家詳細介紹了如何利用WPF實現(xiàn)自定義一個自刪除的多功能ListBox,文中示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-12-12

