Before because of
Warning: It takes 8 minutes to read this article
Hanzo mall before the login is just ordinary mobile phone number, password, verification code for login, does not support mobile verification code secret login, Liu Sumo (thank you ha) suggested that I join the mobile verification code direct login function, just have this strength, arranged. Next share my mobile phone SMS verification code to achieve login code implementation process.
Open ali Cloud SMS service
The first need in ali cloud console to open ali cloud SMS service, personal words each SMS price is 0.045 yuan (not expensive, blunt 10 yuan enough for a long time). After opening SMS service, you also need to apply for SMS template and signature and other information (there will be customer service review, unsuccessful words will prompt you how to change, this must apply, the code will be used). The most important step is to give accessKey SMS permission (must! This section does not involve code, but more explanation, Baidu has a detailed opening tutorial. I won’t talk too much about the code, I will share the process and the pit I stepped on, because many people want to do it, but don’t know where to start, the code is the simplest thing in this.
Maven led package
Maven is a Maven search engine that relies on web sites to search for and copy packages.
<! <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun- Java - sdK-core </artifactId> < version > 4.5.0 < / version > < / dependency > < the dependency > < groupId > com. The aliyun < / groupId > < artifactId > aliyun - Java - SDK - dysmsapi < / artifactId > < version > 2.1.0 < / version > < / dependency >Copy the code
Configure the application. The properties
I like to use application.properties, some people like to use YML, I feel this format looks more clear, line by line, personal habit.
AccessKeyId = your accessKeyId # accessKeySecret= your accessKeySecret Product =Dysmsapi # product domain name = sms.domain=dysmsapi.aliyuncs.com # sign sms.signname = hanzang mall # send verification CODE template CODE sms.templateCode=SMS_185843228Copy the code
Write business layer interface code
/ * * *@authorHao yu QAQ *@qqAc group 951485783 *@email [email protected]
* @linkOn March 17, 2020, https://github.com/Tianhaoy/hanzomall * 17:18:31 interface * / * @ send text messages
public interface SmsService {
/** * Send SMS interface *@param phoneNumber
* @param randomCode
* @return* /
boolean sendSms(String phoneNumber, String randomCode);
}
Copy the code
Write the business layer interface implementation class code
/ * * *@authorHao yu QAQ *@qqAc group 951485783 *@email [email protected]
* @linkOn March 17, 2020, https://github.com/Tianhaoy/hanzomall * 17:18:22 interface * / * @ send text messages
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
@Value("${sms.accessKeyId}")
private String accessKeyId;
@Value("${sms.accessKeySecret}")
private String accessKeySecret;
@Value("${sms.product}")
private String product;
@Value("${sms.domain}")
private String domain;
@Value("${sms.signName}")
private String signName;
@Value("${sms.templateCode}")
private String templateCode;
@Override
public boolean sendSms(String phoneNumber, String randomCode) {
// Set the timeout - adjustable
System.setProperty("sun.net.client.defaultConnectTimeout"."10000");
System.setProperty("sun.net.client.defaultReadTimeout"."10000");
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain(domain);
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId"."cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phoneNumber);
request.putQueryParameter("SignName"."Hanzo Mall");// If you select signName, you will be prompted that the signature is invalid
request.putQueryParameter("TemplateCode", templateCode);
JSONObject object = new JSONObject();
try {
object.put("code",randomCode);
} catch (JSONException e) {
e.printStackTrace();
}
String templateParam =object.toString();
request.putQueryParameter("TemplateParam", templateParam);
try {
// The request fails and a ClientException exception is thrown
CommonResponse response = client.getCommonResponse(request);
log.info("Ali Cloud SMS service return message :"+response.getData());
// Use Alibaba fastjson
Map<String, Object> map= JSON.parseObject(response.getData());
if (("OK").equals(map.get("Code"))) {return true;
}else{
return false; }}catch (ClientException e) {
e.printStackTrace();
log.error(e.getMessage());
}
return false; }}Copy the code
Write the Controller layer code
/ * * *@authorHao yu QAQ *@qqAc group 951485783 *@email [email protected]
* @linkhttps://github.com/Tianhaoy/hanzomall * @ * / send text messages
@Slf4j
@RestController
public class SmsSendController {
@Resource
private SmsService smsService;
@RequestMapping("/sendCodeSms/{phoneNumber}")
public Result SmsSendKaptcha(@PathVariable("phoneNumber") String phoneNumber, HttpSession httpSession) {
// Verify that the mobile phone number matches the rule
if (PhoneUtil.confPhone(phoneNumber)){
try {
// Generate a 6-bit random code
String randomCode = EmailCodeUtils.getRandomCode();
boolean sign = smsService.sendSms(phoneNumber,randomCode);
if (sign){
// The random verification code is placed in the session
log.info("SMS message sent successfully");
httpSession.setAttribute(Constants.RANDOM_CODE,randomCode);
}else {
return ResultGenerator.genFailResult("Service is idle. Please try again later."); }}catch (Exception e){
e.printStackTrace();
log.error("Sending SMS failed"+e.getMessage());
return ResultGenerator.genFailResult("Service is idle. Please try again later."); }}else {
return ResultGenerator.genFailResult("Mobile phone number does not match the rules, please re-enter");
}
returnResultGenerator.genSuccessResult(); }}Copy the code
summary
So far, the whole process of sending SMS verification code is introduced, knowledge is only valuable to share. If you have any questions, please feel free to contact me through my email on my page.