顺丰接口对接-订单创建与取消(java单元测试)

api文档

下单接口 :https://qiao.sf-express.com/Api/ApiDetails?level3=393&interName=%E4%B8%8B%E8%AE%A2%E5%8D%95%E6%8E%A5%E5%8F%A3-EXP_RECE_CREATE_ORDER

取消订单接口: https://qiao.sf-express.com/Api/ApiDetails?level3=339&interName=%E8%AE%A2%E5%8D%95%E7%A1%AE%E8%AE%A4%2F%E5%8F%96%E6%B6%88%E6%8E%A5%E5%8F%A3-EXP_RECE_UPDATE_ORDER

  • 每个接口需要测试成功三次才可上线
  • 下单接口上线需要上传电子面单,下线订单量不大时可以走免面单申请,不需要提交电子面单也可以上线接口

单元测试类

package com.cqdh.group.applet;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;

/**
 * @Description 顺丰API测试
 * @Date 2023/10/17 16:21
 * @Author 余乐
 **/
public class SFApiTest {

    /**
     * 客户编码
     */
    private static final String partnerID = "ZYHNYK*****";
    /**
     * 测试环境url
     */
    private static final String url = "https://sfapi-sbox.sf-express.com/std/service";
    /**
     * 校验码
     */
    private static final String checkWord = "pUVFxVbrao35vtzY***********";


    /**
     * 创建物流订单 ,修改订单orderId即可反复下单
     *
     * @throws UnsupportedEncodingException
     */
    @Test
    public void createLogisticsOrder() throws UnsupportedEncodingException {
        // 请求参数
        String serviceCode = "EXP_RECE_CREATE_ORDER";
        String requestID = UUID.randomUUID().toString();
        String timespase = System.currentTimeMillis() + "";
        String msgData = "{\"expressTypeId\":1,\"orderId\":\"SC1714182733078591144\",\"payMethod\":1,\"totalWeight\":1,\"monthlyCard\":\"7551234567\",\"signBackRemark\":\"test--签\",\"contactInfoList\":[{\"country\":\"CN\",\"contactType\":1,\"tel\":\"13866666666\",\"address\":\"重庆市渝北区两港大道与婵衣路交叉路口往东约140米\",\"contact\":\"小红\"},{\"country\":\"CN\",\"contactType\":2,\"tel\":\"13866666666\",\"address\":\"遵义市汇川区红河路莲花山公园西南侧约150米\",\"contact\":\"张三\"}],\"isDocall\":1}";

        String msgDigest = getMsgDigest(msgData, timespase, checkWord);
        // 构建请求头
        HttpRequest request = HttpRequest.post(url);
        request.header("Content-Type", "application/x-www-form-urlencoded");
        // 构建请求体
        String formData = String.format("serviceCode=%s&partnerID=%s&requestID=%s&timestamp=%s&msgDigest=%s&msgData=%s",
                serviceCode, partnerID, requestID, timespase, msgDigest, msgData);
        // 发送请求并获取响应
        HttpResponse response = request.body(formData).execute();

        // 解析响应内容
        String result = response.body();
        System.out.println("响应内容:" + result);
    }

    /**
     * 取消物流订单 ,必须取消成功三次才可上线,通过接口创建成功的订单才可取消
     *
     * @throws UnsupportedEncodingException
     */
    @Test
    public void cannelLogisticsOrder() throws UnsupportedEncodingException {
        // 请求参数
        String serviceCode = "EXP_RECE_UPDATE_ORDER";
        String requestID = UUID.randomUUID().toString();
        String timespase = System.currentTimeMillis() + "";
        String msgData = "{\"dealType\":2,\"language\":\"zh-CN\",\"orderId\":\"SC1714182733078597644\",\"totalWeight\":1,\"waybillNoInfoList\":[]}";

        String msgDigest = getMsgDigest(msgData, timespase, checkWord);
        // 构建请求头
        HttpRequest request = HttpRequest.post(url);
        request.header("Content-Type", "application/x-www-form-urlencoded");

        // 构建请求体
        String formData = String.format("serviceCode=%s&partnerID=%s&requestID=%s&timestamp=%s&msgDigest=%s&msgData=%s",
                serviceCode, partnerID, requestID, timespase, msgDigest, msgData);
        // 发送请求并获取响应
        HttpResponse response = request.body(formData).execute();

        // 解析响应内容
        String result = response.body();
        System.out.println("响应内容:" + result);
    }


    public static String getMsgDigest(String msgData, String timeStamp, String md5Key) throws UnsupportedEncodingException {
        return (new Base64()).encodeAsString(md5Encrypt(URLEncoder.encode(msgData + timeStamp + md5Key, "UTF-8")));
    }

    private static byte[] md5Encrypt(String encryptStr) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(encryptStr.getBytes("utf8"));
            return md5.digest();
        } catch (Exception var2) {
            throw new RuntimeException(var2);
        }
    }
}

下单响应报文

{
    "apiErrorMsg":"",
    "apiResponseID":"00018BB37AD8993FDF02951B4A6F363F",
    "apiResultCode":"A1000",
    "apiResultData":"{\"success\":true,\"errorCode\":\"S0000\",\"errorMsg\":null,\"msgData\":{\"orderId\":\"SC1714182733078591144\",\"originCode\":\"023\",\"destCode\":\"052\",\"filterResult\":2,\"remark\":\"\",\"url\":null,\"paymentLink\":null,\"isUpstairs\":null,\"isSpecialWarehouseService\":null,\"mappingMark\":null,\"agentMailno\":null,\"returnExtraInfoList\":null,\"waybillNoInfoList\":[{\"waybillType\":1,\"waybillNo\":\"SF7444473317974\",\"boxNo\":null,\"length\":null,\"width\":null,\"height\":null,\"weight\":null,\"volume\":null}],\"routeLabelInfo\":[{\"code\":\"1000\",\"routeLabelData\":{\"waybillNo\":\"SF7444473317974\",\"sourceTransferCode\":\"023W\",\"sourceCityCode\":\"023\",\"sourceDeptCode\":\"023\",\"sourceTeamCode\":\"\",\"destCityCode\":\"052\",\"destDeptCode\":\"052GC\",\"destDeptCodeMapping\":\"\",\"destTeamCode\":\"004\",\"destTeamCodeMapping\":\"\",\"destTransferCode\":\"052\",\"destRouteLabel\":\"052GC-004\",\"proName\":\"\",\"cargoTypeCode\":\"C201\",\"limitTypeCode\":\"T4\",\"expressTypeCode\":\"B1\",\"codingMapping\":\"C15\",\"codingMappingOut\":\"\",\"xbFlag\":\"0\",\"printFlag\":\"000000000\",\"twoDimensionCode\":\"MMM={'k1':'052','k2':'052GC','k3':'004','k4':'T4','k5':'SF7444473317974','k6':'','k7':'1d8ee46c'}\",\"proCode\":\"特快\",\"printIcon\":\"00000000\",\"abFlag\":\"\",\"destPortCode\":\"\",\"destCountry\":\"\",\"destPostCode\":\"\",\"goodsValueTotal\":\"\",\"currencySymbol\":\"\",\"cusBatch\":\"\",\"goodsNumber\":\"\",\"errMsg\":\"\",\"checkCode\":\"1d8ee46c\",\"proIcon\":\"\",\"fileIcon\":\"\",\"fbaIcon\":\"\",\"icsmIcon\":\"\",\"destGisDeptCode\":\"052GC\",\"newIcon\":null,\"sendAreaCode\":null,\"destinationStationCode\":null,\"sxLabelDestCode\":null,\"sxDestTransferCode\":null,\"sxCompany\":null,\"newAbFlag\":null,\"destAddrKeyWord\":\"\",\"rongType\":null,\"waybillIconList\":null},\"message\":\"SF7444473317974:\"}],\"contactInfoList\":null,\"sendStartTm\":null,\"customerRights\":null,\"expressTypeId\":null}}"
}

取消订单响应报文

{
    "apiErrorMsg":"",
    "apiResponseID":"00018BB37FFC733FEB93CB6399A4D03F",
    "apiResultCode":"A1000",
    "apiResultData":"{\"success\":true,\"errorCode\":\"S0000\",\"errorMsg\":null,\"msgData\":{\"orderId\":\"SC1714182733078591144\",\"waybillNoInfoList\":[{\"waybillType\":1,\"waybillNo\":\"SF7444473317974\"}],\"resStatus\":2,\"extraInfoList\":null}}"
}
Java中接入顺丰开放平台的下订单接口- 首先访问顺丰官网,如顺丰开放平台官网(https://open.sf-express.com),注册并创建开发者账号。 - 获取应用key和secret等认证信息。 2. **添加依赖**: - 如果使用的是顺丰提供的SDK,如顺丰Java SDK,需要在项目中添加相应的库到你的Maven或Gradle构建文件中。 ```xml <!-- Maven --> <dependency> <groupId>com.sf Express</groupId> <artifactId>sfExpressJavaSdk</artifactId> <version>最新版本号</version> </dependency> // Gradle implementation 'com.sf Express:sfExpressJavaSdk:最新版本号' ``` 3. **初始化客户端**: - 使用获取到的应用key和secret初始化顺丰客户端,设置请求URL和相关的认证信息。 ```java SfExpressClient sfClient = new SfExpressClient("你的AppKey", "你的AppSecret"); sfClient.setBaseUrl("https://api.sf-express.com/v4/..."); ``` 4. **调用接口**: - 使用`sfClient`实例调用`下单`或`下单速运`方法,传递所需的订单信息,例如寄件人、收件人地址、货物详情等。 ```java OrderRequest orderRequest = new OrderRequest(); orderRequest.setSender(...); orderRequest.setRecipient(...); orderRequest.setPackage(...); OrderResponse orderResponse = sfClient.placeOrder(orderRequest); ``` 5. **处理响应**: - 检查`orderResponse`以获取订单状态和可能存在的错误信息,成功则进一步操作,失败则处理异常。 ```java if (orderResponse.isSuccess()) { // 下单成功,处理订单ID或其他相关信息 } else { // 处理错误信息 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

占星安啦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值