1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 【SpringBoot】实现短信验证码登录(榛子云的SDK)

【SpringBoot】实现短信验证码登录(榛子云的SDK)

时间:2021-08-06 23:18:16

相关推荐

【SpringBoot】实现短信验证码登录(榛子云的SDK)

先去官网注册一个账号领一条免费的

复制一些参数和更改短信模板

三个参数

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.mon.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 /8/1**/@RestControllerpublic class CodeController {private String apiUrl="";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());// 将认证码存入SESSIONrequest.getSession().setAttribute("code",json);return Result.succ("发送成功~");}catch(Exception e){e.printStackTrace();return Result.fail(e.getMessage());}}}

结果展示

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。