先去官网注册一个账号领一条免费的
复制一些参数和更改短信模板
三个参数
appId,appSecret,templateId
然后短信模板中的{1},{2}参数是后面程序中传入的
添加依赖
ps:hutool工具类-是我用的习惯的一个工具类,这里主要是进行json操作 换成别的gjson fastjson都行的
<!--榛子云短信接口-->
<dependency>
<groupId>com.zhenzikj</groupId>
<artifactId>zhenzisms</artifactId>
<version>2.0.2</version>
</dependency>
<!-- hutool工具类-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.3</version>
</dependency>
controller代码
import cn.hutool.json.JSONObject;
import com.yxx.hospital.common.lang.Result;
import com.zhenzi.sms.ZhenziSmsClient;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @Author: YuXinXin
* @Description:
* @Date:Created in 21:01 2020/8/1
**/
@RestController
public class CodeController {
private String apiUrl="https://sms_developer.zhenzikj.com";
private String appId = "";
private String appSecret = "";
@ApiOperation(value="短信接口", notes="短信接口")
@RequestMapping(value = "/phone/code",method = RequestMethod.GET)
public Result getCode(@RequestParam("phoneNumber") String phoneNumber, HttpServletRequest request) {
try{
JSONObject json;
ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
String code = String.valueOf(new Random().nextInt(899999) + 100000);
Map<String, Object> params = new HashMap<String, Object>();
params.put("number", phoneNumber);
params.put("templateId", "1496");
//这个参数就是短信模板上那两个参数
String[] templateParams = new String[2];
templateParams[0] = code;
templateParams[1] = "2分钟";
params.put("templateParams", templateParams);
String result = client.send(params);
json = new JSONObject(result);
if(json.getInt("code")!=0)
return Result.fail("发送短信失败");
json = new JSONObject();
json.append("memPhone",phoneNumber);
json.append("code",code);
json.append("createTime",System.currentTimeMillis());
// 将认证码存入SESSION
request.getSession().setAttribute("code",json);
return Result.succ("发送成功~");
}catch(Exception e){
e.printStackTrace();
return Result.fail(e.getMessage());
}
}
}
结果展示