java使用阿里云短信服务发送短信验证码

需要依赖的pom:

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>2.0.1</version>
        </dependency> 


java代码:



package com.ehl.developerplatform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ehl.developerplatform.config.SmsProperties;
import com.ehl.developerplatform.enums.ResponseEnum;
import com.ehl.developerplatform.exception.DeveloperPlatFormException;
import com.ehl.developerplatform.pojo.DataResponse;
import com.ehl.developerplatform.util.RedisPrefix;
import com.ehl.developerplatform.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * #------------------------------------------------------------------- #
 * #                   CONFIDENTIAL --- CUSTOM STUDIOS                  #
 * #------------------------------------------------------------------- #
 * #                                                                    #
 * #                   @Project Name : develop                          #
 * #                                                                    #
 * #                   @File Name    : SmsService.java                  #
 * #                                                                    #
 * #                   @Programmer   : 王震                              #
 * #                                                                    #
 * #                   @Start Date   : 2021/4/28 18:08                  #
 * #                                                                    #
 * #                   @Last Update  : 2021/4/28 18:08                  #
 * #                                                                    #
 * #------------------------------------------------------------------- #
 * # Classes:                                                           #
 * #                                                                    #
 * #------------------------------------------------------------------- #
 */

@Slf4j
@Service
@SuppressWarnings("all")
@EnableConfigurationProperties(value = SmsProperties.class)
public final class SmsService {

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private RedisUtil redisUtil;

    private SmsService() {

    }

    /**
     * 功能描述: <br>
     * 〈根据用户输入的phone发送验证码〉
     *
     * @Param: [phone] 电话号码
     * @Return: com.ehl.developerplatform.pojo.DataResponse
     * @Author: 王震
     * @Date: 2021/4/28 19:01
     */
    public DataResponse<?> sendSmsCode(final String phone) {
        String code = this.randomCode();
        String message = this.sendMessage(phone, code).getBody().getMessage();
        if (!"OK".equals(message)) {
            log.error("手机号码:{},发送短信失败,失败原因:{},code:{}", phone, message,code);
            return DataResponse.fail(ResponseEnum.SEND_MESSAGE_ERROR);
        }
        log.info("手机号码:{},发送短信成功,验证码为:{}", phone, code);
        redisUtil.set(RedisPrefix.buildSendMessageKey(phone), code, 300);
        return DataResponse.success("短信发送成功!");
    }


    public SendSmsResponse sendMessage(final String phone, final String code) {
        try {
            com.aliyun.dysmsapi20170525.Client client = createClient(smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
            Map<String, Object> map = new HashMap<>();
            map.put("code", code);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplate())
                    .setPhoneNumbers(phone)
                    .setTemplateParam(JSONObject.toJSONString(map));
            // 复制代码运行请自行打印 API 的返回值
            return client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("手机号码:{},发送短信失败,失败原因:{}", phone, e.getMessage());
            throw new DeveloperPlatFormException(ResponseEnum.SEND_MESSAGE_ERROR);
        }
    }


    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(final String accessKeyId, final String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    /**
     * 功能描述: <br>
     * 〈随机数6位〉
     *
     * @Return: com.ehl.developerplatform.pojo.DataResponse
     * @Author: 王震
     * @Date: 2021/4/28 19:34
     */
    private String randomCode() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
    }


}
 



一些项目中的redis工具类、就不贴了,朋友们可以自行替换成自己的。

上一篇:同一域名对应多个IP时,PHP获取远程网页内容的函数


下一篇:《版式设计——日本平面设计师参考手册》—第1章表