阿里短信api接入

我将官方短信api写成了工具类方便页面调用

引入依赖

pom.xml

  1. <!--阿里短信sdk-->
  2. <dependency>
  3. <groupId>com.aliyun</groupId>
  4. <artifactId>aliyun-java-sdk-core</artifactId>
  5. <version>4.5.3</version>
  6. </dependency>

发送短信验证码util类

SendSmsUtil.java

  1. import com.aliyuncs.CommonRequest;
  2. import com.aliyuncs.CommonResponse;
  3. import com.aliyuncs.DefaultAcsClient;
  4. import com.aliyuncs.IAcsClient;
  5. import com.aliyuncs.exceptions.ClientException;
  6. import com.aliyuncs.exceptions.ServerException;
  7. import com.aliyuncs.http.MethodType;
  8. import com.aliyuncs.profile.DefaultProfile;
  9. /**
  10. * 发送短信验证码util类
  11. */
  12. public class SendSmsUtil {
  13. public static String code;//验证码
  14. public static String getSendSms(String userPhone){
  15. DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "accessKeyId", "secret");//accessKey签名
  16. IAcsClient client = new DefaultAcsClient(profile);
  17. CommonRequest request = new CommonRequest();
  18. request.setSysMethod(MethodType.POST);
  19. request.setSysDomain("dysmsapi.aliyuncs.com");
  20. request.setSysVersion("2017-05-25");
  21. request.setSysAction("SendSms");
  22. request.putQueryParameter("RegionId", "cn-hangzhou");
  23. request.putQueryParameter("PhoneNumbers", userPhone);//手机号 这里通过用户传输
  24. request.putQueryParameter("SignName", "短信签名");//短信签名
  25. request.putQueryParameter("TemplateCode", "短信模板code");//短信模板code
  26. request.putQueryParameter("TemplateParam", code=getSmsVerificationCode());//将生成的验证码发送给用户
  27. try {
  28. CommonResponse response = client.getCommonResponse(request);
  29. System.out.println(response.getData());//日志打印
  30. } catch (
  31. ServerException e) {
  32. e.printStackTrace();
  33. } catch (
  34. ClientException e) {
  35. e.printStackTrace();
  36. }
  37. return code;
  38. }
  39. //生成四位随机短信验证码
  40. private static String getSmsVerificationCode(){
  41. //发送的验证码必须是字符串 需要拼接
  42. String coRed = "{\"code\":\"";
  43. String oneNum = String.valueOf(Math.round(Math.random()*9));
  44. String twoNum = String.valueOf(Math.round(Math.random()*9));
  45. String threeNum = String.valueOf(Math.round(Math.random()*9));
  46. String fourNum = String.valueOf(Math.round(Math.random()*9));
  47. String coEnd = "\"}";
  48. code = coRed + oneNum + twoNum + threeNum + fourNum + coEnd;//验证码拼接
  49. return code;
  50. }
  51. }

以上是短信api的工具类内容,只需要在相应的地方调用即可,将签名内容这些填写成自己的就可以使用了,手机号是通过调用工具类是时候传入手机号。

接入步骤

①前往阿里云官网 —> 找到 ‘短信服务’ 进入产品控制台
具体短信申请流程请看我写的原文链接地址