开发者

Curl and FedEx API responding with gibberish in PHP

I've been trying to implement the FedEx rates and transit times API in a PHP script. I successfully connected with it to get the bearer token. But when I try to get rates for a simple shipment, it responds with random gibberish.

I don't even get any errors. That's what frustrating.

Here is my code:

ini_set('display_errors', 1); 
error_reporting(-1);

$access_url = 'https://apis-sandbox.fedex.com/oauth/token';
    $access_headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
    $access_fields = "grant_type=client_credentials&client_id=...&client_secret=...";
    
    $resp = curl_me($access_url, $access_headers, $access_fields);
    
    $access_token = json_decode($resp)->access_token;

    $rate_url = 'https://apis-sandbox.fedex.com/rate/v1/rates/quotes';
    $rate_hdrs =  [
        'Authorization' => 'Bearer '.$access_token,
        'X-locale' => 'en_US',
        'Content-Type' => 'application/json'
    ];
        
    $rate_flds = '{
        "accountNumber": {
            "value": "..."
        },
        "requestedShipment": {
            "shipper": {
                "address": {
                    "streetLines": [
                        "..."
                    ],
                    "city": "...",
                    "stateOrProvinceCode": "...",
                    "postalCode": "...",
                    "countryCode": "US",
                    "residential": false
                }
            },
            "recipient": {
                "address": {
                    "postalCode": "...",
                    "countryCode": "US"
                }
            },
            "shipDateStamp": "2022-12-06",
            "pickupType": "DROPOFF_AT_FEDEX_LOCATION",
            "requestedPackageLineItems": [{
                "declaredValue": {
                    "amount": 123,
                    "currency": "USD"
                },
                "weight": {
                    "units": "LB",
                    "value": 12
                },
                "dimensions": {
                    "length": 12,
                    "width": 12,
                    "height": 12,
                    "units": "IN"
          开发者_Python百科      }
            }],
            "documentShipment": false,
            "packagingType": "YOUR_PACKAGING",
            "groupShipment": true
        },
        "carrierCodes": [
            "FDXE"
        ]
    }';
    
    $field = build_post_fields($rate_flds);
    
    $resp = curl_me($rate_url, $rate_hdrs, $field);
    
    var_dump($resp);

Here are the two functions I'm using:

function curl_me($url, $headers, $postfields){
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
    
    $response = curl_exec($ch);

    echo curl_error($ch);
    
    curl_close($ch);
        
    return $response;
        
}
function build_post_fields( $data,$existingKeys='',&$returnArray=[]){
    if(($data instanceof CURLFile) or !(is_array($data) or is_object($data))){
        $returnArray[$existingKeys]=$data;
        return $returnArray;
    }
    else{
        foreach ($data as $key => $item) {
            build_post_fields($item,$existingKeys?$existingKeys."[$key]":$key,$returnArray);
        }
        return $returnArray;
    }
}

The second function is from Yisrael Dov's answer to this question.

When I used the first function to get the access token, it worked flawlessly. But I can't figure out why the second time I used it responded with: string(176) "��� �@��W朢%jނ��d�]���(R������I���oFgHY�ת��r҆IH/"�Eq�zi����MJ{��6� �..."

I tried all kinds of different was of encoding and decoding the JSON string. But I get gibberish every time.

I've tried running that gibberish through various decoders, but of course they all returned NULL.

I was expecting at least some kind of error or warning.

Any ideas would be appreciated.


$rate_hdrs =  [
    'Authorization: Bearer '.$access_token,
    'X-locale: en_US',
    'Content-Type: application/json',
];

look this: PHP cURL custom headers


Thanks to everyone for the awesome input!

I'm new to CURL, so pardon my not recognizing these mistakes.

I combined Sammitch's comments with Walter KT's answer.

Sammitch was right: the response was gzip encoded. I added curl_setopt($ch, CURLOPT_ENCODING, "gzip"); to my function, and finally got the response (with some handy errors to work through).

I also got rid of the build_post_fields() function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜