使用java语言操作阿里云短信服务api发送随机短信验证码

导入依赖

  <!-- https://mvnrepository.com/artifact/com.aliyun/dysmsapi20170525 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>2.0.23</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-openapi</artifactId>
            <version>0.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-console</artifactId>
            <version>0.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-util</artifactId>
            <version>0.2.16</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea</artifactId>
            <version>1.1.14</version>
        </dependency>
package com.shujia.jinjie;

import com.aliyun.tea.TeaException;
import redis.clients.jedis.Jedis;

import java.util.Random;

public class CodeTool {
    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId("LTAI5t7hMgiV7LNA7JN68LYr")
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret("7Dq5nmGrB45gfN48RHbf6f5aaaaLsV");
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static String createRandomCode(User user) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 1; i <= 6; i++) {
            sb.append(random.nextInt(9) + 1);
        }

        String code = sb.toString();

        //放入到redis中,并设置过期时间
        Jedis redisConnection = RedisTool.getRedisConnection();
        String name = user.getName();
        if(redisConnection.exists(name)){
            code = null;
        }else {
            redisConnection.set(name,code);
            //设置过期时间
            redisConnection.expire(name,60);
        }

        return code;
    }

    public static String sendCode(User user) {
        String status = null;
        try {

            //生成验证码
            String yzm = createRandomCode(user);

            if(yzm!=null){
                com.aliyun.dysmsapi20170525.Client client = CodeTool.createClient();
                com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                        .setSignName("数加科技")
                        .setTemplateCode("SMS_474800760")
                        .setPhoneNumbers(user.getPhoneNumber())
                        .setTemplateParam("{\"code\":\"" + yzm + "\"}");
                com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
                // 复制代码运行请自行打印 API 的返回值
//            client.sendSmsWithOptions(sendSmsRequest, runtime);
                com.aliyun.dysmsapi20170525.models.SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
                com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
                Integer statusCode = resp.statusCode;
//            System.out.println(statusCode);
                status = resp.getBody().getMessage();
//            System.out.println("---------------");
//            System.out.println(info);
//            System.out.println("---------------");
            }else {
                System.out.println("请勿重复发送验证码,60s后重试!");
            }
        } catch (TeaException error) {
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return status;
    }
}
posted @ 2025-02-26 21:07  Xiaohu_BigData  阅读(58)  评论(0)    收藏  举报