文章目录
- 一、前言
- 二、准备工作
- 三、发布短信
- 1、基本测试发布
- ①可-使用测试模板进行调试
- ②测试结果
- ③注意,可能会调试失败,是因为没有余额。进入首页点击头像>进入余额充值;一条大概4分钱
- ④创建SpringBoot项目demo
- 2、可自定义模板,发布短信功能
- ①可-新建签名
- ②新建模板
- 可完成 手机短信注册验证与登录功能。
一、前言
通过手机短信发送验证码,是最普遍、最安全验证用户真实身份的方式,目前,短信验证码广泛应用于用户注册、密码找回、登录保护、身份认证、随机密码、交易确认等应用场景。本文通过调用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, 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(new Gson().toJson(resp));// Asynchronous processing of return values/*response.thenAccept(resp -> {System.out.println(new Gson().toJson(resp));}).exceptionally(throwable -> { // Handling exceptionsSystem.out.println(throwable.getMessage());return null;});*/// Finally, close the clientclient.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 {@Autowiredprivate 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 {@Autowiredprivate JmsMessagingTemplate jmsMessagingTemplate;@RequestMapping("/send")public String senMsg(String phone){jmsMessagingTemplate.convertAndSend("yuan",phone);return phone;}
}
各位看官》创作不易,点个赞!!!
诸君共勉:万事开头难,只愿肯放弃。
免责声明:本文章仅用于学习参考