当前位置: 代码网 > it编程>编程语言>Java > Java实现短信验证码服务的完整代码示例

Java实现短信验证码服务的完整代码示例

2024年09月24日 Java 我要评论
首先这里使用的是阿里云的短信服务。package com.wzy.util;;import cn.hutool.captcha.generator.randomgenerator;import com

首先这里使用的是阿里云的短信服务。

package com.wzy.util;;
import cn.hutool.captcha.generator.randomgenerator;
import com.aliyun.dysmsapi20170525.client;
import com.wzy.entity.ali;
import org.springframework.stereotype.component;

/**
 * @author: 顾安
 * @description:
 * @date: create in 17:30 2024/7/23
 */
@component
public class sendmsgutil {
    /**
     * 使用ak&sk初始化账号client
     * @return client
     * @throws exception
     */

    private static ali ali;

    public sendmsgutil(ali ali) {
        this.ali = ali;
    }
    public static client createclient() throws exception {
        com.aliyun.teaopenapi.models.config config = new com.aliyun.teaopenapi.models.config()
                // 必填,请确保代码运行环境设置了环境变量 alibaba_cloud_access_key_id。
                .setaccesskeyid(ali.getaccesskeyid())

                // 必填,请确保代码运行环境设置了环境变量 alibaba_cloud_access_key_secret。
                .setaccesskeysecret(ali.getaccesskeysecret());
        // endpoint 请参考 https://api.aliyun.com/product/dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new client(config);
    }
/*    *
     * api 相关
     * @return openapi.params*/

    public static com.aliyun.teaopenapi.models.params createapiinfo() throws exception {
        com.aliyun.teaopenapi.models.params params = new com.aliyun.teaopenapi.models.params()
                // 接口名称
                .setaction("sendsms")
                // 接口版本
                .setversion("2017-05-25")
                // 接口协议
                .setprotocol("https")
                // 接口 http 方法
                .setmethod("post")
                .setauthtype("ak")
                .setstyle("rpc")
                // 接口 path
                .setpathname("/")
                // 接口请求体内容格式
                .setreqbodytype("json")
                // 接口响应体内容格式
                .setbodytype("json");
        return params;
    }

    public static string sendcode(string phone) throws exception {
        com.aliyun.teaopenapi.client client = createclient();
        com.aliyun.teaopenapi.models.params params = createapiinfo();
        string code="123456";
        // query params
        java.util.map<string, object> queries = new java.util.hashmap<>();
        queries.put("phonenumbers", phone);
        queries.put("signname", ali.getsignname());
        queries.put("templatecode", ali.gettemplatecode()); //您正在申请手机注册,验证码为:$[code],5分钟内有效!
        queries.put("templateparam", "{\"code\":\""+codes()+"\"}");
        // runtime options
        com.aliyun.teautil.models.runtimeoptions runtime = new com.aliyun.teautil.models.runtimeoptions();
        com.aliyun.teaopenapi.models.openapirequest request = new com.aliyun.teaopenapi.models.openapirequest()
                .setquery(com.aliyun.openapiutil.client.query(queries));
        // 复制代码运行请自行打印 api 的返回值
        // 返回值为 map 类型,可从 map 中获得三类数据:响应体 body、响应头 headers、http 返回的状态码 statuscode。
        client.callapi(params, request, runtime);
        return codes();
    }
    public static string codes(){
        // 自定义纯数字的验证码(随机4位数字,可重复)
        randomgenerator randomgenerator = new randomgenerator("0123456789", 4);
        return string.valueof(randomgenerator);

    }
//    public static string code(){
//        return string.valueof(threadlocalrandom.current().nextint(100000,1000000));
//    }
}

上面的一些属性没有直接写到代码中,而是模拟真实的开发场景,写入application.yml配置文件中,通过定义一个类,然后指定配置文件,在阿里配置类中注入改实体类对象。如下图所示

@data
@allargsconstructor
@noargsconstructor
@component
@configurationproperties("ali.msg")
public class ali {
    private string accesskeyid;
    private string accesskeysecret;
    private string signname;
    private string templatecode;

}

然后需要随机生成数字,我这里也使得是hutool工具,需要加入该工具的jar包

<dependency>
    <groupid>cn.hutool</groupid>
    <artifactid>hutool-all</artifactid>
    <version>5.8.16</version>
</dependency>

该工具包含各种场景的工具,满足开发需求的很多场景,大家可以学习一下,随机生成的代码如下:

public static string codes(){
    // 自定义纯数字的验证码(随机4位数字,可重复)
    randomgenerator randomgenerator = new randomgenerator("0123456789", 4);
    return string.valueof(randomgenerator);

}

生成一个从0到9随机组成的4位数。

然后就可以开始编写我们的真实开发环境的发送验证码

@getmapping("/send")
public r sentmsg(string phone){
   //判断前端传过来的手机号是否正确
    if (phone.equals("166x786xxxxx")){
    //判断验证码是否已发送,防止恶意发送
        if (redistemplate.haskey("code::"+phone)){
            return new r(200,"请不要频繁点击",null);
        }
        try {
        //调用阿里云的接口并拿到前端传来的手机号
            string code = sendmsgutil.sendcode(phone);
           //把验证码存入到redis缓存中并设置过期时间
            redistemplate.opsforvalue().set("code::"+phone,code,5, timeunit.minutes);
            return new r(200,"发送成功",null);
        } catch (exception e) {
            throw new runtimeexception(e);
        }
    }
    return new r(200,"发送失败",null);
}
@postmapping("/login")
public r login(@requestbody loginvo loginvo){
    //拿到缓存中的验证码
    string code = redistemplate.opsforvalue().get("code::" + loginvo.getphone());
     //拿到缓存中的手机号
    string phone = loginvo.getphone();
   //判断手机号是否正确
    if (phone.equals("16627865460")){
     //判断验证码是否为空是否正确
        if (stringutils.hastext(loginvo.getcode())&&loginvo.getcode().equals(code)){
           //删除缓存中的验证码,防止恶意登入
            redistemplate.delete("code::" + phone);
            return new r(200,"登入成功",null);
        }else {
            return new r(500,"登入失败",null);
        }
    }
    return new r(500,"登入失败",null);
}

总结

到此这篇关于java实现短信验证码服务的文章就介绍到这了,更多相关java实现短信验证码服务内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com