Java教程

阿里云短信发送

本文主要是介绍阿里云短信发送,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、阿里云短信SDK

官网: https://next.api.aliyun.com/api-tools/sdk/Dysmsapi?version=2017-05-25&language=java-tea

image

二、阿里云短信发送测试

2.1 添加pom依赖

<!-- 阿里云短信 -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20170525</artifactId>
    <version>2.0.9</version>
</dependency>
<!-- Json转换 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>

2.2 测试方法

package com.codertl.springboottest;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.HashMap;

@SpringBootTest
class SpringbootTestApplicationTests {

    @Test
    void contextLoads() {
        try {
            com.aliyun.dysmsapi20170525.Client client = createClient("自己的accessKeyId", "自己的accessKeySecret");
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            // 手机号  验证码  签名 模板ID
            sendSmsRequest.setPhoneNumbers("电话号码");
            sendSmsRequest.setSignName("签名名称");
            sendSmsRequest.setTemplateCode("模板code");
            HashMap<String, String> message = new HashMap<>();
            message.put("code", "验证码");
            sendSmsRequest.setTemplateParam(JSON.toJSONString(message));
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            System.out.println("sendSmsResponse.body.getCode() = " + sendSmsResponse.body.getCode());
            // sendSmsResponse.body.getCode() = OK
            
            System.out.println("sendSmsResponse.body.getBizId() = " + sendSmsResponse.body.getBizId());
            // sendSmsResponse.body.getBizId() = 729407549600103973^0
            
            System.out.println("sendSmsResponse.body.getMessage() = " + sendSmsResponse.body.getMessage());
            // sendSmsResponse.body.getMessage() = OK
            
            System.out.println("sendSmsResponse.body.getRequestId() = " + sendSmsResponse.body.getRequestId());
            // sendSmsResponse.body.getRequestId() = E0CFA674-1B03-586A-B640-DEE8B10FDA76
            
            System.out.println("sendSmsResponse.headers = " + sendSmsResponse.headers);
            // sendSmsResponse.headers = {access-control-allow-origin=*, date=Sun, 10 Apr 2022 14:15:04 GMT, content-length=110, access-control-max-age=172800, x-acs-request-id=E0CFA674-1B03-586A-B640-DEE8B10FDA76, access-control-allow-headers=X-Requested-With, X-Sequence, _aop_secret, _aop_signature, x-acs-action, x-acs-version, x-acs-date, Content-Type, connection=keep-alive, content-type=application/json;charset=utf-8, access-control-allow-methods=POST, GET, OPTIONS, PUT, DELETE, x-acs-trace-id=50a59994a48f50a0ea0299ec0eecfb43}
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}

三、Springboot整合阿里云短信

3.1 pom依赖

<!-- 阿里云短信 -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20170525</artifactId>
    <version>2.0.9</version>
</dependency>
<!-- Json转换 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>

3.2 application.yml内容

# 短信发送相关
sms:
  # accessKeyId
  accessKeyId: #accessKeyId
  # accessKeySecret
  accessKeySecret: #accessKeySecret
  # 签名
  signName: #签名
  #模板code
  templateCode: #模板code

3.2 service层

package com.system.system.service;

/**
 * 短信发送接口
 */
public interface ISysSendSms {

    /**
     * 短信发送
     * @param mobile 手机号
     * @param content 内容
     * @return
     */
    boolean sendSms(String mobile, String content);
}

3.3 service实现层

package com.system.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.system.system.service.ISysSendSms;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @Author: codertl
 * @Description:
 * @Date: 2022/4/10 19:53
 * @Version: 1.0
 */
@Service
public class SysSendSmsImpl implements ISysSendSms {

    @Value("${sms.accessKeyId}")
    private String accessKeyId;

    @Value("${sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${sms.signName}")
    private String signName;

    @Value("${sms.templateCode}")
    private String templateCode;

    /**
     * 短信发送
     * @param mobile 手机号
     * @param content 验证码内容
     * @return
     */
    @Override
    public boolean sendSms(String mobile, String content) {
        try {
            com.aliyun.dysmsapi20170525.Client client = createClient(accessKeyId, accessKeySecret);
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            // 手机号  验证码  签名 模板ID
            sendSmsRequest.setPhoneNumbers(mobile);
            sendSmsRequest.setSignName(signName);
            sendSmsRequest.setTemplateCode(templateCode);
            HashMap<String, Object> message = new HashMap<>();
            message.put("code", content);
            sendSmsRequest.setTemplateParam(JSON.toJSONString(message));
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            // 是否成功
            return "OK".equals(sendSmsResponse.body.getCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}

3.4 controller层

/**
     * 获取验证码
     */
@ApiImplicitParams({
    @ApiImplicitParam(value = "手机号", name = "phoneNumber", required = true, paramType = "query", dataType = "string", dataTypeClass = String.class),
})
@ApiOperation(value = "获取验证码", notes = "获取验证码", httpMethod = "GET")
@GetMapping("/getVerificationCode")
public AjaxResult getVerificationCode(
    @RequestParam("phoneNumber") String phoneNumber
) {
    return iSysUserService.getVerificationCode(phoneNumber);
}

3.5 service层

/**
* 获取验证码
* @param phoneNumber
* @return
*/
AjaxResult getVerificationCode(String phoneNumber);

3.6 service实现层

/**
* 获取验证码
* @param phoneNumber
* @return
*/
@Override
public AjaxResult getVerificationCode(String phoneNumber) {
    // 生成验证码
    String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    // 发送验证码
    boolean sendSms = sysSendSms.sendSms(phoneNumber, code);
    if (!sendSms) {
        return AjaxResult.error("验证码发送失败");
    }
    // 存入redis
    redisCache.setCacheObject(RedisConstants.SMS_PRE + phoneNumber, code, Constants.SMS_EXPIRATION, TimeUnit.MINUTES);
    return AjaxResult.success("短信发送成功");
}
这篇关于阿里云短信发送的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!