# 短信

阿里云 - 短信服务 费用 5 分

image-20231019114707641

短信基本上都需要

阿里云 - 短信服务使用步骤:

1. 签名 短信是哪个公司发起的,短信需要承担责任,要求先申请签名,还需要资质认证

image-20231019114437853

2. 模板 约定短信内容,不能乱发内容

image-20231019114553312

3. 短信设置 防止盗刷

image-20231019114737958

4. 发送短信

image-20231019114955470

5. 封装工具类

1. 依赖 jar

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

2. 编写工具类

public class AliSmsUtil {
    private static final String ID="";
    private static final String KEY="";
    private static Client client;

    static {
        Config config = new Config()
                // 必填,您的 AccessKey ID
                .setAccessKeyId(ID)
                // 必填,您的 AccessKey Secret
                .setAccessKeySecret(KEY);
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            client=new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @param code 验证码*/
    public static boolean sendCode(String phone,String code){
        SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("来自邢朋辉的短信")
                .setTemplateCode("SMS_115250125")
                .setTemplateParam("{\"code\":\""+code+"\"}");
        try {
            //发送短信
            SendSmsResponse response=client.sendSmsWithOptions(request, new RuntimeOptions());
            return response.body.code.equals("OK");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}