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

2022-02-12 第三方技术短信服务

不得不说,阿里云的文档真是太强大了,整体设计非常人性化,还提供了在线API调用控制台 (opens new window),当然官方文档 (opens new window)也少不了。

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

# application.yml

xk857:
  aliyun:
    accessKeyId: asdAI5*******mEpsdabfd1F
    accessKeySecret: UaUR**********NQa9dasb
    registerCode: SMS_123456789  # 注册短信模板
    signature: 星空小屋  # 短信签名

# 获取配置文件信息

@Data
@Component
@ConfigurationProperties(prefix = "xk857.aliyun")
public class AliyunProperties {

    /**
     * accessKeyId
     */
    private String accessKeyId;

    /**
     * accessKeySecret
     */
    private String accessKeySecret;

    /**
     * 注册短信模板
     */
    private String registerCode;

    /**
     * 短信签名
     */
    private String signature;
}

# 短信发送工具类

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.xk857.properties.AliyunProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author cv大魔王
 * @version 1.0
 * @description 阿里云短信发送工具类
 * @date 2022/8/12
 */
@Slf4j
@Component
public class AliSendCodeUtils {

    @Autowired
    private AliBaseBean aliBaseBean;

    @Autowired
    private AliyunProperties aliyunProperties;

    public boolean sendMsg(String phone, String code) {
        try {
            // 1.获取bean中的client实例
            Client client = aliBaseBean.createClient();

            // 2.根据参数构建客户端
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(aliyunProperties.getSignature())
                    .setTemplateCode(aliyunProperties.getRegisterCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            RuntimeOptions runtime = new RuntimeOptions();
            // 3.发送请求
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);

            if ("OK".equals(sendSmsResponse.body.message)) {
                // 代表消息发送成功
                log.info("[阿里云短信发送成功,提示信息:{}] 手机号码:{} 验证码:{}",sendSmsResponse.body.message,phone,code);
                return true;
            } else {
                // 消息发送失败,真实项目这里应该抛出异常,交给全局异常处理器处理
                log.info("[阿里云短信发送失败,提示信息:{}] 手机号码:{} 验证码:{}",sendSmsResponse.body.message,phone,code);
                return false;
            }
        } catch (TeaException error) {
            // 如有需要,请打印 error
            log.error(error.toString());
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

错误信息额外处理

上述消息发送成功返回"OK",发送失败会返回各种状态,一般返回官方的提示信息即可,如果想自己处理可以参考短信服务API错误码 (opens new window)

# 编写发送验证码接口

验证码一般是后台生成,保存到Redis中,可参考Redis实现验证码加防刷设计

@RestController("/")
public class TestController {

    @Autowired
    private AliSendCodeUtils aliSendCodeUtils;

    @GetMapping("/send/code/{phone}")
    public boolean sendCode(@PathVariable String phone) {
        // 这个验证码一般是后台生成的
        return aliSendCodeUtils.sendMsg(phone,"2234");
    }

}
上次更新: 2 年前