Spring boot simple access to Ali SMS interface

Preparations are as follows: We need to open SMS service ...

Preparations are as follows:

  • We need to open SMS service on Alibaba cloud. Here we can buy resource packs or recharge our own;
  • Create SMS verification signature. The signature needs to be reviewed by Alibaba background, usually about 2 hours;
  • Create SMS template;
  • In the menu under the user's Avatar, (create a user in AccessKey management and give him the permission to get the account and key in SMS) create an authorized user of Alibaba cloud;

Data we need:

nameinterpretationaccessKeyIdCreate user idaccessKeySecretCreate user's secret keySignNameSMS signature nameTemplateCodeid of SMS template

Import the Alibaba SMS package into the project. Note that I use the upgraded SDK 2017-05-25 Click the reference link to enter
Import the jar package according to the document requirements:

<dependency> <groupId>com.aliyun</groupId> <artifactId>tea-openapi</artifactId> <version>0.0.19</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>dysmsapi20170525</artifactId> <version>2.0.6</version> </dependency>

Let's take a look at the official document sample code: Click jump example

This is the official sample code:

package com.aliyun.sample; import com.aliyun.tea.*; import com.aliyun.dysmsapi20170525.*; import com.aliyun.dysmsapi20170525.models.*; import com.aliyun.teaopenapi.*; import com.aliyun.teaopenapi.models.*; public class Sample { /** * Initialize the Client account with AK & sk * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception { Config config = new Config() // Your AccessKey ID .setAccessKeyId(accessKeyId) // Your AccessKey Secret .setAccessKeySecret(accessKeySecret); // Domain name accessed config.endpoint = "dysmsapi.aliyuncs.com"; return new com.aliyun.dysmsapi20170525.Client(config); } public static void main(String[] args_) throws Exception { java.util.List<String> args = java.util.Arrays.asList(args_); com.aliyun.dysmsapi20170525.Client client = Sample.createClient("accessKeyId", "accessKeySecret"); SendSmsRequest sendSmsRequest = new SendSmsRequest() .setPhoneNumbers("17607146571") .setSignName("code") .setTemplateCode("sms_12675377891") .setTemplateParam("{'code':'123456'}"); // Please print the return value of the API when copying the code client.sendSms(sendSmsRequest); } }

What we need to do is to make some changes to the official code to better fit the actual business development scenario:

  • We first define the fixed parameters for sending SMS in the configuration file, and configure the following in yml;
dysms: accessKeyId: LTAIWjSAN0910892 accessKeySecret: pYtZUs4CCZ57hww19277637OICJSN SignName: Dawei Tianlong #SMS signature TemplateCode: SMS_168581995 #There can be multiple templates, and enumeration can be defined according to project requirements

Note that there may be many SMS templates in the project, which can be configured. In addition, the SMS signature may be in Chinese, and the code may be garbled when using the properties configuration file (this is related to the default loading code of spring). For convenience, it is recommended to use yml file configuration;

  • Let's write a configuration file class and initialize the Client
import com.aliyun.teaopenapi.models.Config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @Auther: MR.rp * @Date: 2021/8/3 14:31 * @Description: */ @Configuration public class DysmsConfig { @Value(value = "$") private String accessKeyId; @Value(value = "$") private String accessKeySecret; @Bean public com.aliyun.dysmsapi20170525.Client careateClient() throws Exception { Config config = new Config() .setAccessKeyId(accessKeyId) .setAccessKeySecret(accessKeySecret); // Domain name accessed config.endpoint = "dysmsapi.aliyuncs.com"; return new com.aliyun.dysmsapi20170525.Client(config); } }
  • Write SMS call tool class
import com.aliyun.dysmsapi20170525.Client; import com.aliyun.dysmsapi20170525.models.*; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Pattern; /** * @Auther: MR.rp * @Date: 2021/8/3 14:37 * @Description: */ @Component @Slf4j public class DysmsUtil { private static Client client; private static String signName; //autograph public static String templateCode;// SMS verification code template id @Value("$") public void setMsgCode(String templateCode) { DysmsUtil.templateCode= templateCode; } @Autowired public DysmsUtil(Client client){ this.client = client; } @Value("$") public void setSIGN(String signName) { DysmsUtil.signName= signName; } /** * Send a message to a single mobile phone * @param phoneNums * @param smsModelId * @param template */ public static void sendMsg(String phoneNums, String templateCode, String template){ //Here, in order to test whether the verification of only writing a single mobile phone number is legal, if there are multiple mobile phone numbers in development, you can verify them yourself first and then pass them to the reference if(!phoneNums.matches("^1(3\\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\\d|9[0-35-9])\\d$")) log.warn("============ cell-phone number:"+phoneNums+"wrongful,fail in send ======"); return; } SendSmsRequest sendSmsRequest = new SendSmsRequest() .setPhoneNumbers(phoneNums) .setSignName(signName) //SMS signature name .setTemplateCode(templateCode) //SMS template ID .setTemplateParam(template); //Variable value try { SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest); SendSmsResponseBody sendBody = sendSmsResponse.getBody(); if(sendBody.getMessage().equals("OK")){ log.info("========== to:"+phoneNums+"Send SMS["+template+"]success!!! =========="); } //The following is the result set of query information. Because the SMS itself will have a certain delay, it may not be found during query, or let the thread sleep for a few seconds before query. Here is only the query code posted for your reference String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date()); String bizId = sendBody.bizId; QuerySendDetailsRequest querySendDetailsRequest = new QuerySendDetailsRequest() .setPhoneNumber(phoneNums) .setSendDate(datetime) .setBizId(bizId) .setPageSize(10L) //paging .setCurrentPage(1L); QuerySendDetailsResponseBody body = client.querySendDetails(querySendDetailsRequest).getBody(); ObjectMapper objectMapper = new ObjectMapper(); String msg = objectMapper.writeValueAsString(body); log.info("Returned body information:"+msg); String message = objectMapper.writeValueAsString(sendBody); log.info("Send return message details:"+message); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage(),e); } } /** * Get SMS verification code * @return Verification Code */ public static String getCode() { String code = null; code = (int) ((Math.random() * 9 + 1) * 100000) + ""; log.info("Verification code is["+code+"]"); return code; } }

We call tests in our business:

@GetMapping("/getCode") @ApiOperation(value = "Get verification code",notes = "Get verification code") @Transactional public ServerResponseVO getCode(@RequestParam("userTel")@ApiParam("cell-phone number") String userTel,HttpSession session){ boolean matches = userTel.matches("^1(3\\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\\d|9[0-35-9])\\d$"); if(!matches){ return ServerResponseVO.error("Wrong mobile phone number"); } String code = DysmsUtil.getCode(); // session.setAttribute(userTel,code); // session.setMaxInactiveInterval(300); redisTemplate.opsForValue().set(userTel,code,300, TimeUnit.SECONDS);// redis storage String jsonCode = "{'code':'"+code+"'}"; DysmsUtil.sendMsg(userTel,DysmsUtil.msgCode,jsonCode); log.info("cell-phone number:"+userTel +"Successfully obtained verification code:["+code+"]" ); return ServerResponseVO.success("Successfully obtained verification code"); }

Look at the log:

How about it? Is it simple?

  • In the case of multiple SMS signatures, we can configure several more SMS configuration names and inject them into the tool class. You can also define them as enumerations. When the current enumerations or injected attributes are passed in during the call, the corresponding SMS can be sent. Also note that when the placeholder parameters are passed in, the official support is json format. The author stepped here before, Failed to send all the time;

If you are interested, you can test it yourself

6 November 2021, 06:49 | Views: 7000

Add new comment

For adding a comment, please log in
or create account

0 comments