阿里云短信验证接口调用

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

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


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



 注册好了后如下图



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


 

 


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



需要的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);
}
}


}

 


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

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值