Foreword
Previous spoke springboot integrated mail service, let us learn together under springboot project how to use the SMS service bar.
The project will be used on short message service basically, a simple registration code, message notification, etc. are used. So I'm going to the scaffold also inherited the short message service comes in.
Short message service platform I use Ali cloud. There are many online SMS service provider. You can choose according to their needs.
Ready to work
Ali opened on cloud services, as well as configuration. These aliyun official documents are written very clearly, how did not elaborate, you can refer to the article:
https://blog.csdn.net/qq_27790011/article/details/78339856
Once configured, you need to get the following information:
accessKeyId, accessSecret two are keys. It can be found in the user AccessKey.
signName is the signature name.
templateCode is the template code
Adding dependencies and configuration
With the above preparations, we are going to start developing our project now. Like to join in dependence pom.xml file:
<!--阿里云短信服务-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.61</version>
</dependency>
This fastjson is not necessary, it depends on your project have not used it, did not use it, add the first dependent enough.
Then join in application.properties configuration file, these four parameters, the four parameters is to prepare us for the work.
service layer
And mail services, we here do not relate to the database, to write directly on the service layer interfaces create SmsService and SmsServiceImpl class.
SmsServiceImpl code is as follows:
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
@Value("${sms.accessKeyId}")
private String accessKeyId;
@Value("${sms.accessSecret}")
private String accessSecret;
@Value("${sms.signName}")
private String signName;
@Value("${sms.templateCode}")
private String templateCode;
@Override
public boolean sendSms(String iponeNUmber) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", iponeNUmber);
request.putQueryParameter("SignName", signName);
request.putQueryParameter("TemplateCode", templateCode);
JSONObject object=new JSONObject();
String randCode=getRandCode(6);
log.info("验证码为:{}",randCode);
object.put("code",randCode);
request.putQueryParameter("TemplateParam", object.toJSONString());
try {
CommonResponse response = client.getCommonResponse(request);
log.info(response.getData());
return true;
} catch (Exception e) {
log.error("{}",e);
}
return false;
}
/**
* 生成随机验证码
* @param digits
* @return
*/
public static String getRandCode(int digits) {
StringBuilder sBuilder = new StringBuilder();
Random rd = new Random((new Date()).getTime());
for(int i = 0; i < digits; ++i) {
sBuilder.append(String.valueOf(rd.nextInt(9)));
}
return sBuilder.toString();
}
}
Overall code logic is very simple, first by Value Notes configuration file that four parameters configured to acquire.
sendSms () method:
DefaultProfile and IAcsClient DefaultAcsClient is created and initialized instance. Three parameters respectively are: area ID, RAM account AccessKey ID, RAM account AccessKey Secret.
DescribeInstancesRequest is to create an API request and set the parameters. request.putQueryParamete () we modify the main parameters are modified there. PhoneNumbers phone number to receive information, here I send a text message verification code. I here generates a 6-bit codes of short messages. The specific needs of everyone can be adjusted according to demand.
controller layer
layer controller is relatively simple, it transmits a message interface, creating class at SmsController sms packet, as follows:
@RestController
@RequestMapping("/sms")
public class SmsController {
@Autowired
private SmsService smsService;
@RequestMapping(value = "/send",method = RequestMethod.GET)
public String sendSms(@RequestParam(value = "userName")String userName){
smsService.sendSms(userName);
return "success";
}
}
test
So far, short message service has been set up well, and now we have to test, we first started the project, and then call interface:
http://localhost:9090/zlflovemm/sms/send?userName=13265459362
Then look at the log
Look on our cell phone received a text message.
SMS service is configured you can see the success. Overall, we did not quite that complicated.
Extra
Well, so much for you, today's code is also synchronized to the project on github friends.
github address: https: //github.com/QuellanAn/zlflovemm
Come follow ♡
Welcome to the personal public concern number "Programmers love yogurt"
Share a variety of learning materials including java, linux, big data. Information includes video documentation and source code, while sharing themselves and delivery of high-quality technology blog.
If you like attention and remember to share yo ❤