1:使用榛子云作为短信服务的提供者
榛子云官网:http://smsow.zhenzikj.com/
自己注册下就可以了
查看自己的appid
2:代码编写
1:pom.xml导入最新的依赖
<dependency>
<groupId>com.zhenzikj</groupId>
<artifactId>zhenzisms</artifactId>
<version>1.0.2</version>
</dependency>
2:编写代码controller层
//短信平台相关参数。在用户中心查看
private String apiUrl = "https://sms_developer.zhenzikj.com";//调用的接口
private String appId = "";
private String appSecret = "";
@ResponseBody
@PostMapping("/sendcode")
public Result getCode(@RequestBody Map<String, Object> params, HttpSession httpSession){
String phonenumber = (String) params.get("phonenumber");//通过ajax传过来的手机号
System.out.println(phonenumber);
try {
String code = String.valueOf(new Random().nextInt(999999));
System.out.println("验证码是:"+code+".....................");
ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
String result = client.send(phonenumber, "您的验证码为:" + code + ",该码有效期为5分钟,该码只能使用一次!");
System.out.println(result);
System.out.println("发送成功");
return Result.ok();
} catch (Exception e) {
e.printStackTrace();
}
return Result.error("账号已经存在请登入");
}
3:Result.class
在这里插入代码片
```public class Result extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public Result() {
put("code", 0);
}
public static Result error() {
return error(500, "未知异常,请联系管理员");
}
public static Result error(String msg) {
return error(500, msg);
}
public static Result error(int code, String msg) {
Result r = new Result();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static Result ok(Object msg) {
Result r = new Result();
r.put("msg", msg);
return r;
}
public static Result ok(Map<String, Object> map) {
Result r = new Result();
r.putAll(map);
return r;
}
public static Result ok() {
return new Result();
}
@Override
public Result put(String key, Object value) {
super.put(key, value);
return this;
}
}
3:前端以及ajax编写
<input type="text" name="phonenumber" v-model="phonenumber" id="phonenumber" placeholder="输入手机号">
<button type="button" onclick="sign()" class="am-btn am-btn-default">注册</button>
function dosend() {
var phonenumber= $("#phonenumber").val();
alert("短信成功发送请注意查收!");
$.ajax({
url: "/sendcode", // 后台短信发送接口
type: 'POST',
dataType: 'json',
contentType: "application/json",
async: false, //false 同步
data: JSON.stringify({"phonenumber":phonenumber}),
xhrFields: {
withCredentials: true
},
success: function (result) {
if(result.code == 0) {
}else {
}
},
error: function () {
}
});
}
4:控制台
code格式: