日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

阿里和云之讯短信发送服务

發布時間:2023/12/20 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 阿里和云之讯短信发送服务 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

  • 1 云之訊短信驗證碼
    • 1.1 創建應用
    • 1.2 創建短信模板
    • 1.3 發送短信api
    • 1.4 編寫代碼
    • 1.5 編寫測試用例
    • 1.6 編寫接口服務
  • 2 阿里云短信服務
    • 2.1 申請簽名與模板
    • 2.2 設置用戶權限
    • 2.3 示例代碼
    • 2.4 實現發送短信方法


1 云之訊短信驗證碼

短信驗證碼選用云之訊第三方短信平臺:https://www.ucpaas.com/

選擇原因:注冊贈送10元,無實名認證也可以發驗證碼短信。現在也沒了3元好像

1.1 創建應用

自行注冊、登錄后進行創建應用:

默認情況下,短信只能發送給自己注冊的手機號,為了測試方便需要添加測試手機號(最多6個):

1.2 創建短信模板

發送短信需要創建短信模板,模板中采用{1}、{2}的形式作為參數占位。

模板處于待審核狀態是不可以使用的,需要審核通過后才能使用,審核通過后會有短信通知。

1.3 發送短信api

地址:http://docs.ucpaas.com/doku.php?id=%E7%9F%AD%E4%BF%A1:sendsms

1.4 編寫代碼

配置RestTemplateConfig:

package com.oldlu.sso.config;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import org.springframework.http.converter.StringHttpMessageConverter;import java.nio.charset.Charset;@Configuration public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory) {RestTemplate restTemplate = new RestTemplate(factory);// 支持中文編碼restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));return restTemplate;}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory() {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(5000);//單位為msfactory.setConnectTimeout(5000);//單位為msreturn factory;} }

編寫SmsService:

package com.oldlu.sso.service;import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate;import java.io.IOException; import java.util.HashMap; import java.util.Map;@Service public class SmsService {@Autowiredprivate RestTemplate restTemplate;private static final ObjectMapper MAPPER = new ObjectMapper();/*** 發送驗證碼短信** @param mobile*/public String sendSms(String mobile) {String url = "https://open.ucpaas.com/ol/sms/sendsms";Map<String, Object> params = new HashMap<>();params.put("sid", "*******");params.put("token", "*******");params.put("appid", "*******");params.put("templateid", "*****");params.put("mobile", mobile);// 生成4位數驗證 如果是多個參數用,分隔params.put("param", RandomUtils.nextInt(100000, 999999));ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, params, String.class);String body = responseEntity.getBody();try {JsonNode jsonNode = MAPPER.readTree(body);//000000 表示發送成功if (StringUtils.equals(jsonNode.get("code").textValue(), "000000")) {return String.valueOf(params.get("param"));}} catch (IOException e) {e.printStackTrace();}return null;}}

1.5 編寫測試用例

package com.oldlu.sso.service;import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@SpringBootTest @RunWith(SpringJUnit4ClassRunner.class) public class TestSmsService {@Autowiredprivate SmsService smsService;@Testpublic void sendSms(){this.smsService.sendSms("158****7944");} }

1.6 編寫接口服務

編寫ErrorResult:

package com.oldlu.sso.vo;import lombok.Builder; import lombok.Data;@Data @Builder public class ErrorResult {private String errCode;private String errMessage; }

SmsController:

package com.oldlu.sso.controller;import com.oldlu.sso.service.SmsService; import com.oldlu.sso.vo.ErrorResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import java.util.Map;@RestController @RequestMapping("user") public class SmsController {private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);@Autowiredprivate SmsService smsService;/*** 發送驗證碼** @return*/@PostMapping("login")public ResponseEntity<Object> sendCheckCode(@RequestBody Map<String, Object> param) {ErrorResult.ErrorResultBuilder resultBuilder = ErrorResult.builder().errCode("000000").errMessage("發送短信驗證碼失敗");try {String phone = String.valueOf(param.get("phone"));Map<String, Object> sendCheckCode = this.smsService.sendCheckCode(phone);int code = ((Integer) sendCheckCode.get("code")).intValue();if (code == 3) {return ResponseEntity.ok(null);}else if(code == 1){resultBuilder.errCode("000001").errMessage(sendCheckCode.get("msg").toString());}} catch (Exception e) {LOGGER.error("發送短信驗證碼失敗", e);}return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());}}

SmsService:

package com.oldlu.sso.service;import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate;import java.io.IOException; import java.time.Duration; import java.util.HashMap; import java.util.Map;@Service public class SmsService {private static final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);@Autowiredprivate RestTemplate restTemplate;private static final ObjectMapper MAPPER = new ObjectMapper();@Autowiredprivate RedisTemplate<String, String> redisTemplate;/*** 發送驗證碼** @param mobile* @return*/public Map<String, Object> sendCheckCode(String mobile) {Map<String, Object> result = new HashMap<>(2);try {String redisKey = "CHECK_CODE_" + mobile;String value = this.redisTemplate.opsForValue().get(redisKey);if (StringUtils.isNotEmpty(value)) {result.put("code", 1);result.put("msg", "上一次發送的驗證碼還未失效");return result;}String code = this.sendSms(mobile);if (null == code) {result.put("code", 2);result.put("msg", "發送短信驗證碼失敗");return result;}//發送驗證碼成功result.put("code", 3);result.put("msg", "ok");//將驗證碼存儲到Redis,2分鐘后失效this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(2));return result;} catch (Exception e) {LOGGER.error("發送驗證碼出錯!" + mobile, e);result.put("code", 4);result.put("msg", "發送驗證碼出現異常");return result;}}} package com.itheima.sso.vo;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Result {private boolean success;private int code;private String message; }public Result sendCheckCode(String phone) {String checkCodeKEY = "CHECK_CODE_" + phone;String redisCode = redisTemplate.opsForValue().get(checkCodeKEY);if (StringUtils.isNotEmpty(redisCode)){return new Result(true,1,"上一次發送的驗證碼還未失效");}String code = this.sendSms(phone);if (code == null){return new Result(false,2,"發送驗證碼失效");}//存儲在redis中this.redisTemplate.opsForValue().set(checkCodeKEY,code, Duration.ofHours(24));return new Result(true,3,"發送驗證碼成功");}

2 阿里云短信服務


云之訊平臺如果不能審核通過的話,可以使用阿里云短信服務進行發送。

2.1 申請簽名與模板

https://dysms.console.aliyun.com/dysms.htm?spm=5176.12818093.0.ddysms.2a4316d0ql6PyD

說明:申請簽名時,個人用戶只能申請一個并且簽名的名稱必須為“ABC商城”,否則審核不通過。

申請模板

審核時間需要12小時,請耐心等待

2.2 設置用戶權限

在阿里云中,需要在RAM服務中創建用戶以及權限,才能通過api進行訪問接口。

創建用戶

創建完成后要保存AccessKey Secret和AccessKey ID,AccessKey Secret只顯示這一次,后面將不再顯示。

添加權限

2.3 示例代碼

文檔:https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.6.625.18705ffa8u4lwj:

package com.oldlu.sso.service;import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; /* pom.xml <dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.5.3</version> </dependency> */ public class SendSms {public static void main(String[] args) {DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou","LTAI4G7d2Q9CHc741gighjTF", "uKOOGdIKvmoGhHlej8cJY8H3nlU6Fj");IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();request.setSysMethod(MethodType.POST);request.setSysDomain("dysmsapi.aliyuncs.com");request.setSysVersion("2017-05-25");request.setSysAction("SendSms");request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers", "158****7944"); //目標手機號request.putQueryParameter("SignName", "ABC商城"); //簽名名稱request.putQueryParameter("TemplateCode", "SMS_204756062"); //短信模板coderequest.putQueryParameter("TemplateParam", "{\"code\":\"123456\"}");//模板中變量替換try {CommonResponse response = client.getCommonResponse(request);//{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}System.out.println(response.getData());} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}} }

2.4 實現發送短信方法

配置文件:aliyun.properties

aliyun.sms.regionId = cn-hangzhoualiyun.sms.accessKeyId = LTAI4G7d2Q9CHc741gighjTFaliyun.sms.accessKeySecret = uKOOGdIKvmoGhHlej8cJY8H3nlU6Fjaliyun.sms.domain= dysmsapi.aliyuncs.comaliyun.sms.signName= ABC商城aliyun.sms.templateCode= SMS_204756062

需要注意中文編碼問題

讀取配置:

package com.oldlu.sso.config;import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource;@Configuration @PropertySource("classpath:aliyun.properties") @ConfigurationProperties(prefix = "aliyun.sms") @Data public class AliyunSMSConfig {private String regionId;private String accessKeyId;private String accessKeySecret;private String domain;private String signName;private String templateCode;}

代碼實現:

//SmsService.java /*** 通過阿里云發送驗證碼短信** @param mobile*/public String sendSmsAliyun(String mobile) {DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(),this.aliyunSMSConfig.getAccessKeyId(),this.aliyunSMSConfig.getAccessKeySecret());IAcsClient client = new DefaultAcsClient(profile);String code = RandomUtils.nextInt(100000, 999999) +"";CommonRequest request = new CommonRequest();request.setSysMethod(MethodType.POST);request.setSysDomain(this.aliyunSMSConfig.getDomain());request.setSysVersion("2017-05-25");request.setSysAction("SendSms");request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());request.putQueryParameter("PhoneNumbers", mobile);request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName());request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode());request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");try {CommonResponse response = client.getCommonResponse(request);if(StringUtils.contains(response.getData(), "\"Code\":\"OK\"")){return code;}} catch (Exception e) {e.printStackTrace();}return null;}

總結

以上是生活随笔為你收集整理的阿里和云之讯短信发送服务的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。