基于阿里云短信发送

申请秘钥

  #短信发送
  SMS:
    accessKeyId: LTAI5tEQPHJRsQSgUZehsL96
    accessKeySecret: Mz3ekWTJqZ3A1MCht3Vxl4XES2yA7X

工具类

package com.tianqiauto.base.utils;

import com.alibaba.fastjson.JSON;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Description 基于阿里云短信发送工具类
 * @Author wjx
 * @Date 2023/2/14 15:32
 **/

@Component
public class SMSSendUtils implements EnvironmentAware {

    private static Logger log = LoggerFactory.getLogger(SMSSendUtils.class);

    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";

    private static final String REGION_ID = "cn-hangzhou";

    private static final String OK = "OK";

    private static String ACCESS_KEY_ID;

    private static String ACCESS_KEY_SECRET;


    @Override
    public void setEnvironment(Environment environment) {
        ACCESS_KEY_ID = environment.getProperty("com.SMS.accessKeyId");
        ACCESS_KEY_SECRET = environment.getProperty("com.SMS.accessKeySecret");
    }

    /**
     * @Description 发送短信
     * @Param signName 签名
     * @Param templateCode 模板号
     * @Param phoneNumbers 手机号。支持对多个手机号码发送短信,手机号码之间以半角逗号(,)分隔。上限为1000个手机号码
     * @Param templateParamJson 短信模板变量对应的实际值。支持传入多个参数,示例:{"name":"张三","number":"1390000****"}
     *                          短信模板规范请参考官网:https://help.aliyun.com/document_detail/108253.html?spm=api-workbench.API%20Explorer.0.0.4d4830c3IUTY8W
     * @Return boolean 短信是否发送成功
     * @Author wjx
     * @Date 2023/2/14 16:09
     **/
    public static boolean sendMessage(String signName, String templateCode, String phoneNumbers, String templateParamJson) throws ExecutionException, InterruptedException {
        //短信发送成功标识。由于局部变量不能在lambda中进行操作,所以用该伪局部变量代替。
        boolean[] success = {true};
        AsyncClient client = null;

        try {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(ACCESS_KEY_ID)
                    .accessKeySecret(ACCESS_KEY_SECRET)
                    //.securityToken("<your-token>") // use STS token
                    .build());

            // Configure the Client
            client = AsyncClient.builder()
                    .region(REGION_ID) // 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(ENDPOINT)
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();

            // Parameter settings for API request
            SendSmsRequest.Builder builder = SendSmsRequest.builder();
            builder.phoneNumbers(phoneNumbers);
            builder.signName(signName);
            builder.templateCode(templateCode);
            builder.templateParam(templateParamJson);
            SendSmsRequest sendSmsRequest = builder.build();
            // Request-level configuration rewrite, can set Http request parameters, etc.
            // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))

            log.info("【短信发送请求信息】" + JSON.toJSONString(sendSmsRequest));
            // Asynchronously get the return value of the API request
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            response.get();
            // Asynchronous processing of return values
            response.thenAccept(res -> {
                if (res != null && OK.equalsIgnoreCase(res.getBody().getCode())){
                    log.info("【短信发送返回结果】" + new Gson().toJson(res));
                }else {
                    log.error("【短信发送返回数据有误】,返回数据如下:" + JSON.toJSONString(res));
                }
            }).exceptionally(throwable -> { // Handling exceptions
                if (success[0]) success[0] = false;
                log.error("【短信发送错误】,错误原因:" + throwable.getMessage());
                return null;
            });
            return success[0];
        }catch (Exception e){
            throw e;
        }finally {
            if (client != null) client.close();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值