短信验证码(阿里云)
短信验证码controller层package com.example.demo.controller;import com.example.demo.service.SendSms;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controll
·
短信验证码
controller层
package com.example.demo.controller;
import com.example.demo.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.UUID;
@RestController
@CrossOrigin//跨域支持
public class SmsApiController {
@Autowired
private SendSms sendSms;
@GetMapping("/send/{phone}")
public String code(@PathVariable("phone") String phone) throws Exception {
//生成验证码
String code = UUID.randomUUID().toString().substring(0, 4);
HashMap<String, Object> param = new HashMap<>();
param.put("code",code);
boolean isSend = sendSms.send(phone, param);
if (isSend) return "发送成功";
else return "发送失败";
}
}
service层
package com.example.demo.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.example.demo.service.SendSms;
import com.google.gson.JsonObject;
import org.springframework.stereotype.Service;
import java.util.Map;
import static com.aliyun.credentials.http.FormatType.JSON;
//import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;
@Service
public class SendSmsImpl implements SendSms {
/**
* 使用AK&SK初始化账号Client
*
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
// 您的AccessKey ID和您的AccessKey Secret
Config config = new Config().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
@Override
public boolean send(String phoneNum, Map<String, Object> code) throws Exception {
String accessKeyId = "accessKeyId";
String accessKeySecret = "accessKeySecret";
String signName = "签名名称";
String template="模版CODE";
Client client = createClient(accessKeyId, accessKeySecret);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phoneNum)
.setSignName(signName)
.setTemplateParam(template)
.setTemplateCode(JSONObject.toJSONString(code));
client.sendSms(sendSmsRequest);
return true;
}
}
更多推荐
所有评论(0)