简体   繁体   中英

Issue sending post request to API | PHP

Essentially I need to send the appropriate POST request to the following Parcel Tracking API that return the shipping data from the courier provided:

API Doc: https://www.kd100.com/docs/real-time-shipment-tracking

The problem I am having, is the response:

[code] => 104
[message] => Invalid signature

Can someone please have a look at my request below and tell me if I've made a mistake based on the doc? Assuming the Key, Secret Key and Tracking data is correct, my request should be completely valid.

My POST Request so far:

$key = 'KEY';
$secret = 'SECRET KEY';
$param = array (
    'carrier_id' => 'usps',
    'tracking_number' => 'TRACKING #'
);

$post_data = array();
$post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);

$header_data = array();
$header_data['API-Key'] = $key;
$sign = md5($post_data['param'].$key.$secret);
$header_data['signature'] = strtoupper($sign);

$url = 'https://www.kd100.com/api/v1/tracking/realtime';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "signature: $sign",
  "API-Key: $key"
));

$result = curl_exec($ch);
$data = json_decode($result, true);

echo '<br/><br/>Start:<br/><pre>';
echo print_r($data);
echo '</pre>';

Your signature is not in uppercase. You set $sign variable but never actually set uppercase to it. You actually set uppercase to $header_data['signature'] and then never use it.

$sign = md5($post_data['param'].$key.$secret);
$header_data['signature'] = strtoupper($sign);

Your problem should be solved if you write it like this:

$sign = strtoupper(md5(post_data['param'].$key.$secret));

Remember to clean your code. You don't actually use $header_data anywhere

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM