需要帮助将 Python 脚本转换为 PHP

Need help converting a Python script to PHP

我已经编写了一个 PHP 脚本来跟踪来自不同托运人的包裹,但无法为 FedEx 编写一个有效的脚本。然后我在下面找到了 python 脚本。它工作得很好,但我想为我的所有代码标准化 PHP 。过去几周我一直在尝试转换它,但是 json 数据的中间部分让我感到难过。

有人愿意提供一些关于如何将该部分转换为 PHP 的指示吗?

#!/usr/local/bin/python3

import requests, json, subprocess, datetime, sys, os.path

################
## Grab the argument(s) passed by the calling script.
################
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('tracking_number')
args = parser.parse_args()
tracking_number = args.tracking_number
################

data = requests.post('https://www.fedex.com/trackingCal/track', data={
    'data': json.dumps({
        'TrackPackagesRequest': {
            'appType': 'wtrk',
            'uniqueKey': '',
            'processingParameters': {
                'anonymousTransaction': True,
                'clientId': 'WTRK',
                'returnDetailedErrors': True,
                'returnLocalizedDateTime': False
            },
            'trackingInfoList': [{
                'trackNumberInfo': {
                    'trackingNumber': tracking_number,
                    'trackingQualifier': '',
                    'trackingCarrier': ''
                }
            }]
        }
    }),
    'action': 'trackpackages',
    'locale': 'en_US',
    'format': 'json',
    'version': 99
}).json()

fedex_status  = data['TrackPackagesResponse']['packageList'][0]['keyStatus']
fedex_details = data['TrackPackagesResponse']['packageList'][0]['statusWithDetails']
delivery_date = data['TrackPackagesResponse']['packageList'][0]['displayActDeliveryDt']
delivery_time = data['TrackPackagesResponse']['packageList'][0]['displayActDeliveryTm']

这是我使用 PHP 请求库最接近的结果:

<?php

$dir = __DIR__;
include $dir .'/vendor/autoload.php';

$tracking_number = '123456789';

$url = 'https://www.fedex.com/trackingCal/track';

$headers = ['Content-Type' => 'application/json'];

$data = ['data' => [
            'TrackPackagesRequest' => [
                'appType'   => 'wtrk',
                'uniqueKey' => '',
                'processingParameters'       => [
                    'anonymousTransaction'    => true,
                    'clientId'                => 'WTRK',
                    'returnDetailedErrors'    => true,
                    'returnLocalizedDateTime' => false
                ],
                'trackingInfoList' => [
                    [
                        'trackNumberInfo'      => [
                            'trackingNumber'    => $tracking_number,
                            'trackingQualifier' => '',
                            'trackingCarrier'   => ''
                        ]
                    ]
                ]
            ]],
    'action' => 'trackpackages',
    'locale' => 'en_US',
    'format' => 'json',
    'version' => 99
    ];
            
$response = Requests::post($url, $headers, json_encode($data));

print_r($response);

但是 returns

{
    "CALError": {
        "code":"UNSUPPORTED.ACTION",
        "message":" is not a supported action",
        "rootCause":null
    }
}

我认为这也会帮助很多其他希望跟踪 FedEx 包裹的人,因为我之前看到过这个问题。

郑重声明,我并不是为了使用他们的 API 而开设 FedEx 帐户。

谢谢, 弗兰克

Python 脚本不会将 POST 请求正文发送为 JSON。它使用 data= 而不是 json=,后者将其作为 URL 编码的 data=value 发送,其中值是 JSON 编码的对象。

您需要在 PHP 版本中进行类似操作。只有 data 参数应编码为 JSON,而不是整个请求。

<?php

$dir = __DIR__;
include $dir .'/vendor/autoload.php';

$tracking_number = '123456789';

$url = 'https://www.fedex.com/trackingCal/track';

$headers = [];

$data = [
    "data" => json_encode([
        "TrackPackagesRequest" => [
            "appType" => "wtrk",
            "uniqueKey" => "",
            "processingParameters" => [
                "anonymousTransaction" => true,
                "clientId" => "WTRK",
                "returnDetailedErrors" => true,
                "returnLocalizedDateTime" => false
            ],
            "trackingInfoList" => [[
                "trackNumberInfo" => [
                    "trackingNumber" => $tracking_number,
                    "trackingQualifier" => "",
                    "trackingCarrier" => ""
                ]
            ]]
        ]

    ]),
    "action" => "trackpackages",
    "locale" => "en_US",
    "format" => "json",
    "version" => 99
];

$response = Requests::post($url, $headers, $data);

print_r($response);