最近在开发公司内部系统,其中涉及到了短信业务,公司选择了七牛云短信服务,具体实现方案如下:
一、引入pom依赖
<!-- 七牛短信--><dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId><version>7.9.0</version></dependency>
二、编写工具类
package com.example.xx.utils;import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import com.qiniu.util.Auth;public class SendMessageUtil {public static final String ACCESS_KEY = "";public static final String SECRET_KEY = "";public static final String SIGN_ID = "";/** 发送短信版本一,纯短信* 参数:手机号* */public static String sendMessage(String phone) {Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
// 实例化短信发送对象SmsManager smsManager = new SmsManager(auth);try {Response response = smsManager.sendMessage(SIGN_ID, new String[]{phone}, null);return response.bodyString();}catch (Exception e) {return "发送失败";}}/** 发送短信版本二、验证码类型* 参数:签名id、手机号、验证码* */public static String sendSms(String signId, String phone, String code){Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);// 实例化一个SmsManager对象SmsManager smsManager = new SmsManager(auth);HashMap<String, String> map = new HashMap<>();map.put("code", code);try {Response resp = smsManager.sendMessage(signId, new String[] {phone}, map);System.out.println(resp.bodyString());return resp.bodyString();} catch (QiniuException e) {return "发送失败";}}}
accessKey(AK)、secretKey(SK)、TemplateId(模板id)
查看ACCESS_KEY、SECRET_KEY 的值:七牛云控制台 => 密钥管理(提前创建)
查看SIGN_ID的值:七牛云控制台 => 云短信 SMS => 模板中查看(提前创建)
三、调用
在我们的业务中,直接调用该工具类,即可成功发送短信。