阿里短信api接入
我将官方短信api写成了工具类方便页面调用
引入依赖
pom.xml
<!--阿里短信sdk--><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.5.3</version></dependency>
发送短信验证码util类
SendSmsUtil.java
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;/*** 发送短信验证码util类*/public class SendSmsUtil {public static String code;//验证码public static String getSendSms(String userPhone){DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "accessKeyId", "secret");//accessKey签名IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();request.setSysMethod(MethodType.POST);request.setSysDomain("dysmsapi.aliyuncs.com");request.setSysVersion("2017-05-25");request.setSysAction("SendSms");request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers", userPhone);//手机号 这里通过用户传输request.putQueryParameter("SignName", "短信签名");//短信签名request.putQueryParameter("TemplateCode", "短信模板code");//短信模板coderequest.putQueryParameter("TemplateParam", code=getSmsVerificationCode());//将生成的验证码发送给用户try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());//日志打印} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}return code;}//生成四位随机短信验证码private static String getSmsVerificationCode(){//发送的验证码必须是字符串 需要拼接String coRed = "{\"code\":\"";String oneNum = String.valueOf(Math.round(Math.random()*9));String twoNum = String.valueOf(Math.round(Math.random()*9));String threeNum = String.valueOf(Math.round(Math.random()*9));String fourNum = String.valueOf(Math.round(Math.random()*9));String coEnd = "\"}";code = coRed + oneNum + twoNum + threeNum + fourNum + coEnd;//验证码拼接return code;}}
以上是短信api的工具类内容,只需要在相应的地方调用即可,将签名内容这些填写成自己的就可以使用了,手机号是通过调用工具类是时候传入手机号。
接入步骤
①前往阿里云官网 —> 找到 ‘短信服务’ 进入产品控制台
具体短信申请流程请看我写的原文链接地址
