Java实现短信发送业务

1、业务需求

发送短信功能是一个很普遍的需求,比如验证码,快递单号,通知信息一类。 而在Java中实现短信功能相对简单,只需要调用短信服务商提供的API。接下来以阿里云为例,介绍如何实现短信发送功能,其他短信服务商也是类似的操作。

2、短信发送逻辑

阿里云短信发送逻辑大致总结为:提供登录阿里云的账号(AccessKey ID)和密码(AccessKey Secret)登录后,选择对应的短信签名模版,填充对应的短信内容(模版参数),然后将短信发送到指定的手机号

签名:短信开头时【】内的公司信息

模板:短信内容的骨架,可填充对应参数

注意:阿里云短信服务申请签名主要针对企业开发,个人申请时有一定难度,在审核时会审核资质,需要上传营业执。但阿里云提供了测试签名和测试模板,开发测试时只需要获取对应的测试签名和测试模板。

  • 获取AccessKeyId和AccessKeySecret,点击头像右上角的AccessKey管理按钮后获取。

  • 获取测试签名和模板

3、代码实现

目前阿里云短信服务的SDK分为1.0版本和2.0版本,1.0已经不再维护,推荐使用2.0版本,下面列举了两种方式的实现代码。

  • 2.0版本

(1) Maven方式引入pom依赖

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

(2) 代码编写

代码逻辑:创建发送短信的客户端,提供参数调用对应方法即可。 需要提供下面几个参数:

  • AccessKey ID:类似登录阿里云时的账号
  • AccessKey Secret:类似登录阿里云的密码
  • phone:接收短信的号码
  • signName:短信签名,即短信开头时【】内的公司信息
  • templateCode:模版编码,即短信内容的骨架
  • templateParam:模版参数,即要往短信模版骨架中填充的内容
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;

public class SMSUtils {
    /**
     * 阿里云登录id
     */
    private final static String ACCESS_KEY_ID = "your access key id";

    /**
     * 阿里云登录密码
     */
    private final static String ACCESS_KEY_SECRET = "your access key secret";

    /**
     * 初始化登录阿里云的Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
        .setAccessKeyId(accessKeyId)
        .setAccessKeySecret(accessKeySecret);
        // 可指定登录的服务器地址,可参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信方法
     * @param phoneNumbers 手机号
     * @param signName 签名
     * @param templateCode  模板编号
     * @param param 模板参数
     * @throws Exception
     */
    public static void sendMessage(String phoneNumbers, String signName, String templateCode, String param) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = SMSUtils.createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
        .setPhoneNumbers(phoneNumbers)
        .setSignName(signName)
        .setTemplateCode(templateCode)
        .setTemplateParam(param);
        SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
        System.out.println("短信发送成功,返回结果是:"+sendSmsResponse);
    }

    public static void main(String[] args) {
        try {
            SMSUtils.sendMessage("15179068888", "阿里云短信测试", "SMS_154958888", "{\"code\":\"7777\"}");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

  • 1.0版本

(1) Maven方式引入pom依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.5.16</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.1.0</version>
</dependency>

(2) 代码编写

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;

/**
 * 短信发送工具类
 */
public class SMSUtils {
   /**
    * 发送短信
    * @param signName 签名
    * @param templateCode 模板
    * @param phoneNumbers 手机号
    * @param param 模板参数
    */
   public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
      // client的参数,服务器ip, accessKeyId, accessKeySecret 
      DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "xxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxx");
      // 登录client
      IAcsClient client = new DefaultAcsClient(profile);

      SendSmsRequest request = new SendSmsRequest();
      request.setSysRegionId("cn-hangzhou");
      request.setPhoneNumbers(phoneNumbers);
      request.setSignName(signName);
      request.setTemplateCode(templateCode);
      request.setTemplateParam("{\"code\":\""+param+"\"}");
      try {
         SendSmsResponse response = client.getAcsResponse(request);
         System.out.println("短信发送成功");
      }catch (ClientException e) {
         e.printStackTrace();
      }
   }
}
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送短信验证码可以通过使用第三方短信服务提供商的API来实现。以下是一个简单的示例代码,演示如何使用阿里云短信服务发送短信验证码: ```java import com.aliyun.dysmsapi20170525.models.SendSmsRequest; import com.aliyun.dysmsapi20170525.models.SendSmsResponse; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teaopenapi.modules.AcsClient; import com.aliyun.teaopenapi.modules.exceptions.ServerException; import com.aliyun.teaopenapi.modules.exceptions.ClientException; public class SmsSender { public static void main(String[] args) { // 配置AK、SK和短信签名等信息 Config config = new Config() .setAccessKeyId("yourAccessKeyId") .setAccessKeySecret("yourAccessKeySecret") .setEndpoint("dysmsapi.aliyuncs.com") .setRegionId("yourRegionId"); // 创建AcsClient实例 AcsClient acsClient = new AcsClient(config); // 构造请求对象 SendSmsRequest request = new SendSmsRequest() .setPhoneNumbers("yourPhoneNumber") .setSignName("yourSignName") .setTemplateCode("yourTemplateCode") .setTemplateParam("{\"code\":\"123456\"}"); try { // 发送短信 SendSmsResponse response = acsClient.sendSms(request); System.out.println("短信发送成功,请求ID:" + response.getRequestId()); } catch (ServerException e) { System.out.println("短信发送失败,错误码:" + e.getErrCode() + ",错误信息:" + e.getErrMsg()); } catch (ClientException e) { System.out.println("短信发送失败,错误码:" + e.getErrCode() + ",错误信息:" + e.getErrMsg()); } } } ``` 请注意,上述代码中的`yourAccessKeyId`、`yourAccessKeySecret`、`yourRegionId`、`yourPhoneNumber`、`yourSignName`和`yourTemplateCode`需要替换为你自己的实际值。其中,`yourAccessKeyId`和`yourAccessKeySecret`是阿里云账号的AccessKey ID和AccessKey Secret,`yourRegionId`是短信服务所在的地域ID,`yourPhoneNumber`是接收验证码的手机号码,`yourSignName`是短信签名,`yourTemplateCode`是短信模板ID。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值