阿里云短信验证

前端控制按钮通过js实现60秒倒计时

$(function () {
        $("#sendCode").click(function () {
            //2、倒计时
            if ($(this).hasClass("disabled")) {
                //正在倒计时中
            } else {
                //1、给指定手机号发送验证码
                $.get("/sms/sendCode?phone=" + $("#phoneNum").val(), function (data) {
                    if (data.code != 0) {
                        alert(data.msg);
                    }
                });
                timeoutChangeStyle();// 开始倒计时
            }
        });
    });

    var num = 60;

    function timeoutChangeStyle() {
        $("#sendCode").attr("class", "disabled");// 已经点击发送验证码后,当前按钮不可点击
        if (num == 0) {
            $("#sendCode").text("发送验证码");// 60秒后,文本更改为发送验证码
            num = 60;
            $("#sendCode").attr("class", "");// 60秒后,可以点击
        } else {
            var str = num + "s 后再次发送";
            $("#sendCode").text(str);
            setTimeout("timeoutChangeStyle()", 1000);// 一秒后执行timeoutChangeStyle()
            num--;
        }
    }

第三方服务,发送短信包

1.1搜索短信接口,购买一个5条的短信

阿里云短信验证码发送接口


1.2购买后进入云市场,查看相关3个参数(AppKey、AppSecret、AppCode) 

云市场

 1.3代码实现(请求头使用Authorization作为key + 值使用AppCode的值来验证身份)

/**
 * 短信配置类
 * @Author: wanzenghui
 * @Date: 2021/11/27 23:01
 */
@Configuration
public class SmsConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.cloud.alicloud.sms")
    public SmsServiceImpl smsService() {
        return new SmsServiceImpl();
    }
}

/**
 * 短信服务实现类
 * @Author: wanzenghui
 * @Date: 2021/11/27 22:58
 */
@Data
public class SmsServiceImpl implements SmsService {

    private String host;
    private String path;
    private String appcode;
    private String sign;
    private String skin;

    @Override
    public Boolean sendCode(String phone, String code) {
        String urlSend = host + path + "?code=" + code + "&phone=" + phone + "&sign=" + sign + "&skin=" + skin ; // 拼接请求链接
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE
            // (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json:");
                System.out.print(json);
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权(或URL和Path不正确)");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }
        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
            // e.printStackTrace();
        }
        return true;
    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}

/**
 * 短信服务
 * @Author: wanzenghui
 * @Date: 2021/11/27 23:20
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    SmsServiceImpl smsService;

    /**
     * 发送短信验证码
     * 提供其他模块调用
     * @param phone 号码
     * @param code  验证码
     */
    @GetMapping("/test")
    public R sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        smsService.sendCode(phone, code);
        return R.ok();
    }
}

1.4认证模块_调用发送短信验证码

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    /**
     * 发送短信验证码
     * @param phone 号码
     * @param code  验证码
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        String code = UUID.randomUUID().toString().substring(0, 5);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }
}

完善版本(添加Redis实现60秒内防刷)

/**
 * 发送短信验证码
 *
 * @param phone 号码
 * @param code  验证码
 */
@ResponseBody
@GetMapping("/sms/sendCode")
public R sendCode(@RequestParam(name = "phone", required = true) String phone) {
    // 1.判断60秒间隔发送,防刷
    String _code = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
    if (StringUtils.isNotBlank(_code) && System.currentTimeMillis() - Long.parseLong(_code.split("_")[1]) < 60000) {
        // 调用接口小于60秒间隔不允许重新发送新的验证码
        return R.error(BizCodeEnume.SMS_CODE_EXCEPTION);
    }

    // 2.验证码存入缓存
    String code = UUID.randomUUID().toString().substring(0, 5);
    // 验证码缓存到redis中(并且记录当前时间戳)
    redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);

    // 3.发送验证码
    thirdPartFeignService.sendCode(phone, code);

    return R.ok();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Golang和阿里云短信平台发送短信验证码的示例代码: ```go package main import ( "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" "io/ioutil" "math/rand" "net/http" "net/url" "sort" "strings" "time" ) func main() { // 阿里云短信平台的请求参数 params := url.Values{} params.Set("PhoneNumbers", "17633802772") // 手机号码 params.Set("SignName", "阿里云短信测试专用") // 签名名称 params.Set("TemplateCode", "SMS_123456789") // 模板CODE params.Set("TemplateParam", "{\"code\":\"123456\"}") // 模板参数 // 发送短信验证码 sendSms(params) } // 发送短信验证码 func sendSms(params url.Values) { // 阿里云短信平台的请求参数 accessKeyId := "your_access_key_id" // 替换为你的AccessKeyId accessSecret := "your_access_secret" // 替换为你的AccessKeySecret params.Set("AccessKeyId", accessKeyId) params.Set("SignatureMethod", "HMAC-SHA1") params.Set("SignatureNonce", fmt.Sprintf("%d", rand.Int63())) params.Set("SignatureVersion", "1.0") params.Set("Timestamp", time.Now().UTC().Format("2006-01-02T15:04:05Z")) // 对参数进行排序 var keys []string for k := range params { keys = append(keys, k) } sort.Strings(keys) // 构造待签名的字符串 var signStrings []string for _, k := range keys { signStrings = append(signStrings, url.QueryEscape(k)+"="+url.QueryEscape(params.Get(k))) } signString := strings.Join(signStrings, "&") // 计算签名 stringToSign := "GET&%2F&" + url.QueryEscape(signString) hmacKey := []byte(accessSecret+"&") hmacSha1 := hmac.New(sha1.New, hmacKey) hmacSha1.Write([]byte(stringToSign)) signBytes := hmacSha1.Sum(nil) sign := base64.StdEncoding.EncodeToString(signBytes) params.Set("Signature", sign) // 发送请求 url := "https://dysmsapi.aliyuncs.com/?" + params.Encode() resp, err := http.Get(url) if err != nil { fmt.Println("发送短信验证码失败:", err) return } defer resp.Body.Close() // 处理响应 body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("发送短信验证码失败:", err) return } fmt.Println("发送短信验证码成功:", string(body)) } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值