阿里云短信服务

阿里云短信服务

短信服务(Short Message Service)是广大企业客户快速触达手机用户所优选使用的通信能力。调用API或用群发助手,即可发送验证码、通知类和营销类短信;国内验证短信秒级触达,到达率最高可达99%;国际/港澳台短信覆盖200多个国家和地区,安全稳定,广受出海企业选用。

进入阿里云开通短信服务

现在阿里云已经不支持个人申请未上线的业务,可以去云市场买第三方的短信服务

直接拿来用就可以

  1. 引入依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    </dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    </dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    </dependency>
  2. 添加配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    # 服务端口
    server.port=8204
    # 服务名
    spring.application.name=service-msm

    #返回json的全局时间格式
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    spring.jackson.time-zone=GMT+8

    spring.redis.host=192.168.134.134
    spring.redis.port=6379
    spring.redis.database= 0
    spring.redis.timeout=1800000
    spring.redis.lettuce.pool.max-active=20
    spring.redis.lettuce.pool.max-wait=-1
    #最大阻塞等待时间(负数表示没限制)
    spring.redis.lettuce.pool.max-idle=5
    spring.redis.lettuce.pool.min-idle=0

    # nacos服务地址
    spring.cloud.nacos.discovery.server-addr=localhost:8848
  3. 添加启动类

    1
    2
    3
    4
    5
    6
    7
    8
    @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //取消数据源自动配置
    @EnableDiscoveryClient
    @ComponentScan(basePackages = {"com.CPG"})
    public class ServiceMsmApplication {
    public static void main(String[] args) {
    SpringApplication.run(ServiceMsmApplication.class,args);
    }
    }
  4. 创建HttpUtils工具类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    public class HttpUtils {

    /**
    * get
    *
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @return
    * @throws Exception
    */
    public static HttpResponse doGet(String host, String path, String method,
    Map <String, String> headers,
    Map<String, String> querys)
    throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpGet request = new HttpGet(buildUrl(host, path, querys));
    for (Map.Entry <String, String> e : headers.entrySet()) {
    request.addHeader(e.getKey(), e.getValue());
    }

    return httpClient.execute(request);
    }

    /**
    * post form
    *
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param bodys
    * @return
    * @throws Exception
    */
    public static HttpResponse doPost(String host, String path, String method,
    Map <String, String> headers,
    Map <String, String> querys,
    Map <String, String> bodys)
    throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry <String, String> e : headers.entrySet()) {
    request.addHeader(e.getKey(), e.getValue());
    }

    if (bodys != null) {
    List <NameValuePair> nameValuePairList = new ArrayList <NameValuePair>();

    for (String key : bodys.keySet()) {
    nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
    }
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
    formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
    request.setEntity(formEntity);
    }

    return httpClient.execute(request);
    }

    /**
    * Post String
    *
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
    public static HttpResponse doPost(String host, String path, String method,
    Map <String, String> headers,
    Map <String, String> querys,
    String body)
    throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry <String, String> e : headers.entrySet()) {
    request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
    request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
    }

    /**
    * Post stream
    *
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
    public static HttpResponse doPost(String host, String path, String method,
    Map <String, String> headers,
    Map <String, String> querys,
    byte[] body)
    throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry <String, String> e : headers.entrySet()) {
    request.addHeader(e.getKey(), e.getValue());
    }

    if (body != null) {
    request.setEntity(new ByteArrayEntity(body));
    }

    return httpClient.execute(request);
    }

    /**
    * Put String
    *
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
    public static HttpResponse doPut(String host, String path, String method,
    Map <String, String> headers,
    Map <String, String> querys,
    String body)
    throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPut request = new HttpPut(buildUrl(host, path, querys));
    for (Map.Entry <String, String> e : headers.entrySet()) {
    request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
    request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
    }

    /**
    * Put stream
    *
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
    public static HttpResponse doPut(String host, String path, String method,
    Map <String, String> headers,
    Map <String, String> querys,
    byte[] body)
    throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPut request = new HttpPut(buildUrl(host, path, querys));
    for (Map.Entry <String, String> e : headers.entrySet()) {
    request.addHeader(e.getKey(), e.getValue());
    }

    if (body != null) {
    request.setEntity(new ByteArrayEntity(body));
    }

    return httpClient.execute(request);
    }

    /**
    * Delete
    *
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @return
    * @throws Exception
    */
    public static HttpResponse doDelete(String host, String path, String method,
    Map <String, String> headers,
    Map <String, String> querys)
    throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
    for (Map.Entry <String, String> e : headers.entrySet()) {
    request.addHeader(e.getKey(), e.getValue());
    }

    return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map <String, String> querys) throws UnsupportedEncodingException {
    StringBuilder sbUrl = new StringBuilder();
    sbUrl.append(host);
    if (!StringUtils.isBlank(path)) {
    sbUrl.append(path);
    }
    if (null != querys) {
    StringBuilder sbQuery = new StringBuilder();
    for (Map.Entry <String, String> query : querys.entrySet()) {
    if (0 < sbQuery.length()) {
    sbQuery.append("&");
    }
    if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
    sbQuery.append(query.getValue());
    }
    if (!StringUtils.isBlank(query.getKey())) {
    sbQuery.append(query.getKey());
    if (!StringUtils.isBlank(query.getValue())) {
    sbQuery.append("=");
    sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
    }
    }
    }
    if (0 < sbQuery.length()) {
    sbUrl.append("?").append(sbQuery);
    }
    }

    return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
    HttpClient httpClient = new DefaultHttpClient();
    if (host.startsWith("https://")) {
    sslClient(httpClient);
    }

    return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
    try {
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {
    public X509Certificate[] getAcceptedIssuers() {
    return null;
    }

    public void checkClientTrusted(X509Certificate[] xcs, String str) {

    }

    public void checkServerTrusted(X509Certificate[] xcs, String str) {

    }
    };
    ctx.init(null, new TrustManager[]{tm}, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = httpClient.getConnectionManager();
    SchemeRegistry registry = ccm.getSchemeRegistry();
    registry.register(new Scheme("https", 443, ssf));
    } catch (KeyManagementException ex) {
    throw new RuntimeException(ex);
    } catch (NoSuchAlgorithmException ex) {
    throw new RuntimeException(ex);
    }
    }
    }
  5. 创建MsmUtils工具类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    public class MsmUtils {

    /**
    * 发送验证码
    * @param mobile 手机号
    * @param code 发送的验证码
    */
    public static void sendMessage(String mobile,String code){
    String host = "https://dfsns.market.alicloudapi.com";
    String path = "/data/send_sms";
    String method = "POST";
    String appcode = "03e878fdb9054763afe0143f50b3526a";
    Map<String, String> headers = new HashMap<String, String>();
    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    headers.put("Authorization", "APPCODE " + appcode);
    //根据API的要求,定义相对应的Content-Type
    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    Map<String, String> querys = new HashMap<String, String>();
    Map<String, String> bodys = new HashMap<String, String>();
    bodys.put("content", "code:"+ code +",expire_at:2");
    bodys.put("phone_number", mobile);
    bodys.put("template_id", "TPL_0001");

    try {
    HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
    System.out.println(response.toString());
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
  6. 创建RandomUtils工具类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    public class RandomUtils {

    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    //生成四位验证码
    public static String getFourBitRandom() {
    return fourdf.format(random.nextInt(10000));
    }

    //生成六位验证码
    public static String getSixBitRandom() {
    return sixdf.format(random.nextInt(1000000));
    }

    /**
    * 给定数组,抽取n个数据
    * @param list
    * @param n
    * @return
    */
    public static ArrayList getRandom(List list, int n) {

    Random random = new Random();

    HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

    // 生成随机数字并存入HashMap
    for (int i = 0; i < list.size(); i++) {

    int number = random.nextInt(100) + 1;

    hashMap.put(number, i);
    }

    // 从HashMap导入数组
    Object[] robjs = hashMap.values().toArray();

    ArrayList r = new ArrayList();

    // 遍历数组并打印数据
    for (int i = 0; i < n; i++) {
    r.add(list.get((int) robjs[i]));
    System.out.print(list.get((int) robjs[i]) + "\t");
    }
    System.out.print("\n");
    return r;
    }
    }
  7. controller

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
    //从Redis中获取验证码,如果可以获取到,返回ok
    //key:手机号 value:验证码
    String code = redisTemplate.opsForValue().get(phone);
    if (!StringUtils.isEmpty(code)){
    return Result.ok();
    }

    //如果获取不到,生成验证码,通过整合短信服务进行发送
    code = RandomUtils.getSixBitRandom();
    //整合阿里云短信服务进行发送
    boolean isSend = msmService.send(phone,code);
    //生成的验证码放到redis中,设置有效时间
    if (isSend){
    redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
    return Result.ok();
    }else {
    return Result.fail().message("发送短信失败!");
    }
    }
  8. service

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    //发送手机验证码
    @Override
    public boolean send(String phone, String code) {
    //判断手机号是否为空
    if (StringUtils.isEmpty(phone)){
    return false;
    }
    //整合阿里云短信服务,设置相关参数
    MsmUtils.sendMessage(phone,code);
    return true;
    }

本站由 Cccccpg 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。