天天看點

基于阿裡雲短信發送

申請秘鑰

#短信發送
  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();
        }
    }
}