阿里云短信验证接口调用

首先我们需要注册一个阿里云开源镜像站的账号,下面是网址

(阿里巴巴开源镜像站-OPSX镜像站-阿里云开发者社区 (aliyun.com))


然后我们去里面搜索短信服务,这里还需要注册一个访问阿里云的账号



 注册好了后如下图



 到这里我们需要手动添加权限,


 


需要注意的是,用于测试,我们需要充值一块钱(可以测试很多次了)的费用,接下来是后端代码的编写,

扫描二维码关注公众号,回复: 15341188 查看本文章


需要的maven依赖

<!-- 升级版 SDK这是一个短信 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.23</version>
</dependency>

 


package com.service.thereService;



import com.Common.constants.Constants;
import com.Common.exception.BaseException;
import com.Common.result.ResultEnum;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


/**
* @Author 陈厚德
* @Version 2.2
*/
@Service
public class AliYunService {

private static final Logger log = LoggerFactory.getLogger(AliYunService.class);
/**
* 阿里云发送短信
* @param phone 手机号
* @param code 需要发送的验证码
* @return
*/
public boolean sendSms(String phone ,String code){
//初始化client
Config config = new Config();
config.setAccessKeyId("你的密钥");
config.setAccessKeySecret("你的密钥");
//准备request请求体
config.endpoint="dysmsapi.aliyuncs.com";
try {
Client client= new Client(config);
SendSmsRequest sendSmsRequest= new SendSmsRequest();
sendSmsRequest.setPhoneNumbers(phone)
.setSignName("阿里云短信测试")
.setTemplateCode("SMS_154950909")
.setTemplateParam("{\"code\":"+code+"}");
//执行发送 --通过client发送
SendSmsResponse response= client.sendSms(sendSmsRequest);
log.info("短信响应体为{}", response.getBody().toString());
if (response.getBody().code.equals(Constants.Sms.ALI_SMS_RESULT)){
return true;
}
return false;
} catch (Exception e) {
log.error("短信发送失败:{}",e.getMessage());
throw new BaseException(ResultEnum.SMS_SENDING_ERROR);
}
}


}


我们只需要给手机号和随机生成(随机数就行)的验证码,就可以实现给手机发短信了,希望能帮到各位小伙伴

猜你喜欢

转载自blog.csdn.net/weixin_69218754/article/details/130905315
今日推荐