AliSmsHttpClient.java 7.12 KB
package com.diligrp.assistant.sms.client;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.diligrp.assistant.shared.ErrorCode;
import com.diligrp.assistant.shared.util.ObjectUtils;
import com.diligrp.assistant.sms.domain.SmsMessage;
import com.diligrp.assistant.sms.domain.SmsTemplate;
import com.diligrp.assistant.sms.exception.SmsServiceException;
import com.diligrp.assistant.sms.type.TemplateState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.stream.Collectors;

public class AliSmsHttpClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliSmsHttpClient.class);

    private Client client;

    public AliSmsHttpClient(String endPoint, String accessKeyId, String accessKeySecret) {
        Config config = new Config().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret);
        config.endpoint = endPoint;
        try {
            this.client = new Client(config);
        } catch (Exception e) {
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "阿里云短信通道初始化错误");
        }
    }

    public String createSmsTemplate(SmsTemplate template) {
        AddSmsTemplateRequest request = new AddSmsTemplateRequest();
        request.setTemplateName(template.getName());
        request.setTemplateContent(template.getContent());
        request.setTemplateType(template.getType());
        request.setRemark(template.getDescription());

        AddSmsTemplateResponse response;
        try {
            response = this.client.addSmsTemplate(request);
        } catch (Exception ex) {
            LOGGER.error("Failed to create ali sms template", ex);
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "创建短信模板失败: 未知错误");
        }

        AddSmsTemplateResponseBody body = response.getBody();
        if ("OK".equalsIgnoreCase(body.getCode())) {
            return body.getTemplateCode();
        } else {
            LOGGER.error("Failed to create ali sms template, {}:{}", body.getCode(), body.getMessage());
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "创建短信模板失败: " + body.getMessage());
        }
    }

    public void modifySmsTemplate(SmsTemplate template) {
        UpdateSmsTemplateRequest request = new UpdateSmsTemplateRequest();
        request.setTemplateName(template.getName());
        request.setTemplateCode(template.getId());
        request.setTemplateContent(template.getContent());
        request.setTemplateType(template.getType());
        request.setRemark(template.getDescription());

        UpdateSmsTemplateResponse response;
        try {
            response = this.client.updateSmsTemplate(request);
        } catch (Exception ex) {
            LOGGER.error("Failed to modify ali sms template", ex);
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "修改短信模板失败: 未知错误");
        }

        UpdateSmsTemplateResponseBody body = response.getBody();
        if (!"OK".equalsIgnoreCase(body.getCode())) {
            LOGGER.error("Failed to modify ali sms template, {}:{}", body.getCode(), body.getMessage());
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "修改短信模板失败: " + body.getMessage());
        }
    }

    public TemplateState querySmsTemplateState(String templateId) {
        QuerySmsTemplateRequest request = new QuerySmsTemplateRequest();
        request.setTemplateCode(templateId);

        QuerySmsTemplateResponse response;
        try {
            response = this.client.querySmsTemplate(request);
        } catch (Exception ex) {
            LOGGER.error("Failed to query ali sms template", ex);
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "查询短信模板失败: 未知错误");
        }

        QuerySmsTemplateResponseBody body = response.getBody();
        if ("OK".equalsIgnoreCase(body.getCode())) {
            Integer state = body.getTemplateStatus();
            switch (state) {
                case 0 -> {
                    return TemplateState.PENDING;
                }
                case 1 -> {
                    return TemplateState.SUCCESS;
                }
                default -> {
                    LOGGER.info("Ali sms template audit not passed: {}", body.getReason());
                    return TemplateState.FAILED;
                }
            }
        } else {
            LOGGER.error("Failed to query ali sms template, {}:{}", body.getCode(), body.getMessage());
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "查询短信模板失败: " + body.getMessage());
        }
    }

    public void deleteSmsTemplate(String templateId) {
        DeleteSmsTemplateRequest request = new DeleteSmsTemplateRequest();
        request.setTemplateCode(templateId);

        DeleteSmsTemplateResponse response;
        try {
            response = this.client.deleteSmsTemplate(request);
        } catch (Exception ex) {
            LOGGER.error("Failed to delete ali sms template", ex);
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "删除短信模板失败: 未知错误");
        }

        DeleteSmsTemplateResponseBody body = response.getBody();
        if (!"OK".equalsIgnoreCase(body.getCode())) {
            LOGGER.error("Failed to delete ali sms template, {}:{}", body.getCode(), body.getMessage());
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "删除短信模板失败: " + body.getMessage());
        }
    }

    public String sendSmsMessage(SmsMessage message) {
        String telephones = message.getTelephones().stream().reduce((telephone1, telephone2) ->
            "".concat(telephone1).concat(",").concat(telephone2)).get();
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(telephones);
        request.setSignName(message.getSignature());
        request.setTemplateCode(message.getTemplateId());
        if (ObjectUtils.isNotEmpty(message.getParams())) {
            String json = message.getParams().stream()
                .filter(p -> ObjectUtils.isNotEmpty(p.getKey()) && ObjectUtils.isNotEmpty(p.getValue()))
                .map(p -> String.format("\"%s\": \"%s\"", p.getKey(), p.getValue()))
                .collect(Collectors.joining(",", "{", "}"));
            request.setTemplateParam(json);
        }

        SendSmsResponse response;
        try {
            response = this.client.sendSms(request);
        } catch (Exception ex) {
            LOGGER.error("Failed to send ali sms message", ex);
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "发送短信失败: 未知错误");
        }

        SendSmsResponseBody body = response.getBody();
        if ("OK".equalsIgnoreCase(body.getCode())) {
            return body.getBizId();
        } else {
            LOGGER.error("Failed to send ali sms message, {}:{}", body.getCode(), body.getMessage());
            throw new SmsServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "发送短信失败: " + body.getMessage());
        }
    }
}