AliSmsHttpClient.java 2.74 KB
package com.diligrp.cashier.assistant.client;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.diligrp.cashier.assistant.domain.SmsMessage;
import com.diligrp.cashier.assistant.exception.AssistantServiceException;
import com.diligrp.cashier.shared.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;
import java.util.stream.Collectors;

public class AliSmsHttpClient {

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

    private final 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 AssistantServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "阿里云短信通道初始化错误");
        }
    }

    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 (Objects.nonNull(message.getParams())) {
            String json = message.getParams().entrySet().stream()
                .filter(p -> Objects.nonNull(p.getKey()) && Objects.nonNull(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 AssistantServiceException(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 AssistantServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "发送短信失败: " + body.getMessage());
        }
    }
}