ソースを参照

添加PythonDemo

gmw 5 年 前
コミット
d029d31e55

+ 9 - 2
JavaDemo/src.main/java/demo/TmsApiDemo.java

@@ -4,6 +4,9 @@ import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import util.HttpClientHelper;
 
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
 /**
  * TMS接口调用实例,以 "获取登陆凭证接口"、 "创建订单接口"、 "批量查询订单接口" 为例
  * 其余接口调用方式相同;
@@ -18,6 +21,8 @@ public class TmsApiDemo {
 
     private static final String PASSWORD = "123456";
 
+    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+
     public static void main(String[] args) {
         System.out.println("*********************获取登陆凭证接口*********************");
         JSONObject tokenParams = new JSONObject();
@@ -33,6 +38,7 @@ public class TmsApiDemo {
         System.out.println("ACCESS_TOKEN = " + accessToken);
         System.out.println("REFRESH_TOKEN = " + refreshToken);
         System.out.println();
+
         System.out.println("*********************创建订单接口*********************");
         JSONObject createOrderParams = new JSONObject();
         JSONArray orders = new JSONArray();
@@ -67,6 +73,7 @@ public class TmsApiDemo {
         JSONArray orderNumberList = createOrderResponse.getJSONArray("data");
         System.out.println("TMS生成的单号:" + orderNumberList);
         System.out.println();
+
         System.out.println("*********************批量查询订单接口*********************");
         JSONObject queryOrderParams = new JSONObject();
         //页码,1开始
@@ -77,8 +84,8 @@ public class TmsApiDemo {
         queryOrderParams.put("state", 1000);
         //查询时间类型,created录入时间,deliveryed提货时间,appointArrived预约提货时间,signed签收时间
         queryOrderParams.put("timeType", "created");
-        queryOrderParams.put("startDate", "2019-12-15 00:00:00");
-        queryOrderParams.put("endDate", "2019-12-18 16:00:00");
+        queryOrderParams.put("startDate", dateFormat.format(new Date(System.currentTimeMillis() - 24 * 3600 * 1000)));
+        queryOrderParams.put("endDate", dateFormat.format(new Date()));
         result = HttpClientHelper.httpPost(URL + "/order/query_orders?access_token=" + accessToken, queryOrderParams);
         JSONObject queryOrderResponse = JSONObject.parseObject(result);
         JSONObject queryOrders = queryOrderResponse.getJSONObject("data");

+ 0 - 0
Python3Demo/__init__.py


+ 55 - 0
Python3Demo/ctms_api.py

@@ -0,0 +1,55 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+import ujson
+import requests
+
+
+class CtmsApi(object):
+    def __init__(self, user, password, url):
+        self.user = user
+        self.password = password
+        self.url = url
+
+    def __call__(self, path, params=None, body=None):
+        token = self.generate_token()
+        print('获取Token:', token)
+        if not params:
+            params = {'access_token': token}
+        else:
+            params['access_token'] = token
+        resp = requests.post('%s%s' % (self.url, path), params=params, json=body, timeout=30)
+        if resp.status_code == 200:
+            result = resp.text
+            if result:
+                return ujson.loads(result)
+        elif resp.status_code == 401:
+            print('ctms token invalidate')
+            return {'code': resp.status_code, 'message': '401 Forbidden'}
+        else:
+            print('ctms error with unknown code: %d' % resp.status_code)
+            return {'code': resp.status_code, 'message': None}
+
+    def generate_token(self):
+        """
+        生成token,token一般只需生成一次即可,有效期一年,
+        之后每次获取到的token值均相同,除非使用刷新token接口,
+        此处为方便,每次调用接口时都获取token,实际不建议这么做,
+        如果对安全性要求比较高,可以每隔几小时刷新一次token,
+        否则获取一次以后设置为常量即可
+        """
+        body = {
+            'userName': self.user,
+            'password': self.password
+        }
+        response = requests.post(url=self.url + '/user/generate_access_token/v2', json=body, timeout=30)
+        if response.status_code != 200:
+            return ''
+        result = response.text
+        if not result:
+            return ''
+        json_result = ujson.loads(result)
+        data = json_result.get('data')
+        if not data:
+            return ''
+        return data.get('accessToken')

+ 64 - 0
Python3Demo/demo.py

@@ -0,0 +1,64 @@
+"""
+TMS接口python demo,以下代码在python=3.7测试通过,接口调用封装在ctms_api.py中
+调用接口的参数并非全部参数,完整参数请查看TMS接口文档
+此demo只做调用演示用,较为简陋,对接时请根据实际业务需要完善相关逻辑
+"""
+from Python3Demo.ctms_api import CtmsApi
+import time
+
+# token的获取在CtmsApi中完成,请求地址使用的测试环境的地址,此处注意url结尾不要带/
+api = CtmsApi(user='19012345678', password='123456', url='http://api.test.56ctms.com')
+
+
+def stamp2date(stamp):
+    """
+    时间戳转日期
+    :param stamp: 时间戳
+    :return: 日期,格式:%Y-%m-%d %H:%M:%S
+    """
+    if not stamp:
+        return None
+    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stamp))
+
+
+print('******************创建订单接口******************')
+create_order_params = {
+    'orderList': [{
+        # 用于唯一性检测,此字段不在系统中展示:必填
+        "orderNumber": "KHY_TEST_654321",
+        # 发货人地址:必填
+        "consignerAddress": "浙江省杭州市西湖区计量大厦",
+        # 发货人姓名:必填
+        "consignerName": "快货运测试",
+        # 发货人电话:必填
+        "consignerPhone": "19012345678",
+        # 提货时间:时间戳,精确到秒:必填
+        "deliveryTime": int(time.time()),
+        # 提送类型:选填, 1)自提,2)送货
+        "deliveryType": 1,
+        # 客户单号:选填
+        "customerOrderNumber": "KHY_TEST_654321",
+        # 预约送到时间:时间戳,精确到秒:选填
+        "appointArriveTime": int(time.time()),
+        # 收货人地址:可不填
+        "consigneeAddress": "xxx",
+        # 收货人姓名:可不填
+        "consigneeName": "xxx",
+        # 收货人电话:可不填
+        "consigneePhone": "19012345679",
+    }]
+}
+result = api(path='/order/create_order', body=create_order_params)
+print(result)
+
+print('******************批量查询订单接口******************')
+query_order_params = {
+    'page': 1,
+    'size': 2,
+    'state': 1000,
+    'timeType': 'created',
+    'startDate': stamp2date(time.time() - 24 * 3600),
+    'endDate': stamp2date(time.time()),
+}
+result = api(path='/order/query_orders', body=query_order_params)
+print(result)

+ 1 - 15
pom.xml

@@ -63,6 +63,7 @@
 
     <build>
         <finalName>demo</finalName>
+        <sourceDirectory>JavaDemo/src.main/java</sourceDirectory>
         <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
@@ -75,21 +76,6 @@
             </plugin>
 
             <plugin>
-                <groupId>org.eclipse.jetty</groupId>
-                <artifactId>jetty-maven-plugin</artifactId>
-                <version>9.3.2.v20150730</version>
-                <configuration>
-                    <httpConnector>
-                        <port>9090</port>
-                    </httpConnector>
-                    <webApp>
-                        <contextPath>/</contextPath>
-                        <descriptor>webapp/WEB-INF/web.xml</descriptor>
-                    </webApp>
-                </configuration>
-            </plugin>
-
-            <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.2</version>