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

一、前言

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

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("<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, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("<your-accessKeyId>")
                .accessKeySecret("<your-accessKeySecret>")
                //.securityToken("<your-token>") // 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();
    }

}

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>

监听代码

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();
        }
    }

}

前端调用控制层方法

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;
    }
}

在这里插入图片描述

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

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

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++实现56dxw短信验证码WebService接口。 编译工具gsoap-2.8.zip 因为长名字关系,请到根目录解压后再拷贝进来,直接解压可能会解压报错。 用VS.NET2003 开发游戏程序的时候,有一个登录功能模块,需要短信验证码。 56短信网有两种接口,一是HTTP,二是 Web Service。 短信验证码,采用HTTP接口,在客户端发送是不实际的,因为一是受制于客户端网络稳定性,二是容易被客户端拦截URL, 三是被拦截后,容易泄漏56短信网的帐号密码,导致被盗用,产生不安全因素。 服务端采用HTTP接口,也不是很好,服务端连接众多客户端,压力很大,如何有效执行URL和如何得到返回值都是问题。 服务端毕竟不是网站,需要及时有效响应。 因此,采用 服务端 + Web Service 方案很有必要。 其实,Web Service是什么,之前我也不懂,翻阅了大量百度后,知道SOAP这个东西来实现。 非常感谢这篇文章 http://hi.baidu.com/winnyang/blog/item/1138fad9bfac1be338012fdf.html 现在把我C++写的例子实现简单介绍下,与大家共享: 1、下载工具gsoap-2.8。gsoap是个好工具,包装了SOAP到C++的实现,不需要我们再辛苦。(例子中附带这个工具) gsoap-2.8.zip 因为长名字关系,请到根目录解压后再拷贝进来,直接解压可能会解压报错。 2、我例子目录下面有个文件夹gsoap,里面 soapcpp2.exe、wsdl2h.exe 、wsmap.dat、gsoap.bat、stdsoap2.h、stdsoap2.cpp 这几个文件不要删除。 其它文件可以删除,通过执行gsoap.bat重新生成。 3、执行gsoap.bat生成文件。 gsoap.bat内容: wsdl2h.exe -o 56dxw_webservice.h -t wsmap.dat -e http://jiekou.56dxw.com/WebServiceInterface.asmx?wsdl soapcpp2 -i -C -x 56dxw_webservice.h -I ..\gsoap-2.8\gsoap\import del /s /f /q WebServiceInterfaceSoap.nsmap.cpp rename WebServiceInterfaceSoap.nsmap WebServiceInterfaceSoap.nsmap.cpp 各参数意义稍微解释(网上复制): -t 定义std:string到C++中的字符串转化规则, 当前例子采用UNIOCDE编码编译,请在wsmap.dat 中加上 xsd__string = | std::wstring | std::wstring* 这句话 -o 文件名,指定输出头文件 -n 名空间前缀 代替默认的ns -c 产生纯C代码,否则是C++代码 -s 不要使用STL代码 -t 文件名,指定type map文件,默认为typemap.dat -e 禁止为enum成员加上名空间前缀 -C 仅生成客户端代码 -S 仅生成服务器端代码 -L 不要产生soapClientLib.c和soapServerLib.c文件 -c 产生纯C代码,否则是C++代码(与头文件有关) -I 指定import路径(见上文) -x 不要产生XML示例文件 -i 生成C++包装,客户端为xxxxProxy.h(.cpp),服务器端为xxxxService.h(.cpp)。 4、创建VS.NET2003对话框例子 (1)设置项目属性 设置 不使用预编译头 和 使用 Unicode 字符集(是否使用UNICODE根据项目实际情况,只要注意字符串转换) (2)项目中添加以下文件:注意,这些文件都是通过gsoap自动生成,无须修改。 stdsoap2.cpp stdsoap2.h soapC.cpp soapH.h WebServiceInterfaceSoap.nsmap.cpp soapWebServiceInterfaceSoapProxy.cpp soapWebServiceInterfaceSoapProxy.h (3)在对话框.h文件中 添加 #include "gsoap/soapWebServiceInterfaceSoapProxy.h" using namespace std; (4)在对话框.cpp文件中 添加 void Ctest2Dlg::OnBnClickedButton1() { #ifdef _UNICODE #define tstring wstring #else #define tstring string #endif WebServiceInterfaceSoapProxy gs; _ns1__SendNote SendSms; _ns1__SendNoteResponse Resp; CString str; GetDlgItemText(IDC_EDIT3,str); tstring handtels(str); tstring content(TEXT("验证码内容")); GetDlgItemText(IDC_EDIT1,str); tstring userName(str); //请测试人员此处直接输入用户名和密码 GetDlgItemText(IDC_EDIT2,str); tstring password(str); tstring cid(TEXT("713")); tstring sendtime(TEXT("")); tstring smsnumber(TEXT("1061")); SendSms.handtels = &handtels; SendSms._USCOREcontent = &content; SendSms.userName = &userName; SendSms.password = &password; SendSms.cid = &cid; SendSms._USCOREsendtime = &sendtime; SendSms._USCOREsmsnumber = &smsnumber; if(gs.SendNote(&SendSms;, &Resp;) == SOAP_OK) { int nReturn = Resp.SendNoteResult; switch( nReturn ) { case 1:str.Format(TEXT("发送成功"));break; case -1:str.Format(TEXT("用户名密码不正确"));break; case -2:str.Format(TEXT("内容不能大于70个字"));break; case -3:str.Format(TEXT("验证此平台是否存在"));break; case -4:str.Format(TEXT("提交号码不能为空或客户余额为0"));break; case -5:str.Format(TEXT("客户剩余条数不够要发送的短信数量"));break; case -6:str.Format(TEXT("非法短信内容"));break; case -7:str.Format(TEXT("返回系统故障"));break; case -8:str.Format(TEXT("网络性错误,请稍后再试"));break; default:str.Format(TEXT("未知错误"));break; } AfxMessageBox(str); } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值