0


手机短信注册验证与登录功能

文章目录

一、前言

通过手机短信发送验证码,是最普遍、最安全验证用户真实身份的方式,目前,短信验证码广泛应用于用户注册、密码找回、登录保护、身份认证、随机密码、交易确认等应用场景。本文通过调用API开发一个短信验证码为例,带您了解如何实现短信验证码功能。

二、准备工作

两步即可,本次以阿里云为例。第一步,在阿里云开通短信服务,第二步,创建一个简单的springboot的项目。
1、注册阿里云并完成实名认证
阿里云地址:https://www.aliyun.com/
2、创建AccessKey
在这里插入图片描述

3、搜索短信服务
在这里插入图片描述

4、点击同意-并控制台开通短信服务
在这里插入图片描述

三、发布短信

1、基本测试发布

①可-使用测试模板进行调试

在这里插入图片描述

②测试结果

在这里插入图片描述

③注意,可能会调试失败,是因为没有余额。进入首页点击头像>进入余额充值;一条大概4分钱

在这里插入图片描述

在这里插入图片描述

④创建SpringBoot项目demo

引入jar包

<dependency><groupId>com.aliyun</groupId><artifactId>alibabacloud-dysmsapi20170525</artifactId><version>2.0.22</version></dependency>

创建类SendSms
注意,代码中输入自己的accessKeyId,accessKeySecret。在第2步 创建AccessKey点击查看Secret获取

packagecom.hn.yuan.controller;importcom.aliyun.auth.credentials.Credential;importcom.aliyun.auth.credentials.provider.StaticCredentialProvider;importcom.aliyun.core.http.HttpClient;importcom.aliyun.core.http.HttpMethod;importcom.aliyun.core.http.ProxyOptions;importcom.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;importcom.aliyun.sdk.service.dysmsapi20170525.models.*;importcom.aliyun.sdk.service.dysmsapi20170525.*;importcom.google.gson.Gson;importdarabonba.core.RequestConfiguration;importdarabonba.core.client.ClientOverrideConfiguration;importdarabonba.core.utils.CommonUtil;importdarabonba.core.TeaPair;//import javax.net.ssl.KeyManager;//import javax.net.ssl.X509TrustManager;importjava.net.InetSocketAddress;importjava.time.Duration;importjava.util.*;importjava.util.concurrent.CompletableFuture;publicclassSendSms{publicstaticvoidmain(String[] args)throwsException{// HttpClient Configuration/*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/// Configure Credentials authentication information, including ak, secret, tokenStaticCredentialProvider provider =StaticCredentialProvider.create(Credential.builder().accessKeyId("<your-accessKeyId>").accessKeySecret("<your-accessKeySecret>")//.securityToken("<your-token>") // use STS token.build());// Configure the ClientAsyncClient client =AsyncClient.builder().region("cn-hangzhou")// Region ID//.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient).credentialsProvider(provider)//.serviceConfiguration(Configuration.create()) // Service-level configuration// Client-level configuration rewrite, can set Endpoint, Http request parameters, etc..overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com")//.setConnectTimeout(Duration.ofSeconds(30))).build();// Parameter settings for API requestSendSmsRequest sendSmsRequest =SendSmsRequest.builder().signName("阿里云短信测试").templateCode("模板code").phoneNumbers("手机号").templateParam("{\"code\":\"6666\"}")// Request-level configuration rewrite, can set Http request parameters, etc.// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders())).build();// Asynchronously get the return value of the API requestCompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);// Synchronously get the return value of the API requestSendSmsResponse resp = response.get();System.out.println(newGson().toJson(resp));// Asynchronous processing of return values/*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/// Finally, close the client
        client.close();}}

2、可自定义模板,发布短信功能

①可-新建签名

在这里插入图片描述

审核中,一般需要 2 小时左右!防止非法发送短信骚扰他人! 审核不通过,换个名称:“杭州快餐店”重新审核。

②新建模板

发送短信的内容模版,都是有严格要求的,不能涉及到违反互联网规定的法律条款
在这里插入图片描述

审核中,一般需要 2 小时左右!禁止非法发送短信骚扰他人!严厉禁止群发黄赌毒信息!

可完成 手机短信注册验证与登录功能。

String code =(int)(Math.random()*1000000)+“”; //随机产生一个 6 位数;
通过监听器@JmsListener,当用户输入的数字和通过Redis中缓存进行验证,是否一致。

部分代码

<dependency><groupId>org.springframework</groupId><artifactId>spring-jms</artifactId><version>5.2.6.RELEASE</version></dependency>

监听代码

packagecom.hn.yuan.controller;importdarabonba.core.exception.ClientException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jms.annotation.JmsListener;importorg.springframework.stereotype.Component;@ComponentpublicclassMyListener{@AutowiredprivateSendSms sendSms;@JmsListener(destination ="yuan")publicvoidgetMessage(String phone){try{
            sendSms.getsendSms(phone);//通知发送短信代码}catch(ClientException e){
            e.printStackTrace();}}}

前端调用控制层方法

packagecom.hn.yuan.controller;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jms.core.JmsMessagingTemplate;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/jms")publicclassJmsController{@AutowiredprivateJmsMessagingTemplate jmsMessagingTemplate;@RequestMapping("/send")publicStringsenMsg(String phone){
        jmsMessagingTemplate.convertAndSend("yuan",phone);return phone;}}

在这里插入图片描述

各位看官》创作不易,点个赞!!!
诸君共勉:万事开头难,只愿肯放弃。

免责声明:本文章仅用于学习参考


本文转载自: https://blog.csdn.net/SoulNone/article/details/127937911
版权归原作者 源的世界 所有, 如有侵权,请联系我们删除。

“手机短信注册验证与登录功能”的评论:

还没有评论