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


    一、前言

    通过手机短信发送验证码,是最普遍、最安全验证用户真实身份的方式,目前,短信验证码广泛应用于用户注册、密码找回、登录保护、身份认证、随机密码、交易确认等应用场景。本文通过调用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>
    
    • 1
    • 2
    • 3
    • 4
    • 5

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

    package com.hn.yuan.controller;
    
    
    import com.aliyun.auth.credentials.Credential;
    import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
    import com.aliyun.core.http.HttpClient;
    import com.aliyun.core.http.HttpMethod;
    import com.aliyun.core.http.ProxyOptions;
    import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
    import com.aliyun.sdk.service.dysmsapi20170525.models.*;
    import com.aliyun.sdk.service.dysmsapi20170525.*;
    import com.google.gson.Gson;
    import darabonba.core.RequestConfiguration;
    import darabonba.core.client.ClientOverrideConfiguration;
    import darabonba.core.utils.CommonUtil;
    import darabonba.core.TeaPair;
    
    //import javax.net.ssl.KeyManager;
    //import javax.net.ssl.X509TrustManager;
    import java.net.InetSocketAddress;
    import java.time.Duration;
    import java.util.*;
    import java.util.concurrent.CompletableFuture;
    
    public class SendSms {
        public static void main(String[] args) throws Exception {
    
            // 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("", 9001))
                            .setCredentials("", ""))
                    // 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, token
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId("")
                    .accessKeySecret("")
                    //.securityToken("") // use STS token
                    .build());
    
            // Configure the Client
            AsyncClient 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 request
            SendSmsRequest 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 request
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().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();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    监听代码

    package com.hn.yuan.controller;
    
    import darabonba.core.exception.ClientException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jms.annotation.JmsListener;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyListener {
    
        @Autowired
        private SendSms sendSms;
    
        @JmsListener(destination = "yuan")
        public void getMessage(String phone){
            try {
                sendSms.getsendSms(phone); //通知发送短信代码
            }catch (ClientException e){
                e.printStackTrace();
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    前端调用控制层方法

    package com.hn.yuan.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jms.core.JmsMessagingTemplate;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/jms")
    public class JmsController {
    
        @Autowired
        private JmsMessagingTemplate jmsMessagingTemplate;
    
        @RequestMapping("/send")
        public String senMsg(String phone){
            jmsMessagingTemplate.convertAndSend("yuan",phone);
            return phone;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

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

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

  • 相关阅读:
    【有源码】基于asp.net的旅游度假村管理系统C#度假村美食住宿一体化平台源码调试 开题 lw ppt
    浅谈CVPR2022的几个研究热点
    深度学习基础之梯度下降
    我国跨境电商行业研究报告(2022)
    计算机网络原理复习汇总
    Netty架构详解
    “如何实现高效的应用交付”鲁班会开发者训练营厦门站进行时
    【《On Java 8》学习之路——复用】知识点整理分享
    业内人士真心话:只会测试没有前途的,我慌了....
    关于我的家乡网页设计主题题材——梧州14页HTML+CSS网页
  • 原文地址:https://blog.csdn.net/SoulNone/article/details/127937911