1. 程式人生 > 其它 >spring boot 2 : 開發快遞100訂閱運單資料(spring boot v2.5.4)

spring boot 2 : 開發快遞100訂閱運單資料(spring boot v2.5.4)

一,快遞100開發的相關文件

1,快遞公司編碼的表格 登入後訪問:
https://api.kuaidi100.com/manager/page/document/kdbm
2,快遞公司編碼的表格下載:
https://api.kuaidi100.com/manager/utils/download/kdbm.do
3,官方程式碼地址: github
https://github.com/kuaidi100-api

gitee

https://gitee.com/kuaidi100-api
4,開發平臺的地址:
https://api.kuaidi100.com/

說明:劉巨集締的架構森林是一個專注架構的部落格,地址:https://www.cnblogs.com/architectforest

對應的原始碼可以訪問這裡獲取:https://github.com/liuhongdi/
或:https://gitee.com/liuhongdi

說明:作者:劉巨集締 郵箱: [email protected]

二,獲得key和customer:

登入到後臺:我的資訊->企業資訊 右側有key和customer:

三,匯入java庫:

1,mvnrepository上的地址:
https://mvnrepository.com/artifact/com.github.kuaidi100-api/sdk
如圖: 2,匯入到maven:
<dependency>
            <
groupId>com.github.kuaidi100-api</groupId> <artifactId>sdk</artifactId> <version>1.0.5</version> </dependency>

四,配置資料庫:

建表:
CREATE TABLE `express` (
 `expressId` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
 `expressNum` varchar(100) NOT NULL
DEFAULT '' COMMENT '運單編號', `companyCode` varchar(100) NOT NULL DEFAULT '' COMMENT '快遞公司編碼', `state` tinyint NOT NULL DEFAULT '-1' COMMENT '-1初始狀態,0在途,1攬件,2疑難,3簽收,4退籤,5派件,6退回', `addTime` datetime NOT NULL DEFAULT '2022-01-21 00:00:00' COMMENT '新增時間', `subStatus` int NOT NULL DEFAULT '0' COMMENT '訂閱狀態,0,初始,200:成功', `subRequest` varchar(2000) NOT NULL DEFAULT '' COMMENT '請求引數', `subResult` varchar(2000) NOT NULL DEFAULT '' COMMENT '返回引數', PRIMARY KEY (`expressId`), UNIQUE KEY `expressNum` (`expressNum`) ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='運單表'
CREATE TABLE `express_data` (
 `dataId` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
 `expressId` bigint NOT NULL DEFAULT '0' COMMENT '運單id',
 `expressNum` varchar(100) NOT NULL DEFAULT '' COMMENT '運單',
 `dataTime` timestamp NOT NULL DEFAULT '2022-01-21 00:00:00' COMMENT '運單資料的時間',
 `context` varchar(500) NOT NULL DEFAULT '' COMMENT '運單說明文字',
 `addTime` datetime NOT NULL DEFAULT '2022-01-21 00:00:00' COMMENT '新增時間',
 PRIMARY KEY (`dataId`),
 UNIQUE KEY `expressId` (`expressId`,`dataTime`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='運單資料表’

五,配置日誌:

說明:從快遞100所post過來的資料,可以儲存到資料庫,也可以儲存到日誌檔案, 這裡我們選擇儲存到日誌檔案 log4j2.xml
        <!--kuaidi100的日誌記錄追加器-->
        <RollingFile name="kd100LogRollingFile" fileName="${LOG_HOME}/kd100.log"
                     filePattern="${LOG_HOME}/logs/$${date:yyyy-MM}/kd100-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="500 MB"/>
                <TimeBasedTriggeringPolicy/>
            </Policies>
        </RollingFile>

六,配置檔案:

  kuaidi100:
  key: KBAABBccDD11
  customer: C1FAABBccDDAABBccDD49F97B706F2E
  secret: 8e1AABBccDDAABBccDDAABBccDDce83
  userid: 744aabbccddeeffgghhiibbdda3ba
  #回撥地址(寫上真實的回撥地址)
  url: http://www.lhdtest.net/api/express/callback
  #開通行政區域解析功能以及物流軌跡增加物流狀態值
  resultv2: 1

七,java程式碼:

1,service/impl/ExpressServiceImpl.java
@Service
public class ExpressServiceImpl implements ExpressService {

    @Resource
    private ConfigBeanValue configBeanValue;

    @Resource
    private ExpressMapper expressMapper;

    @Resource
    private ExpressDataMapper expressDataMapper;

    private Logger loggerKd100 = LogManager.getLogger("kd100LogRollingFile");

    @Override
    public boolean subscribe(String code,String num) throws Exception {

        // 授權key
        String key = configBeanValue.kd100Key;
        String customer = configBeanValue.kd100Customer;
        // 介面回撥地址
        String callbackUrl = configBeanValue.kd100Url; //PropertiesReader.get("url");
        // 開啟行政區域解析
        String resultv2 = configBeanValue.kd100Resultv2; //PropertiesReader.get("resultv2");

        Express express = new Express();

        SubscribeParameters subscribeParameters = new SubscribeParameters();
        subscribeParameters.setCallbackurl(callbackUrl);
        subscribeParameters.setPhone("17725390266");
        subscribeParameters.setResultv2(resultv2);

        SubscribeParam subscribeParam = new SubscribeParam();
        subscribeParam.setParameters(subscribeParameters);
        subscribeParam.setCompany(code);
        subscribeParam.setNumber(num);
        subscribeParam.setKey(key);

        SubscribeReq subscribeReq = new SubscribeReq();
        subscribeReq.setSchema(ApiInfoConstant.SUBSCRIBE_SCHEMA);
        subscribeReq.setParam(new Gson().toJson(subscribeParam));

        IBaseClient subscribe = new Subscribe();

        // 訂閱推送服務
        HttpResult httpResult = subscribe.execute(subscribeReq);

        SubscribeResp response = new Gson().fromJson(httpResult.getBody(), SubscribeResp.class);

        String returnCode = response.getReturnCode();
        if("501".equals(returnCode)){
            // 重複訂閱的請求,不改變訂閱成功的狀態,只儲存報文(以防誤操作)
            express.setSubStatus(200);
        }else{
            express.setSubStatus(Integer.valueOf(returnCode));
        }
        express.setSubRequest(subscribeReq.getParam());
        express.setSubResult(httpResult.getBody());

        //得到express的相應欄位
        express.setExpressNum(num);
        express.setCompanyCode(code);
        express.setState(-1);
        //express.set

        //新增到資料庫
        int expressId = expressMapper.insertOneExpress(express);
        //返回:
        return true;
    }

   @Override
   public SubscribeResp handleCallBack(HttpServletRequest request) {
       // 獲取引數
       String param = request.getParameter("param");
       String sign = request.getParameter("sign");

       //寫日誌:
       //loggerKd100
       loggerKd100.info("param:");
       loggerKd100.info(param);

       loggerKd100.info("sign:");
       loggerKd100.info(sign);

       //處理資料,add database
       SubscribePushParamResp backResp = new Gson().fromJson(param, SubscribePushParamResp.class);
       String expressNum = backResp.getLastResult().getNu();

       Express express = expressMapper.selectOneExpressByExpressNum(expressNum);
       Long expressId = express.getExpressId();

       //查詢資料庫,

       List<SubscribePushData> dataList = backResp.getLastResult().getData();
       List<ExpressData> infoList = new ArrayList<>();
       for (SubscribePushData data : dataList) {
           ExpressData info = new ExpressData();
           info.setDataTime(data.getFtime());
           info.setExpressId(expressId);
           info.setExpressNum(expressNum);
           info.setContext(data.getContext());
           infoList.add(info);
       }
       if(infoList.size() > 0){
           // 入庫操作前,先刪除sys_express_info表中的資料,只保留最新資料。
           //expressInfoMapper.deleteSysExpressInfoByNum(expressNum);

           expressDataMapper.deleteExpressDataByExpressId(expressId);

           for (ExpressData data : infoList) {
               expressDataMapper.insertOneExpressData(data);
           }
           //expressInfoMapper.insertSysExpressBatch(infoList);
       }

       //更新狀態
       int state = Integer.parseInt(backResp.getLastResult().getState());
       expressMapper.updateOneExpressState(expressId,state);

       //返回:
       SubscribeResp response = new SubscribeResp();
       response.setResult(Boolean.TRUE);
       response.setReturnCode("200");
       response.setMessage("成功");
       return response;
   }
}
2,controller/ExpressController.java
@RestController
@RequestMapping("/express")
public class ExpressController {
 
    @Resource
    private ExpressService expressService;
 
    //session詳情
    @GetMapping("/subscribe")
    @ResponseBody
    public Result subscribe(@NotBlank(message="快遞公司編號")@RequestParam("code") String code,
                            @NotBlank(message="運單編號")@RequestParam("num") String num) throws Exception{
 
        Map<String, Object> data = new HashMap<String, Object>();
        boolean isIns = expressService.subscribe(code, num);
        return Result.success(data);
    }
 
    /**
     * 快遞100回撥介面
     * @param request
     */
    @PostMapping("/callback")
    public SubscribeResp callBack(HttpServletRequest request) throws Exception {
        return expressService.handleCallBack(request);
    }
}
3,ExpressMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yj.storeback.mapper.ExpressMapper">
    <insert id="insertOneExpress" parameterType="com.yj.storeback.pojo.Express" useGeneratedKeys="true" keyProperty="expressId" >
        insert into express(expressNum,companyCode,state,addTime,subStatus,subRequest,subResult)
        values(
                  #{expressNum},#{companyCode},#{state},now(),#{subStatus},#{subRequest},#{subResult}
              )
    </insert>
 
    <select id="selectOneExpressByExpressNum" resultType="com.yj.storeback.pojo.Express">
        select * from express where expressNum=#{expressNum}
    </select>
    <update id="updateOneExpressState">
        UPDATE express SET
                           state = #{state}
        WHERE expressId=#{expressId}
    </update>
</mapper>
4,ExpressDataMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yj.storeback.mapper.ExpressDataMapper">
    <insert id="insertOneExpressData" parameterType="com.yj.storeback.pojo.ExpressData" useGeneratedKeys="true" keyProperty="dataId" >
        insert into express_data(expressId,expressNum,dataTime,addTime,context)
        values(
                  #{expressId},#{expressNum},#{dataTime},now(),#{context}
              )
    </insert>
 
    <delete id="deleteExpressDataByExpressId" >
        delete from express_data where expressId = #{expressId}
    </delete>
</mapper>
5,ExpressService.java
public interface ExpressService {
    public boolean subscribe(String code,String num) throws Exception;
    public SubscribeResp handleCallBack(HttpServletRequest request);
}
6,ExpressMapper.java
@Repository
@Mapper
public interface ExpressMapper {
    int insertOneExpress(Express express);
    Express selectOneExpressByExpressNum(@Param("expressNum")String expressNum);
    int updateOneExpressState(@Param("expressId")Long expressId, @Param("state")int state);
 
}
7,ExpressDataMapper.java
@Repository
@Mapper
public interface ExpressDataMapper {
    int insertOneExpressData(ExpressData expressData);
    int deleteExpressDataByExpressId(@Param("expressId")Long expressId);
}

八,測試效果:

1訂閱 訪問:
http://www.lhdtest.net/api/express/subscribe?code=shunfeng&num=SF1322339353060
返回: 2,接收推送: 檢視日誌:
[lhdpc@blog logs]$ tail -100 /data/logs/nginxlogs/store.access_log 
日誌如下:
...
120.92.182.60 - - [29/Jan/2022:16:55:17 +0800] "POST /api/express/callback HTTP/1.1" 200 0 "-" "HttpComponents/1.1"
...

九,檢視springboot的版本:

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::                (v2.5.4)