Java 后台实现通过阿里云短信api发送短信验证码

一、前言
在实际项目中, 涉及用户登录或者注册时,可能需要有多种登录方式,通过用户密码登录或者手机号验证码登录,那么当使用验证码登录时,就需要发送手机验证码,下面就具体说明如何通过aliyun 短信Api实现发送验证码的功能。

二、如何实现发送验证码?
1.引入阿里云短信相关的Maven依赖。

 <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.1.0</version>
        </dependency>

2.编写发送短信验证码的工具类AliyunSmsUtils。

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

public class AliyunSmsUtils {

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    //static final String domain = "dysmsapi.aliyuncs.com";
    static final String domain = "dysmsapi-vpc.cn-hangzhou.aliyuncs.com";

    // 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = “*******”;  // TODO 修改成自己的
    static final String accessKeySecret = "******";   // TODO 修改成自己的

    public static final String templateCode = "SMS_190729219";

    public static final String signName = "*xx科技";
    public static boolean sendCheckCode(String phone, String code) {
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            SendSmsRequest request = new SendSmsRequest();

            request.setPhoneNumbers(phone);
           //必填:短信签名-可在短信控制台中找到
            request.setSignName(signName);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);
			//可选:模板中的变量替换JSON串,如模板内容为"您的验证码为${code}"时,此处的值为
			//"{\"code\":\"" + code + "\"}"
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                System.out.println("短信发送成功!");
            } else {
                System.out.println("短信发送失败!");
            }
            String codeStr = sendSmsResponse.getCode();
            if (codeStr == null) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
            /**
     * 发送短信
     * @return
     * @throws ClientException
     */
    public static String sendSmsCommon(String telephone, String templateCode, String signName,String templateParam) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(telephone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
       // request.setTemplateParam("{\"name\":\"Jack\", \"code\":\"123\"}");
        request.setTemplateParam(templateParam);
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");
        //hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            System.out.println("短信发送成功!");
        } else {
            System.out.println("短信发送失败!");
        }
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + sendSmsResponse.getCode());
        System.out.println("Message=" + sendSmsResponse.getMessage());
        System.out.println("RequestId=" + sendSmsResponse.getRequestId());
        System.out.println("BizId=" + sendSmsResponse.getBizId());
        String codeStr = sendSmsResponse.getCode();
        if (codeStr == null) {
            return "error";
        }
        return codeStr;
    }
}

3.接着我们通过main方法调用。

/**
     * 获取6为随机数,发验证码用
     *
     * @return
     * @throws
     */
    public static String getSixCode() {

        String str = "0123456789";
        Random r = new Random();
        String arr[] = new String[6];
        String b = "";
        for (int i = 0; i < 6; i++) {
            int n = r.nextInt(9);
            arr[i] = str.substring(n, n + 1);
            b += arr[i];
        }
        return b;
    }
  public static void main(String[] args) throws ClientException, InterruptedException {
        String code = getSixCode();
        String responCode = sendSmsCommon("151****0699",templateCode,signName,""{\"code\":\"" + code + "\"}"");
        
        if ("OK".equals(responCode)) {
            System.out.println("发送的验证码为:" + code);
        } else {
            System.out.println("error“);
        }
   }

main方法执行后,如果发送成功,则会打印发送的验证码,否则打印 errror。

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用阿里云发送短信,你需要进行以下步骤: 1. 注册阿里云账号,并开通短信服务。 2. 创建短信模板,并审核通过。 3. 获取 AccessKeyId 和 AccessKeySecret。 4. 导入阿里云 SDK。 5. 编写发送短信Java 代码。 以下是一个简单的 Java 代码示例,可以用于发送短信: ```java import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.sms.model.v20160927.SendSmsRequest; import com.aliyuncs.sms.model.v20160927.SendSmsResponse; public class AliyunSms { public static void main(String[] args) { String accessKeyId = "your_accessKeyId"; String accessKeySecret = "your_accessKeySecret"; // 设置超时时间和 regionId IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Sms", "sms.aliyuncs.com"); // 构造请求 SendSmsRequest request = new SendSmsRequest(); request.setPhoneNumbers("手机号码"); request.setSignName("短信签名"); request.setTemplateCode("短信模板ID"); request.setTemplateParam("{\"code\":\"12345\"}"); // 发送请求 IAcsClient client = new DefaultAcsClient(profile); try { SendSmsResponse response = client.getAcsResponse(request); System.out.println("短信发送成功!"); } catch (ServerException e) { e.printStackTrace(); System.out.println("短信发送失败!"); } catch (ClientException e) { e.printStackTrace(); System.out.println("短信发送失败!"); } } } ``` 其中,需要将 `your_accessKeyId` 和 `your_accessKeySecret` 替换为你自己的 AccessKeyId 和 AccessKeySecret,同时将 `手机号码`、`短信签名` 和 `短信模板ID` 替换为你自己创建的短信模板相关信息。`{\"code\":\"12345\"}` 是短信模板中需要替换的内容,可以根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜空下的星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值