spring boot集成阿里云短信发送接收短信回复功能

1.集成阿里云通信发送短信:

在pom.xml文件里添加依赖

 



   com.aliyun
   aliyun-java-sdk-core
   3.7.1


   com.aliyun
   aliyun-java-sdk-dysmsapi
   1.1.0

直接复制发送短信demo测试:

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.dysmsapi.transform.v20170525.SendSmsResponseUnmarshaller;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created on 17/6/7.
 * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过
 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可)
 * 工程依赖了2个jar包(存放在工程的libs目录下)
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 *
 * 备注:Demo工程编码采用UTF-8
 * 国际短信发送请勿参照此DEMO
 */
public class SmsDemo {

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "yourAccessKeyId";
    static final String accessKeySecret = "yourAccessKeySecret";

    public static SendSmsResponse sendSms() throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers("15000000000");
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("云通信");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_1000000");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)如果需要查看短信回复。这个得填上
         request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");

        //hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }


    public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber("15000000000");
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询,格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常,注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    public static void main(String[] args) throws ClientException, InterruptedException {

        //发短信
        SendSmsResponse response = sendSms();
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

        Thread.sleep(3000L);

        //查明细
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        }

    }
}

填上自己的数据

 

run(运行)这个类可以测试

2.消息接口:

下载官方消息demo:项目名:alicom-mns-receive-samples

复制项目的lib包到自己项目目录下:

spring boot集成阿里云短信发送接收短信回复功能_第1张图片

直接拷贝lib包到自己项目目录下,和src同级,然后右键点击lib再点击Add as libbarary:

spring boot集成阿里云短信发送接收短信回复功能_第2张图片

复制消息接收demo中的类到自己项目中:

spring boot集成阿里云短信发送接收短信回复功能_第3张图片

我的Gson报错,删掉lib包中依赖的gson的jar,然后在pom.xml中:


   com.google.code.gson
   gson

并且在pom.xml移除默认的jackson依赖:


   org.springframework.boot
   spring-boot-starter-web
   
   
      
         com.fasterxml.jackson.core
         jackson-databind
      
   

运行这个类:测试:

1.先发送短信

2.回复短信

3.可以在控制台打印相关信息了

我把接收短信的类测试短信上行接收:

String messageType="SmsUp";//短信回执:SmsReport,短信上行:SmsUp 

spring boot集成阿里云短信发送接收短信回复功能_第4张图片

spring boot集成阿里云短信发送接收短信回复功能_第5张图片

短信回复内容:

spring boot集成阿里云短信发送接收短信回复功能_第6张图片

控制台打印:

spring boot集成阿里云短信发送接收短信回复功能_第7张图片

更正:无反应的话:

spring boot集成阿里云短信发送接收短信回复功能_第8张图片

如果想实现获取发送出去的短信的回复内容(不管啥时候回复短信(阿里云限制好像30天之内),启动类中会自动获取回复的内容):我是在启动类中实现:

package com.shengquan.registeradmin;

import com.alicom.mns.tools.DefaultAlicomMessagePuller;
import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.aliyuncs.exceptions.ClientException;
import com.google.gson.Gson;
import com.shengquan.registeradmin.service.DuanXinService;
import com.shengquan.registeradmin.util.ReceiveDemo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Configuration
//@EnableScheduling//定时任务
@EnableAsync
@SpringBootApplication
public class RegisteradminApplication extends SpringBootServletInitializer implements WebApplicationInitializer {


   private static DuanXinService duanXinService;

   @Autowired
   public void setDatastore(DuanXinService duanXinService) {
      RegisteradminApplication.duanXinService = duanXinService;
   }

   private static Log logger= LogFactory.getLog(ReceiveDemo.class);

 public static void main(String[] args) throws Exception, ParseException { 
           System.out.print("======项目====启动类2."+"\n");                                       SpringApplication.run(RegisteradminApplication.class, args); 
}

   //该方法的作用是可以把项目打包成war包
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application){

      System.out.print("=========项目=启动类1."+"\n");

      //处理消息回复
      DefaultAlicomMessagePuller puller=new DefaultAlicomMessagePuller();

      //设置异步线程池大小及任务队列的大小,还有无数据线程休眠时间
      puller.setConsumeMinThreadSize(6);
      puller.setConsumeMaxThreadSize(16);
      puller.setThreadQueueSize(200);
      puller.setPullMsgThreadSize(1);
      //和服务端联调问题时开启,平时无需开启,消耗性能
      puller.openDebugLog(false);

      //TODO 此处需要替换成开发者自己的AK信息
      String accessKeyId="   ";
      String accessKeySecret="  ";

      /*
       * TODO 将messageType和queueName替换成您需要的消息类型名称和对应的队列名称
       *云通信产品下所有的回执消息类型:
       *1:短信回执:SmsReport,
       *2:短息上行:SmsUp
       *3:语音呼叫:VoiceReport
       *4:流量直冲:FlowReport
       */
      String messageType="SmsUp";//此处应该替换成相应产品的消息类型messageType
      String queueName="  ";//在云通信页面开通相应业务消息后,就能在页面上获得对应的queueName,格式类似Alicom-Queue-xxxxxx-SmsReport
      try {
         puller.startReceiveMsg(accessKeyId,accessKeySecret, messageType, queueName, new MyMessageListener());
      } catch (ClientException e) {

      } catch (ParseException e) {
         e.printStackTrace();
      }
      return application.sources(RegisteradminApplication.class);
   }



 class MyMessageListener implements MessageListener {

   private Gson gson=new Gson();

   @Override
   public boolean dealMessage(Message message) {

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      //消息的几个关键值
//    System.out.println("message receiver time from mns:" + format.format(new Date()));
//    //System.out.println("message handle: " + message.getReceiptHandle());
//    System.out.println("message body: " + message.getMessageBodyAsString());
//    //System.out.println("message id: " + message.getMessageId());
//    System.out.println("message dequeue count:" + message.getDequeueCount());
//    System.out.println("Thread:" + Thread.currentThread().getName());
      try{
         Map contentMap=gson.fromJson(message.getMessageBodyAsString(), HashMap.class);
         //TODO 根据文档中具体的消息格式进行消息体的解析
         //String arg = (String) contentMap.get("arg");
         //TODO 这里开始编写您的业务代码
         String phoneNumber=(String)contentMap.get("phone_number");
         System.out.print("=======短信回复消息==手机号==========="+phoneNumber+"\n");

         String content=(String)contentMap.get("content");
         // System.out.print("=========短信内容==========="+content+"\n");

         String sign_name=(String)contentMap.get("sign_name");
         //System.out.print("=========短信签名==========="+sign_name+"\n");

         String dest_code=(String)contentMap.get("dest_code");
         //System.out.print("=========扩展码==========="+dest_code+"\n");

         Double sequence_id= (Double) contentMap.get("sequence_id");
         //System.out.print("=========消息序列ID==========="+sequence_id+"\n");
         if (content!=null&&phoneNumber!=null){
            //根据手机号把短信回复内容插入到表里
            int jieguo= duanXinService.insertHuifuByPhone(content,phoneNumber);
            System.out.print("短信短信回复内容插入结果=="+jieguo+"\n");
         }

      }catch(com.google.gson.JsonSyntaxException e){
         logger.error("短信回复内容插入失败(RegisteradminApplication之MyMessageListener):error_json_format:"+message.getMessageBodyAsString(),e);
         //理论上不会出现格式错误的情况,所以遇见格式错误的消息,只能先delete,否则重新推送也会一直报错
         return true;
      } catch (Throwable e) {
         //您自己的代码部分导致的异常,应该return false,这样消息不会被delete掉,而会根据策略进行重推
         return false;
      }

      //消息处理成功,返回true, SDK将调用MNS的delete方法将消息从队列中删除掉
      return true;
   }

}

}

你可能感兴趣的:(spring,boot)