阿里云短信服务详细说明与实战开发后端代码(三)

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: 阿里云短信服务详细说明与实战开发后端代码

9.自主测试Java SDK

8.在线测试签名模板API 中屏幕右边的代码进行拷贝自己运行即可:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>alibabacloud-dysmsapi20170525</artifactId>
  <version>2.0.23</version>
</dependency>
// This file is auto-generated, don't edit it. Thanks.
package demo;
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-wulanchabu") // 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("SMS_275395309")
                .phoneNumbers("18670082846")
                .templateParam("{\"code\":\"1234\"}")
                // 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();
    }
}

10.⭐前后端实战开发-发送短信验证码

10.1 流程分析

10.2 配置参数说明

sms:
  ali:
    # 子用户的访问键
    accessKeyId: LTAI5tPBmf8y7ZoQSn9h****
    # 子用户的访问密钥
    accessKeySecret: cbd511ed24bd832d05af54f64c84****
    # 签名名称
    signName: 逐浪教育
    # 登录短信模板的code
    loginTemplateCode: SMS_27539****

10.2.1 访问键与密钥

就是在 4.3 创建子用户 中得到的 accessKeyId 与 accessKeySecret

10.2.2 签名名称

就是在 5.添加签名 中设置的签名内容。

10.2.3 登录短信模板code

10.3 🚀 后端代码

由于demo代码过多,这里不做展示。

实战demo源码地址:Mr-Write/SpringbootDemo: 各种demo案例 (github.com)

对应的是 sms-demo 包模块。

🍀 示例演示,用 Apipost7 进行测试:【POST】 http://127.0.0.1:10505/sms-ali/sendLoginCode

同时在我的手机上也接受到了验证码消息。

10.4 补充说明

10.4.1 调用 api 后响应的返回数据

名称 类型 描述 示例
Code String 请求状态码。返回OK代表请求成功。其他错误码,请参见[API错误码](https://help.aliyun.com/document_detail/101346.html?spm=api-workbench.API Document.0.0.5be349a5PlzN8a)。 OK
Message String 状态码的描述。 OK
BizId String 发送回执ID。可根据发送回执ID在接口QuerySendDetails中查询具体的发送状态。 9006197469364984****
RequestId String 请求ID。 F655A8D5-B967-440B-8683-DAD6FF8DE990

正常返回的JSON格式示例

{
  "Code": "OK",
  "Message": "OK",
  "BizId": "9006197469364984****",
  "RequestId": "F655A8D5-B967-440B-8683-DAD6FF8DE990"
}

10.4.2 application.yml 文件中的配置需要进行修改。

  • redis 地址
  • redis 密码
  • 短信平台信息

10.4.3 ubuntu安装docker的步骤

  1. 安装需要的包
sudo apt-get update
  1. 安装依赖包
sudo apt-get install \
   apt-transport-https \
   ca-certificates \
   curl \
   gnupg-agent \
   software-properties-common
  1. 添加 Docker 的官方 GPG 密钥
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  1. 设置远程仓库
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) \
  stable"
  1. 安装 Docker-CE
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
  1. 验证是否成功
sudo docker run hello-world

10.4.4 使用 docker 安装redis并设置密码的步骤

# 拉取redis镜像
docker pull redis
# 启动容器的时候,并为其设置密码
docker run -d --name myredis -p 6379:6379 redis --requirepass "123456"

10.4.5 其它注意事项

注意需要将服务器防火墙6379端口打开。

相关文章
|
7月前
|
小程序
如何提升审核通过率?|阿里云短信服务
提升短信审核率的 tips 都在这里了哦!
472 15
|
5月前
|
SQL JSON 关系型数据库
17.6K star!后端接口零代码的神器来了,腾讯开源的ORM库太强了!
"🏆 实时零代码、全功能、强安全 ORM 库 🚀 后端接口和文档零代码,前端定制返回 JSON 的数据和结构"
|
5月前
|
人工智能 安全 搜索推荐
阿里云采购季:短信服务低至 0.01 元/条!
阿里云“上云采购季”,短信服务低至 0.01 元/条
166 3
|
6月前
|
消息中间件 API 开发工具
实时获取短信发送状态,这个功能别错过!|阿里云短信服务
短信回执可以让你对每一次短信的审核和送达状态了如指掌,怎么样才能摆脱“状态轮询”,实时获取各种状态呢?
714 17
|
7月前
通义灵码企业级检索增强-后端注释生成代码场景DEMO
通义灵码企业级检索增强DEMO展示后端注释生成代码场景。通过上传加密算法的标准化写法(英文注释),大模型能够准确推荐企业标准写法,促进内部知识复用,并支持主动干预生成过程,提升代码规范性和一致性。
|
8月前
|
安全 JavaScript API
阿里云短信服务 5 大优势
选择阿里云短信服务的 5 大理由
355 15
阿里云短信服务 5 大优势
|
8月前
|
安全 小程序
|
9月前
|
API
如何使用控制台群发短信 | 阿里云短信服务
操作指南|通过控制台群发短信
702 14
|
云安全 安全 API
阿里云——OpenAPI使用——短信服务
阿里云——OpenAPI使用——短信服务
536 0
|
安全
阿里云短信服务是可以发送包含下载链接的文本内容的,
阿里云短信服务是可以发送包含下载链接的文本内容的,但是需要注意以下几点:
899 1
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问