Springboot整合阿里巴巴SMS

前提条件

用户权限
要确保用户有这个权限
组权限还要确保组要有这个权限

讲反了要先保证组有这个权限然后保证用户有这个权限,然后就可以使用这个用户的权限的key来调取api了

申请资质、签名等

申请资质

申请资质
点击这个进入声请就可以了然后等2个小时左右就可以通过了

申请签名

在这里插入图片描述
这个是为了之后自定义模板做准备

添加模板

添加模板当然第一次是可以注册钉钉认证之后获取免费的一些额度

api引入

依赖引入

<!--sms的服务-->
 <dependency>
     <groupId>com.aliyun</groupId>
     <artifactId>alibabacloud-dysmsapi20170525</artifactId>
     <version>2.0.24</version>
 </dependency>

代码部分

package com.example.lpms.tool;

import com.example.lpms.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;

/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/12/13
 * @Title:
 */

@Component
public class SMSTool {
    @Value("${spring.sms.id}")
    String id;

    @Value("${spring.sms.secret}")
    String secret;

    @Value("${spring.sms.sign-name}")
    String signName;

    @Value("${spring.sms.templateCode}")
    String templateCode;

    public R sendSMS(String phone, String captcha) {

        try {

            // Configure Credentials authentication information, including ak, secret, token
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(id)
                    .accessKeySecret(secret)
                    //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                    .build());

            // Configure the Client
            AsyncClient client = AsyncClient.builder()
                    .region("cn-shanghai") // 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()
                                    // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();

            // Parameter settings for API request
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(signName)
                    .templateCode(templateCode)
                    .phoneNumbers(phone)
                    .templateParam("{\"code\":\"" + captcha + "\"}")
                    // 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));


            // Finally, close the client
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }


        return R.ok();
    }

}

注意

这下面和官网不一样但是不这样写会报错,好像是因为这个是直接注入到哪里的,而这里是不需要注入的

// Configure Credentials authentication information, including ak, secret, token
StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
        .accessKeyId(id)
        .accessKeySecret(secret)
        //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
        .build());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现Spring Boot整合阿里云短信服务,可以按照以下步骤进行操作: 1. 首先,在启动类上添加相关注解和配置。根据引用中的代码,可以在启动类上加上注解`@EnableSwagger2`、`@ComponentScan`和`@SpringBootApplication`。同时,可以使用`@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)`来取消数据源的自动配置。 2. 接下来,需要引入阿里云短信服务的相关依赖。可以在项目的`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.2.2</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.0.0</version> </dependency> ``` 3. 然后,需要在阿里云短信服务中创建一个短信模板,并获得对应的Access Key ID和Access Key Secret。这些信息将用于对接阿里云短信服务。 4. 在项目的配置文件中,可以配置阿里云短信服务的相关信息。可以在`application.properties`或`application.yml`文件中添加以下配置: ```yaml aliyun.sms.accessKeyId=your-access-key-id aliyun.sms.accessKeySecret=your-access-key-secret aliyun.sms.regionId=cn-hangzhou aliyun.sms.signName=your-sign-name aliyun.sms.templateCode=your-template-code ``` 其中,`your-access-key-id`和`your-access-key-secret`是在阿里云短信服务中***,根据实际情况进行设置;`your-sign-name`是短信签名的名称,需要根据实际情况进行设置;`your-template-code`是短信模板的编码,需要根据实际情况进行设置。 5. 接下来,可以在项目中创建一个短信发送的工具类。可以创建一个`SmsUtil`类,其中含发送短信的方法。在方法中,可以使用阿里云短信服务提供的SDK来发送短信。可以参考阿里云的官方文档和示例代码来编写发送短信的逻辑。 6. 最后,在需要发送短信的地方调用`SmsUtil`类中的发送短信方法即可实现发送短信的功能。 综上所述,以上是使用Spring Boot整合阿里云短信服务的一般步骤。具体实现过程可以参考引用中的文章,该文章详细介绍了整合阿里云短信服务的每一步过程,并且将验证码存放到Redis中并设置过期时间,以保证实现发短信的功能。同时,引用中的项目简介也提供了一些有关Spring Boot的其他整合开发工具和配置的信息,可以参考其中的内容。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [SpringBoot整合阿里云短信服务详细过程(保证初学者也能实现)](https://blog.csdn.net/weixin_47316183/article/details/124909807)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [springboot-demo:基于SpringBoot 2.x整合各种常用开发工具,括但不限于Redis,MyBatisPlus,RocketMQ,...](https://download.csdn.net/download/weixin_42127754/18369068)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

堕落年代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值