You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PHP变量传入CURL POST字段解决ShipStation接口orderId报错

问题原因

报错是因为手动拼接JSON字符串作为POST参数时,出现了格式、类型匹配错误,导致接口无法正确解析orderId字段值:

  • 你定义的$order2是字符串类型,接口要求orderId为整数类型
  • 手动拼接JSON如果后续变量出现特殊字符、空值等场景,会直接生成无效JSON,导致解析失败

解决方案

推荐使用PHP数组定义所有请求参数,再通过json_encode()函数自动生成合法的JSON字符串,避免手动拼接的格式错误。

修正后完整代码

<?php
$order2 = "1604";
$curl2 = curl_init();

// 先定义请求参数数组,自动处理类型和格式
$postData = [
    'orderId' => intval($order2), // 转成整数类型匹配接口要求
    'carrierCode' => 'stamps_com',
    'serviceCode' => 'usps_priority_mail',
    'packageCode' => 'small_flat_rate_box',
    'confirmation' => null,
    'shipDate' => '2021-11-05',
    'weight' => [
        'value' => 2,
        'units' => 'pounds'
    ],
    'dimensions' => null,
    'insuranceOptions' => null,
    'internationalOptions' => null,
    'advancedOptions' => null,
    'testLabel' => true
];

curl_setopt_array($curl2, array(
    CURLOPT_URL => "https://ssapi.shipstation.com/orders/createlabelfororder",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode($postData), // 用生成的合法JSON
    CURLOPT_HTTPHEADER => array(
        "Host: ssapi.shipstation.com",
        "Authorization:Basic MYAUTHCODE",
        "Content-Type: application/json"
    ),
));

$response2 = curl_exec($curl2);

curl_close($curl2);
echo $response2;

内容的提问来源于stack exchange,提问作者Sohaib TechnorayX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:06:04