Pthon of Express Bird API Single Number Query Interface Function

Keywords: Python encoding JSON PHP

Before writing express delivery, there were only examples of php and. net on the official website, and I used the relevant functions of python package to trample a lot of holes before I came out and shared my method.
Firstly, the picture above shows the results.

For technical documents, please refer to Express Bird's official website api: Free Query Express Interface 100% Safety Guarantee Logistics Instant Query API - Express Bird

Express company code link: https://www.kdniao.com/file/2019 Express Bird Interface Supports Express Company Coding. xlsx

(1) Access process:

1 > Register Express Bird Account.

API_ID: test1234567
API_KEY: XXXXXXXXXXXXXXXXXX

2>. Application for Services

Apply for the required services in the personal center. The instant inquiry function is free of charge.

3>. Docking Service

*** Write your own business logic *** - The main body of this article

4>. Test code
5>. Official use
1. Register Express Bird Account on the Registration Page of Express Bird Official Website

Website: Express Bill Inquiry Interface Electronic Form APIKey Authorization Application Express Bird Account Registration

2. Login Express Bird User Management Background

Website: User login Express Bird API makes logistics interface docking easier

Note: User ID and API Key are obtained after login express bird user management background. This is used to ensure the reliability of application source, avoid application forgery and be used illegally.

3. Enter "My Membership Center" for Name Certification

Note:

3.1. Authentication type and application type can be selected according to the user's actual situation. The data returned by the interface has nothing to do with the result of selection.

3.2. The document marked * is required to upload clear, jpg format and less than 2M document pictures.

3.3. The information of technology docking is the information of user docking engineer.

3.4. If you have any other questions, you can join the business cooperation group on the official website for consultation.

After successful certification, enter "product service management" and open related member services.

Note:

Logistics enquiry (free edition) Membership Package is free edition. After one year of validity, data interaction system will automatically renew for free in the past three months.

(2) Interface description/description

(1) The query interface supports querying by shipping order number (single query).

(2) The interface needs to specify the express company code of the express delivery number. If the format is wrong or the coding error will return the failure information.

For example, EMS Logistics Number should select Express Company Code (EMS) to view Express Company Code

(3) The returned logistics tracking information is arranged in ascending order according to the time of occurrence.

(4) Interface instruction 1002.

(5) The message receiving mode supported by the interface is HTTP POST, and the encoding format of the request method (utf-8): "application/x-www-form-urlencoded;charset=utf-8".

(6) Test address: http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json

(7) Official address: http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx

(3) Explanation of the required parameters:

Request content:

OrderCode: Order Number - Not Necessary

ShipperCode: Express Company Code - Must

Logistic Code: Logistics Number - Must

system parameter

RequestData: Encoding the request content in JSON format with a URL(utf-8);

EBusinessID: API_ID;

RequestType: 1002;

DataSign: Request content (uncoded) +AppKey is encrypted in MD5, then Base64 is encoded, and finally URL(utf-8) is encoded.

(4) Functional encapsulation

Request Data Processing

def organize_request_data(shipper_code, logistic_code):

"""Encoding Request Data"""
original_request_data = {
    "OrderCode": "",  # The default setting is null
    "ShipperCode": shipper_code,
    "LogisticCode": logistic_code,
    "IsHandleInfo": "0"
}
# Data conversion to json format
data = json.dumps(original_request_data)

# url encoding
# There is a pit here. If you are interested, you can try it.
#  Requ_data = quote (data), which is different
request_data = quote(data).replace("%20%", "%")

return request_data

def generate_data_sign(shipper_code, logistic_code):

"""generate datasign"""
original_request_data = {
    'OrderCode': '',
    'ShipperCode': shipper_code,
    'LogisticCode': logistic_code,
    "IsHandleInfo": "0"
}
# APP_KEY = API_KEY_PRO
APP_KEY = API_KEY_PRO

# Request content (uncoded) + AppKey
# Here's another pit. For MD5 encryption, there are no spaces in the dictionary. The results are different. For this interface, the spaces need to be removed.
data = json.dumps(original_request_data).replace(": ", ":").replace(", ", ",") + APP_KEY

# md5 encryption
sign_md5 = hashlib.md5(data.encode("utf-8")).hexdigest()

# base 64 encoding
data_sign = base64.b64encode(sign_md5.encode("utf-8")).decode("utf-8")

return data_sign

/ Spacing effect of MD5/

(5) View logic:

class CompanyView(LoginRequiredView):

"""Code Display of Express Company"""
def get(self, request):
    company_qs = KDCompany.objects.all()
    company_list = []
    for company in company_qs:
        company_list.append({
            "name": company.name,
            "code": company.code
        })
    return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'company_list': company_list})

class KD(LoginRequiredView):

"""Exhibition of Express Details"""
def post(self, request):
    shipper_codes = request.POST.get('shipper_code')
    # Because of the XX of the front-end code, the acquired data needs to be processed here to obtain the required code.
    shipper_code=shipper_codes.split(" ")[0]
    logistic_code = request.POST.get('logistic_code')
    request_data = organize_request_data(shipper_code, logistic_code)
    data_sign = generate_data_sign(shipper_code, logistic_code)
    API_ID = API_ID_PRO
    API_URL = API_URL_PRO
    data = {
        "RequestData": request_data,
        "DataSign": data_sign,
        "RequestType": "1002",
        "EBusinessID": API_ID,
        "ShipperCode": shipper_code,
        "LogisticCode": logistic_code,
        "DataType":"2"
    }
    # Setting Request Header Information as Required
    headers = {'content-type': 'application/x-www-form-urlencoded','content-Encoding': 'charset=utf-8'}
    kd_response = requests.post(url=API_URL, data=data,headers=headers)
    kd_response.encoding="utf-8"
    trace_resp=json.loads(kd_response.content).get("Traces")
    trace_black = ""
    traces = trace_black if type(trace_resp) == "NoneType" else trace_resp
    context = {
        "ShipperCode": shipper_code,
        "LogisticCode": logistic_code,
        "kd_response":traces
    }
    return render(request, 'kd_trace.html', context)

In addition, python has a third-party package for express birds, but there are some areas that need to be modified, and look a little dizzy, so I wrote a use for myself, feeling more clear. If there is anything wrong, please correct it.

Posted by ixalmida on Mon, 16 Sep 2019 23:33:05 -0700