测试使用阿里云短信服务,在项目中集成

阿里云实名认证分为个人实名认证和企业实名认证,短信服务产品属于后付费产品,即发送短信成功才会开始计费。

不同短信模板的单价不同,产生费用后,进行累计计费,每5分钟出账一次,每个月月底进行扣费。≤10万时,0.045元/条,冲个几块钱,个人做小项目练手的话是够用的。

阿里云短信官网:https://helpcdn.aliyun.com/product/44282.html

使用场景:作为个人用户,主要是用来做短信验证码,如登录注册找回密码等功能。

使用流程:

进入快速入门页面,https://help.aliyun.com/document_detail/55288.html?spm=a2c4g.11186623.6.557.6b6abc45UPyJ3A,按照教程完成个人认证,开通短信服务,申请短信签名和模板(审核得几个小时),给账户冲点钱,发送短信。

进入OpenAPI Explorer,根据提示,填写你的参数,会给一个能运行的小例子,发起调用就能收到短信了。

在项目中集成

首先添加依赖:

1         <dependency>
2             <groupId>com.aliyun</groupId>
3             <artifactId>aliyun-java-sdk-core</artifactId>
4             <version>4.0.3</version>
5         </dependency>
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>
*/
public class SendSms {
    public static void main(String[] args) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", "132xxxxxxxx");
        request.putQueryParameter("SignName", "xxx");
        request.putQueryParameter("TemplateCode", "SMS_xxxxxx");
        request.putQueryParameter("TemplateParam", "{"code":"xxxx"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

如果和我一样是用于找回密码功能,使用流程如下

1:后台Service层随机生成几位验证码

2:根据传入的手机号,使用官方给的API,设为自己的参数,将验证码发送出去

3:获取用户的输入验证码,和后台验证码进行对比

4:如果一致,则可以修改密码

原文地址:https://www.cnblogs.com/flyuz/p/11041017.html