PHP code example of kode / express-api
1. Go to this page and download the library: Download kode/express-api library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kode / express-api example snippets
$config = new \Kode\ExpressApi\EMS\Config([
'app_key' => 'your_production_app_key',
'app_secret' => 'your_production_app_secret',
'sandbox' => false, // 默认值,可省略
]);
$config = new \Kode\ExpressApi\EMS\Config([
'app_key' => 'your_sandbox_app_key',
'app_secret' => 'your_sandbox_app_secret',
'sandbox' => true,
]);
// 韵达配置示例
$yundaConfig = new \Kode\ExpressApi\Yunda\Config([
'app_key' => 'your_yunda_app_key',
'app_secret' => 'your_yunda_app_secret',
'sandbox' => true,
]);
// 中通配置示例
$ztoConfig = new \Kode\ExpressApi\ZTO\Config([
'app_key' => 'your_zto_app_key',
'app_secret' => 'your_zto_app_secret',
'sandbox' => true,
]);
// 申通配置示例
$stoConfig = new \Kode\ExpressApi\STO\Config([
'app_key' => 'your_sto_app_key',
'app_secret' => 'your_sto_app_secret',
'sandbox' => true,
]);
// 菜鸟网络配置示例
$cainiaoConfig = new \Kode\ExpressApi\Cainiao\Config([
'app_key' => 'your_cainiao_app_key',
'app_secret' => 'your_cainiao_app_secret',
'partner_id' => 'your_cainiao_partner_id',
'sandbox' => true,
]);
// 认证过程由SDK自动处理
$client = new \Kode\ExpressApi\EMS\Client($config);
// 首次API调用时会自动获取并缓存访问令牌
$result = $client->queryOrder('123456');
use Kode\ExpressApi\ExpressApiClient;
// 创建EMS配置数组
$emsConfig = [
'app_key' => 'YOUR_EMS_APP_KEY',
'app_secret' => 'YOUR_EMS_APP_SECRET',
'sandbox' => true, // 使用沙箱环境
];
// 创建顺丰配置数组
$sfConfig = [
'app_key' => 'YOUR_SF_APP_KEY',
'app_secret' => 'YOUR_SF_APP_SECRET',
'sandbox' => true,
];
// 创建韵达配置数组
$yundaConfig = [
'app_key' => 'YOUR_YUNDA_APP_KEY',
'app_secret' => 'YOUR_YUNDA_APP_SECRET',
'sandbox' => true,
];
// 创建中通配置数组
$ztoConfig = [
'app_key' => 'YOUR_ZTO_APP_KEY',
'app_secret' => 'YOUR_ZTO_APP_SECRET',
'sandbox' => true,
];
// 创建申通配置数组
$stoConfig = [
'app_key' => 'YOUR_STO_APP_KEY',
'app_secret' => 'YOUR_STO_APP_SECRET',
'sandbox' => true,
];
// 创建菜鸟网络配置数组
$cainiaoConfig = [
'app_key' => 'YOUR_CAINIAO_APP_KEY',
'app_secret' => 'YOUR_CAINIAO_APP_SECRET',
'partner_id' => 'YOUR_CAINIAO_PARTNER_ID',
'sandbox' => true,
];
// 方式1:使用工厂方法创建客户端
$emsClient = ExpressApiClient::create('ems', $emsConfig);
$sfClient = ExpressApiClient::create('sf', $sfConfig);
$yundaClient = ExpressApiClient::create('yunda', $yundaConfig);
$ztoClient = ExpressApiClient::create('zto', $ztoConfig);
$stoClient = ExpressApiClient::create('sto', $stoConfig);
$cainiaoClient = ExpressApiClient::create('cainiao', $cainiaoConfig);
// 方式2:直接创建客户端
$emsClient = new \Kode\ExpressApi\EMS\Client($emsConfig);
$sfClient = new \Kode\ExpressApi\SF\Client($sfConfig);
$yundaClient = new \Kode\ExpressApi\Yunda\Client($yundaConfig);
$ztoClient = new \Kode\ExpressApi\Zto\Client($ztoConfig);
$stoClient = new \Kode\ExpressApi\Sto\Client($stoConfig);
$cainiaoClient = new \Kode\ExpressApi\Cainiao\Client($cainiaoConfig);
// 检查快递公司是否支持
if (ExpressApiClient::isCourierSupported('ems')) {
echo "EMS快递支持";
}
// 获取支持的快递公司列表
$supportedCouriers = ExpressApiClient::getSupportedCouriers();
print_r($supportedCouriers);
// 发货数据
$shipmentData = [
'order_no' => 'ORD' . date('YmdHis'),
'sender' => [
'name' => '张三',
'phone' => '13800138000',
'province' => '广东省',
'city' => '深圳市',
'district' => '南山区',
'address' => '科技园南区8栋',
],
'recipient' => [
'name' => '李四',
'phone' => '13900139000',
'province' => '北京市',
'city' => '北京市',
'district' => '朝阳区',
'address' => '建国路88号',
],
'items' => [
[
'name' => '商品1',
'quantity' => 1,
'weight' => 0.5,
],
],
'weight' => 0.5,
'express_type' => 1,
];
// EMS发货通知
$response = $emsClient->sendShipment($shipmentData);
// 顺丰发货通知
$response = $sfClient->sendShipment($shipmentData);
// 韵达发货通知
$response = $yundaClient->sendShipment($shipmentData);
// 中通发货通知
$response = $ztoClient->sendShipment($shipmentData);
// 申通发货通知
$response = $stoClient->sendShipment($shipmentData);
// 菜鸟网络发货通知
$response = $cainiaoClient->sendShipment($shipmentData);
// 批量发货数据
$batchShipmentData = [
[
'order_no' => 'ORD001',
// 其他发货数据...
],
[
'order_no' => 'ORD002',
// 其他发货数据...
],
];
// EMS批量发货
$response = $emsClient->batchSendShipment($batchShipmentData);
// 顺丰批量发货
$response = $sfClient->batchSendShipment($batchShipmentData);
// 韵达批量发货
$response = $yundaClient->batchSendShipment($batchShipmentData);
// 中通批量发货
$response = $ztoClient->batchSendShipment($batchShipmentData);
// 申通批量发货
$response = $stoClient->batchSendShipment($batchShipmentData);
// 菜鸟网络批量发货
$response = $cainiaoClient->batchSendShipment($batchShipmentData);
// 取件数据
$pickupData = [
'order_no' => 'ORD001',
'pickup_time' => date('Y-m-d H:i:s', strtotime('+1 hour')),
'sender' => [
'name' => '张三',
'phone' => '13800138000',
'address' => '广东省深圳市南山区科技园',
],
];
// EMS取件通知
$response = $emsClient->pickupNotice($pickupData);
// 顺丰取件通知
$response = $sfClient->pickupNotice($pickupData);
// 韵达取件通知
$response = $yundaClient->pickupNotice($pickupData);
// 中通取件通知
$response = $ztoClient->pickupNotice($pickupData);
// 申通取件通知
$response = $stoClient->pickupNotice($pickupData);
// 菜鸟网络取件通知
$response = $cainiaoClient->pickupNotice($pickupData);
// 查询订单(参数为订单ID字符串)
$orderId = 'ORD001';
// EMS订单查询
$response = $emsClient->queryOrder($orderId);
// 顺丰订单查询
$response = $sfClient->queryOrder($orderId);
// 韵达订单查询
$response = $yundaClient->queryOrder($orderId);
// 中通订单查询
$response = $ztoClient->queryOrder($orderId);
// 申通订单查询
$response = $stoClient->queryOrder($orderId);
// 菜鸟网络订单查询
$response = $cainiaoClient->queryOrder($orderId);
// 批量查询订单(参数为订单ID字符串数组)
$orderIds = ['ORD001', 'ORD002'];
// EMS批量查询订单
$response = $emsClient->batchQueryOrders($orderIds);
// 顺丰批量查询订单
$response = $sfClient->batchQueryOrders($orderIds);
// 韵达批量查询订单
$response = $yundaClient->batchQueryOrders($orderIds);
// 中通批量查询订单
$response = $ztoClient->batchQueryOrders($orderIds);
// 申通批量查询订单
$response = $stoClient->batchQueryOrders($orderIds);
// 菜鸟网络批量查询订单
$response = $cainiaoClient->batchQueryOrders($orderIds);
// 取消订单(参数:订单ID,可选取消原因)
$orderId = 'ORD001';
$reason = '客户取消';
// EMS取消订单
$response = $emsClient->cancelOrder($orderId, $reason);
// 顺丰取消订单
$response = $sfClient->cancelOrder($orderId, $reason);
// 韵达取消订单
$response = $yundaClient->cancelOrder($orderId, $reason);
// 中通取消订单
$response = $ztoClient->cancelOrder($orderId, $reason);
// 申通取消订单
$response = $stoClient->cancelOrder($orderId, $reason);
// 菜鸟网络取消订单
$response = $cainiaoClient->cancelOrder($orderId, $reason);
// 查询轨迹(参数:运单号,可选语言)
$trackingNo = 'SF1234567890';
// EMS轨迹查询
$response = $emsClient->queryTracking($trackingNo);
// 顺丰轨迹查询
$response = $sfClient->queryTracking($trackingNo);
// 韵达轨迹查询
$response = $yundaClient->queryTracking($trackingNo);
// 中通轨迹查询
$response = $ztoClient->queryTracking($trackingNo);
// 申通轨迹查询
$response = $stoClient->queryTracking($trackingNo);
// 菜鸟网络轨迹查询
$response = $cainiaoClient->queryTracking($trackingNo);
// 批量查询轨迹(参数为运单号字符串数组)
$trackingNumbers = ['SF1234567890', 'SF0987654321'];
// EMS批量轨迹查询
$response = $emsClient->batchQueryTracking($trackingNumbers);
// 顺丰批量轨迹查询
$response = $sfClient->batchQueryTracking($trackingNumbers);
// 韵达批量轨迹查询
$response = $yundaClient->batchQueryTracking($trackingNumbers);
// 中通批量轨迹查询
$response = $ztoClient->batchQueryTracking($trackingNumbers);
// 申通批量轨迹查询
$response = $stoClient->batchQueryTracking($trackingNumbers);
// 菜鸟网络批量轨迹查询
$response = $cainiaoClient->batchQueryTracking($trackingNumbers);
// 拦截件(参数:订单ID + 可选拦截数据数组)
$orderId = 'ORD001';
$interceptData = ['reason' => '发错地址'];
// EMS拦截件
$response = $emsClient->intercept($orderId, $interceptData);
// 顺丰拦截件
$response = $sfClient->intercept($orderId, $interceptData);
// 韵达拦截件
$response = $yundaClient->intercept($orderId, $interceptData);
// 中通拦截件
$response = $ztoClient->intercept($orderId, $interceptData);
// 申通拦截件
$response = $stoClient->intercept($orderId, $interceptData);
// 菜鸟网络拦截件
$response = $cainiaoClient->intercept($orderId, $interceptData);
// 改件信息(参数:订单ID + 修改数据数组)
$orderId = 'ORD001';
$modifyData = [
'new_address' => [
'name' => '王五',
'phone' => '13700137000',
'province' => '上海市',
'city' => '上海市',
'district' => '浦东新区',
'address' => '陆家嘴金融中心',
],
];
// EMS改件信息
$response = $emsClient->modify($orderId, $modifyData);
// 顺丰改件信息
$response = $sfClient->modify($orderId, $modifyData);
// 韵达改件信息
$response = $yundaClient->modify($orderId, $modifyData);
// 中通改件信息
$response = $ztoClient->modify($orderId, $modifyData);
// 申通改件信息
$response = $stoClient->modify($orderId, $modifyData);
// 菜鸟网络改件信息
$response = $cainiaoClient->modify($orderId, $modifyData);
// 面单打印(参数:订单ID + 可选面单配置数组)
$orderId = 'ORD001';
$printData = [
'template_config' => [
// 面单配置...
],
];
// EMS面单打印
$response = $emsClient->printLabel($orderId, $printData);
// 顺丰面单打印
$response = $sfClient->printLabel($orderId, $printData);
// 韵达面单打印
$response = $yundaClient->printLabel($orderId, $printData);
// 中通面单打印
$response = $ztoClient->printLabel($orderId, $printData);
// 申通面单打印
$response = $stoClient->printLabel($orderId, $printData);
// 菜鸟网络面单打印
$response = $cainiaoClient->printLabel($orderId, $printData);
// 批量面单打印(参数:订单ID字符串数组 + 可选打印配置)
$orderIds = ['ORD001', 'ORD002'];
$printData = [
'template_config' => [
// 面单配置...
],
];
// EMS批量面单打印
$response = $emsClient->batchPrintLabels($orderIds, $printData);
// 顺丰批量面单打印
$response = $sfClient->batchPrintLabels($orderIds, $printData);
// 韵达批量面单打印
$response = $yundaClient->batchPrintLabels($orderIds, $printData);
// 中通批量面单打印
$response = $ztoClient->batchPrintLabels($orderIds, $printData);
// 申通批量面单打印
$response = $stoClient->batchPrintLabels($orderIds, $printData);
// 菜鸟网络批量面单打印
$response = $cainiaoClient->batchPrintLabels($orderIds, $printData);
use Kode\ExpressApi\ExpressApiClient;
// 顺丰国际配置(HMAC-SHA256 签名鉴权)
$sfIntlConfig = [
'app_key' => 'YOUR_SF_INTL_APP_KEY',
'app_secret' => 'YOUR_SF_INTL_APP_SECRET',
'customer_code' => 'YOUR_CUSTOMER_CODE',
'sandbox' => true,
];
$client = ExpressApiClient::create('sf_international', $sfIntlConfig);
// 空运下单(自动注入 mode = air)
$response = $client->createAirFreight([
'order_no' => 'INTL' . date('YmdHis'),
'destination_country' => 'US',
'sender' => ['name' => '张三', 'phone' => '13800138000', 'address' => '深圳市南山区'],
'recipient' => ['name' => 'John', 'phone' => '1234567890', 'address' => '1st Ave, New York'],
'items' => [['name' => '样品', 'quantity' => 1, 'weight' => 0.5]],
'hs_code' => '123456',
'product_name' => 'Sample',
'declared_value' => 10,
'currency' => 'USD',
'origin_country' => 'CN',
]);
// 运费报价
$quote = $client->getQuotation([
'mode' => 'air',
'origin' => 'CN',
'destination' => 'US',
'weight' => 1.2,
]);
// 海关申报
$customs = $client->declareCustoms([
'hs_code' => '123456',
'product_name' => 'Sample',
'declared_value' => 10,
'currency' => 'USD',
'origin_country' => 'CN',
]);
use Kode\ExpressApi\ExpressApiClient;
// 德邦物流配置(MD5 签名鉴权)
$debangConfig = [
'app_key' => 'YOUR_DEBANG_APP_KEY',
'app_secret' => 'YOUR_DEBANG_APP_SECRET',
'sandbox' => true,
];
$client = ExpressApiClient::create('debang', $debangConfig);
// 零担下单(自动注入 service_type = ltl)
$response = $client->createLtl([
'order_no' => 'LTL' . date('YmdHis'),
'sender' => ['name' => '张三', 'phone' => '13800138000', 'address' => '上海市浦东新区XX路1号'],
'receiver' => ['name' => '李四', 'phone' => '13900139000', 'address' => '北京市朝阳区XX街2号'],
'goods' => [['name' => '机械设备', 'weight' => 500]],
'origin' => '上海',
'destination' => '北京',
]);
// 整车下单(自动注入 service_type = ftl)
$response = $client->createFtl([ /* 同上结构 */ ]);
// 运费报价
$quote = $client->getQuotation([
'service_type' => 'ltl',
'origin' => '上海',
'destination' => '北京',
'weight' => 500,
]);
// 网点查询
$network = $client->queryNetwork([
'city' => '上海',
'keyword' => '浦东',
]);
use Kode\ExpressApi\ExpressApiClient;
// 仅凭运单号推断承运商(无需手动指定)
$courier = ExpressApiClient::recognize('SF1234567890123'); // => 'sf'
$courier = ExpressApiClient::recognize('JD0091234567890'); // => 'jd'
use Kode\ExpressApi\ExpressApiClient;
// 聚合已签约的聚合查询服务商,构建权威解析器(自动忽略非聚合商 / 无效配置)
$resolver = ExpressApiClient::buildAggregateResolver([
'seventeentrack' => ['app_secret' => 'YOUR_17TRACK_TOKEN'],
'kuaidi100' => ['app_key' => 'K', 'app_secret' => 'S'],
]);
// 方式一:注册为全局解析器(此后 recognize 自动回退)
\Kode\ExpressApi\Common\CourierRecognizer::setResolver($resolver);
// 方式二:单次识别时透传(推荐,避免全局状态)
$courier = ExpressApiClient::recognize('UNKNOWN-INTL-999', $resolver); // => 'dhl'(示例)
$chain = ExpressApiClient::buildChain(
['origin' => 'CN', 'dest' => 'US', 'weight' => 5, 'mode' => 'air'],
[
'sf' => $sfConfig, 'debang' => $debangConfig,
'dhl' => $dhlConfig, 'ems_international' => $emsIntlConfig, 'jd' => $jdConfig,
]
// 可选:环节级覆盖,如 ['crossborder' => 'fourpx']
);
$legs = $chain->toArray()['legs'];
// => [揽收(sf), 干线(debang), 跨境(dhl), 清关(ems_international), 末端(jd)]
$chain = ExpressApiClient::chainFromTracking('SF1234567890123', ['sf' => $sfConfig]);
$info = $chain->toArray();
// $info['detected_courier'] => 'sf' // 自动识别的承运商
// $info['suggested_chain'] => [...] // 推断的完整 5 环节链路模板
$menu = ExpressApiClient::getApiMenu();
// $menu['couriers']['fourpx']['operations']['freight'] => ['createSeaFreight','createAirFreight','getQuotation']
// $menu['couriers']['fourpx']['operations']['customs'] => ['declareCustoms','queryCustoms']
use Kode\ExpressApi\Common\HttpClient;
// 额外重试 2 次,基础延迟 200ms(实际延迟 200ms / 400ms)
HttpClient::setRetry(2, 200);
// 关闭重试(默认)
HttpClient::setRetry(0);
use Kode\ExpressApi\Common\ResponseHandler;
ResponseHandler::registerPolicy(
'my_courier',
static fn(array $r): bool => ($r['result'] ?? '') === 'FAIL', // 错误判定
static fn(array $r): array => $r['body'] ?? $r // 数据解包
);
use Kode\ExpressApi\ExpressApiClient;
$result = ExpressApiClient::batchQueryTracking([
['courier' => 'ems', 'number' => 'EMS123'],
['courier' => 'sf', 'number' => 'SF456'],
['courier' => 'dhl', 'number' => 'DHL789'],
]);
// $result['success'] => 成功条数
// $result['failed'] => 失败条数
// $result['results'][0] => ['index'=>0,'courier'=>'ems','number'=>'EMS123','ok'=>true,'data'=>[...]]
echo ExpressApiClient::version(); // 例如 "2.9.0"
$meta = HttpClient::getLastMeta();
// ['url'=>'...','method'=>'GET','http_code'=>200,'attempt'=>1,'duration_ms'=>37]
$template = [
'id' => 'ems_standard_100x150',
'name' => 'EMS标准面单(100mm×150mm)',
'size' => [
'width' => 100, // 宽度(mm)
'height' => 150, // 高度(mm)
],
'fields' => [
'sender_name' => [
'x' => 10, // X坐标(mm)
'y' => 20, // Y坐标(mm)
'width' => 50, // 宽度(mm)
'height' => 5, // 高度(mm)
'font_size' => 12,
'align' => 'left',
],
'receiver_name' => [
'x' => 10,
'y' => 40,
'width' => 50,
'height' => 5,
'font_size' => 12,
'align' => 'left',
],
// 更多字段...
],
];
use Kode\ExpressApi\Label\LayoutManager;
$layoutManager = new LayoutManager();
// 创建面单模板
$template = $layoutManager->createTemplate([
'name' => 'EMS标准面单',
'size' => ['width' => 100, 'height' => 150],
]);
// 添加字段
$template->addField('sender_name', [
'x' => 10,
'y' => 20,
'width' => 50,
'height' => 5,
]);
// 保存模板
$layoutManager->saveTemplate($template);
// 读取模板
$template = $layoutManager->getTemplate('ems_standard');
// 获取所有字段
$fields = $template->getFields();
// 为字段设置实际值
if (isset($fields['sender_name'])) {
$fields['sender_name']->setValue('张三');
}
if (isset($fields['receiver_name'])) {
$fields['receiver_name']->setValue('李四');
}
// 获取字段值
$senderName = $fields['sender_name']->getValue();
$receiverName = $fields['receiver_name']->getValue();
// 转换为数组格式(用于API传输或存储)
$fieldArray = $fields['sender_name']->toArray();
$templateConfig = [
'size' => 'ems_default',
'dimensions' => [
'width' => 100,
'height' => 140,
],
'fields' => [
[
'id' => 'tracking_number',
'label' => '物流单号',
'type' => 'text',
'x' => 10,
'y' => 10,
'width' => 80,
'height' => 15,
'fontSize' => 10,
'fontFamily' => 'Arial',
'fontWeight' => 'bold',
'align' => 'center',
'showLabel' => true,
'labelPosition' => 'top',
],
[
'id' => 'tracking_barcode',
'label' => '条形码',
'type' => 'barcode',
'x' => 5,
'y' => 30,
'width' => 90,
'height' => 30,
'barcodeType' => 'code128',
'showLabel' => false,
],
// 更多字段配置...
],
];
new MultilingualField(string $id, array $config = [])
use Kode\ExpressApi\Label\MultilingualField;
// 创建多语言字段
$field = new MultilingualField('product_name', [
'labels' => [
'zh' => '产品名称',
'en' => 'Product Name',
'ja' => '商品名',
'ko' => '제품명'
],
'x' => 10,
'y' => 30,
'width' => 50,
'height' => 5,
'font_size' => 10
]);
// 设置当前语言
$field->setLanguage('en'); // 显示英文标签
echo $field->getLabel(); // 输出: Product Name
$field->setLanguage('ja'); // 显示日文标签
echo $field->getLabel(); // 输出: 商品名
// 获取特定语言的标签
echo $field->getLabelByLanguage('ko'); // 输出: 제품명
// 添加新的语言标签
$field->addLabel('fr', 'Nom du produit');
echo $field->getLabelByLanguage('fr'); // 输出: Nom du produit
use Kode\ExpressApi\Label\AdvancedLayoutManager;
$layoutManager = new AdvancedLayoutManager('/path/to/templates');
$config = [
'id' => 'multilingual_template',
'name' => '多语言模板',
'courier' => 'ems',
'size' => ['width' => 100, 'height' => 150],
'fields' => [
'sender' => [
'label' => '发件人',
'x' => 5,
'y' => 5,
'width' => 40,
'height' => 10
],
'product_name' => [
'labels' => [
'zh' => '产品名称',
'en' => 'Product Name',
'ja' => '商品名'
],
'x' => 5,
'y' => 20,
'width' => 50,
'height' => 5,
'font_size' => 8
]
]
];
// 成功响应
[
'success' => true,
'data' => [...], // API返回的数据
'message' => 'success',
'code' => 0,
]
// 失败响应
[
'success' => false,
'data' => null,
'message' => '错误信息',
'code' => 错误代码,
]
$emsConfig = [
'app_key' => 'YOUR_EMS_APP_KEY',
'app_secret' => 'YOUR_EMS_APP_SECRET',
'sandbox' => true, // 使用沙箱环境
];
$sfConfig = [
'app_key' => 'YOUR_SF_APP_KEY',
'app_secret' => 'YOUR_SF_APP_SECRET',
'sandbox' => true,
];
$yundaConfig = [
'app_key' => 'YOUR_YUNDA_APP_KEY',
'app_secret' => 'YOUR_YUNDA_APP_SECRET',
'sandbox' => true,
];
$ztoConfig = [
'app_key' => 'YOUR_ZTO_APP_KEY',
'app_secret' => 'YOUR_ZTO_APP_SECRET',
'sandbox' => true,
];
$stoConfig = [
'app_key' => 'YOUR_STO_APP_KEY',
'app_secret' => 'YOUR_STO_APP_SECRET',
'sandbox' => true,
];
$cainiaoConfig = [
'app_key' => 'YOUR_CAINIAO_APP_KEY',
'app_secret' => 'YOUR_CAINIAO_APP_SECRET',
'partner_id' => 'YOUR_CAINIAO_PARTNER_ID',
'sandbox' => true,
];
bash
php -S localhost:8000 -t src/Label/Visualizer/