天天看点

java 实现阿里云短信接口的后台全部实现逻辑

1: 项目地址

https://gitee.com/itliulei/sms-aliyun-demo.git
           

对接阿里短信服务,首先需要准备的有SignName ,TemplateCode ,AccessKeyId,AccessSecret,前面两个是在阿里短信服务里面创建的,一个是短信签名名称,一个是短信要使用的模板id,后面两个我理解的意思就是获取权限,给你登录的账号密码差不多,准备好这些,就可以写java的后台对接逻辑了

注意:如果你时间比较急,那就重点研究SmsClient 和SmsAliYunClient ,就这俩在其作用,其他的只是把调用发送短信流程补充完整

项目的目录(这就是我写的一个专门测试阿里短信起的一个项目)

java 实现阿里云短信接口的后台全部实现逻辑

下面分运行顺序进行代码粘贴

loginController

@RestController
@RequestMapping("/sys")
public class loginController {
    @Autowired
    private SmsClient smsClient;
    //调用本接口测试调用阿里接口
    @GetMapping("/getVerificationCode")
    public Result getVerificationCodeOfMember(@RequestParam String mobile){
        Result result=new Result();
        result.setSuccess(false);
        String code= RandomUtil.randomNumbers(4);
        for (;;){

            if (!code.startsWith("0")){
                break;
            }
            code=RandomUtil.randomNumbers(4);

        }
        if (StringUtils.isEmpty(mobile)){
            result.setMessage("手机号不能为空");
            return result;
        }
        VerificationCode verificationCode=new VerificationCode();
        verificationCode.setCode(code);
        //这里就是调用好发送
        smsClient.singleSendVerificationCode(mobile,code);

        return Result.ok(verificationCode);
    }
}

           

SmsClient (短信平台)接口

public interface SmsClient {

    //单一发送验证码 2:寻找接口
    SendResult singleSendVerificationCode(String mobile, String code);

    @Data
    @Accessors(chain = true)
    class SendResult {

        public static final int SUCCESS_CODE = 0;
        public static final int ERROR_CODE = 1;
        public static final String SUCCESS_MESSAGE = "SUCCESS";

        /**
         * 错误码
         */
        private Integer code;
        /**
         * 错误信息
         */
        private String message;
        /**
         * 是否成功
         */
        private Boolean isSuccess;
    }

    /**
     * 短信发送 - 单个
     *
     * @param mobile 手机号
     * @param sign 签名
     * @param templateCode 短信模板code
     * @param template 短信模板
     * @param templateParams 短信模板 params
     * @return 发送后信息
     */
    SendResult singleSend(String mobile, String sign, String templateCode,
                          String template, Map<String, String> templateParams);

    /**
     *
     * @param mobile
     * @param templateParams
     * @return
     */
    SendResult singleSendMsg(String mobile, Map<String, String> templateParams);

    /**
     * 短信发送 - 批量
     *
     * @param mobileList 手机号
     * @param sign 签名
     * @param templateCode 短信模板 code
     * @param template 短信模板
     * @param templateParams 短信模板params
     * @return 发送后信息
     */
    SendResult batchSend(List<String> mobileList, String sign, String templateCode,
                         String template, Map<String, String> templateParams);
}
           

SmsAliYunClient 短信平台接口实现类

public class SmsAliYunClient implements SmsClient {

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

    private static final String DOMAIN = "dysmsapi.aliyuncs.com";
    private static final String SUCCESS_CODE = "OK";
    private static final String SUCCESS_MESSAGE = "OK";
    /**
     * 阿里云短信 - 批量推送最大数 500,支持 1000
     */
    private static final int MAX_BATCH_SIZE = 500;

    @Value("${sms.aliYun.accessKeyId?:'default_value'}")
    private String accessKeyId;
    @Value("${sms.aliYun.accessSecret?:'default_value'}")
    private String accessSecret;




    @Accessors(chain = true)
    @Data
    public static class Result {
        /**
         * 发送回执ID,可根据该ID在接口QuerySendDetails中查询具体的发送状态。
         */
        private String BizId;
        /**
         * 请求状态码。
         *
         * - OK 蔡成功
         */
        private String Code;
        /**
         * 状态码的描述。
         */
        private String Message;
        /**
         * 请求ID。
         */
        private String RequestId;
    }

    @Data
    private class  VerificationCode{
        private String mobile;
        private String code;

        public VerificationCode(String mobile, String code) {
            this.mobile = mobile;
            this.code = code;
        }
    }
    //单一发送验证码 3:接口的实现类
    @Override
    public SendResult singleSendVerificationCode(String mobile,String code) {

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);//接收短信的手机号码。
        request.putQueryParameter("SignName","然***" ); //短信签名名称。请在控制台签名管理页面签名名称一列查看。说明 必须是已添加、并通过审核的短信签名。
        request.putQueryParameter("TemplateCode", "S*S_15*******5");//短信模板ID。请在控制台模板管理页面模板CODE一列查看。
        request.putQueryParameter("TemplateParam", "{code:"+code+"}");//短信模板变量对应的实际值,JSON格式。
        // 发送请求
        return doSend(request);
    }

    @Override
    public SendResult singleSend(String mobile, String sign, String templateCode,
                                 String template, Map<String, String> templateParams) {
        // params
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", sign);//短信签名名称。请在控制台签名管理页面签名名称一列查看。说明 必须是已添加、并通过审核的短信签名。
        request.putQueryParameter("TemplateCode", templateCode);//短信模板ID。请在控制台模板管理页面模板CODE一列查看。
        request.putQueryParameter("TemplateParam", JSON.toJSONString(templateParams));//短信模板变量对应的实际值,JSON格式。

        // 发送请求
        return doSend(request);
    }

    @Override
    public SendResult singleSendMsg(String mobile, Map<String, String> templateParams) {
        // params
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "然***");
        request.putQueryParameter("TemplateCode", "SMS_15********5");
        request.putQueryParameter("TemplateParam", JSON.toJSONString(templateParams));

        // 发送请求
        return doSend(request);
    }

    @Override
    public SendResult batchSend(List<String> mobileList, String sign, String templateCode,
                                String template, Map<String, String> templateParams) {

        // 最大发送数为 1000,我们设置为 500 个, 分段发送
        int maxSendSize = MAX_BATCH_SIZE;
        int maxSendSizeCount = mobileList.size() % maxSendSize == 0
                ? mobileList.size() / maxSendSize
                : mobileList.size() / maxSendSize + 1;

        SendResult sendResult = null;
        for (int i = 0; i < maxSendSizeCount; i++) {
            // 分批发送
            List<String> batchSendMobile = mobileList
                    .subList(i * maxSendSize, (i + 1) * maxSendSize);

            // params
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain(DOMAIN);
            request.setVersion("2017-05-25");
            request.setAction("SendBatchSms");
            request.putQueryParameter("PhoneNumberJson", JSON.toJSONString(batchSendMobile));
            request.putQueryParameter("SignNameJson", JSON.toJSONString(Collections.singletonList(sign)));
            request.putQueryParameter("TemplateCode", templateCode);
            request.putQueryParameter("TemplateParamJson", JSON.toJSONString(Collections.singletonList(templateParams)));

            // 发送请求
            sendResult = doSend(request);
        }
        return sendResult;
    }
    //单一发送验证码 4:调用发送方法
    private SendResult doSend(CommonRequest request) {
        // 获取 client
        IAcsClient client = getClient();
        try {
            CommonResponse response = client.getCommonResponse(request);
            Result result = JSON.parseObject(response.getData(), Result.class);
            if (!SUCCESS_CODE.equals(result.getCode())) {

                LOGGER.info("发送验证码失败 params {} res {}", JSON.toJSON(request), JSON.toJSON(result));

                // 错误发送失败
                return new SendResult()
                        .setIsSuccess(false)
                        .setCode(SendResult.ERROR_CODE)
                        .setMessage(result.getMessage());
            } else {
                LOGGER.info("发送验证码成功 params {} res", JSON.toJSON(request), JSON.toJSON(result));

                // 发送成功
                return new SendResult()
                        .setIsSuccess(true)
                        .setCode(SendResult.SUCCESS_CODE)
                        .setMessage(result.getMessage());
            }
        } catch (ClientException e) {
            LOGGER.error("发送验证码异常 {}", ExceptionUtils.getMessage(e));
            return new SendResult()
                    .setIsSuccess(false)
                    .setCode(SendResult.ERROR_CODE)
                    .setMessage(ExceptionUtils.getMessage(e));
        }
    }

    /**
     * 获取 client
     *
     * @return
     */
    //AccessKeyId和AccessSecret在阿里云的RAM访问控制添加AccessKey获取
    //拿到AccessKeyId(主账号AccessKey的ID。示例:LTAIP00vvvvvvvvv) 和 AccessSecret
    private IAcsClient getClient() {
        return new DefaultAcsClient(DefaultProfile.getProfile("default", "LTA************NJ8", "qJdL******************3Kiv"));
    }
           

用到的一个实体类

@Data
public class VerificationCode {
    private String code;
}
           

用到的返回结果分装类

Result

public class Result<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 成功标志
	 */
	private boolean success = true;

	/**
	 * 返回处理消息
	 */
	private String message = "操作成功!";

	/**
	 * 返回代码
	 */
	private Integer code = 0;
	
	/**
	 * 返回数据对象 data
	 */
	private T result;
	
	/**
	 * 时间戳
	 */
	private long timestamp = System.currentTimeMillis();

	public Result() {
		
	}
	
	public Result<T> error500(String message) {
		this.message = message;
		this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
		this.success = false;
		return this;
	}
	
	public Result<T> success(String message) {
		this.message = message;
		this.code = CommonConstant.SC_OK_200;
		this.success = true;
		return this;
	}
	
	
	public static Result<Object> ok() {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setMessage("成功");
		return r;
	}
	
	public static Result<Object> ok(String msg) {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setMessage(msg);
		return r;
	}
	
	public static Result<Object> ok(Object data) {
		Result<Object> r = new Result<Object>();
		r.setSuccess(true);
		r.setCode(CommonConstant.SC_OK_200);
		r.setResult(data);
		return r;
	}
	
	public static Result<Object> error(String msg) {
		return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg);
	}
	
	public static Result<Object> error(int code, String msg) {
		Result<Object> r = new Result<Object>();
		r.setCode(code);
		r.setMessage(msg);
		r.setSuccess(false);
		return r;
	}
	
	/**
	 * 无权限访问返回结果
	 */
	public static Result<Object> noauth(String msg) {
		return error(CommonConstant.SC_JEECG_NO_AUTHZ, msg);
	}
}
           

使用的依赖

<!--调用阿里短信使用的依赖-->
     <properties>
        <java.version>1.8</java.version>
        <!--调用阿里短信使用的依赖版本-->
        <commons.version>2.6</commons.version>
        <aliyun-java-sdk-core.version>4.1.0</aliyun-java-sdk-core.version>
        <aliyun-java-sdk-dysmsapi.version>1.0.0</aliyun-java-sdk-dysmsapi.version>
        <!--调用阿里短信使用的依赖版本-->
    </properties>
	<dependencies>
        <!-- 阿里云短信 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>${aliyun-java-sdk-dysmsapi.version}</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>${aliyun-java-sdk-core.version}</version>
        </dependency>
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--随机数-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.5.11</version>
        </dependency>
        <!-- commons -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>${commons.version}</version>
        </dependency>
        <!-- json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
    <!--调用阿里短信使用的依赖-->
 </dependencies>
           

阿里获取签名等的截图

java 实现阿里云短信接口的后台全部实现逻辑
java 实现阿里云短信接口的后台全部实现逻辑
java 实现阿里云短信接口的后台全部实现逻辑