PHPackages                             tourze/cainiao-pickup-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. tourze/cainiao-pickup-bundle

ActiveSymfony-bundle

tourze/cainiao-pickup-bundle
============================

菜鸟驿站快递代收服务集成包

0.0.1(5mo ago)00MITPHPCI passing

Since Nov 16Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/cainiao-pickup-bundle)[ Packagist](https://packagist.org/packages/tourze/cainiao-pickup-bundle)[ RSS](/packages/tourze-cainiao-pickup-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (42)Versions (2)Used By (0)

CainiaoPickupBundle
===================

[](#cainiaopickupbundle)

[English](README.md) | [中文](README.zh-CN.md)

[![PHP Version](https://camo.githubusercontent.com/203e41ee67a084a9147d998a7638fdd19a17a2d2e57e56ebfb1f01a8a22171b1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f6361696e69616f2d7069636b75702d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/cainiao-pickup-bundle)[![Latest Version](https://camo.githubusercontent.com/e65fa9466bf3e60baa64845a6dd548609e2bd8c3ef28e55f44b22a7230446a36/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f6361696e69616f2d7069636b75702d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/cainiao-pickup-bundle)[![License](https://camo.githubusercontent.com/50b8b7afc09b4db703bc0fbd5ba81458ec59845360593e48d4f3610fc5cd278f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f6361696e69616f2d7069636b75702d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/cainiao-pickup-bundle)[![Total Downloads](https://camo.githubusercontent.com/745d0f669c3be5c0fc78fe60e07bd6282faf6292d853412e354b13e2ed23e2b4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f6361696e69616f2d7069636b75702d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/cainiao-pickup-bundle)[![Code Coverage](https://camo.githubusercontent.com/b28fb224dc49e033478b4a222a71e1bc1c66e11b6424ea1d02eb75d3695caf37/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d38352532352d627269676874677265656e3f7374796c653d666c61742d737175617265)](https://github.com/tourze/php-monorepo/actions)

A Symfony bundle for integrating with Cainiao pickup service, providing pickup order management, logistics tracking, and comprehensive order lifecycle management.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Dependencies](#dependencies)
- [Quick Start](#quick-start)
- [Console Commands](#console-commands)
- [Configuration](#configuration)
- [Advanced Usage](#advanced-usage)
- [Exception Handling](#exception-handling)
- [Security](#security)
- [Contributing](#contributing)
- [Testing](#testing)
- [License](#license)
- [Support](#support)
- [Credits](#credits)

Features
--------

[](#features)

- 🚚 Complete pickup order management (create, modify, cancel)
- 📦 Support for multiple item types (documents, packages, etc.)
- 📍 Detailed address management for senders and receivers
- 🔄 Real-time order status tracking (20+ status types)
- 📊 Logistics detail querying and tracking
- 🏭 Multi-configuration support for different warehouses/providers
- 🔒 Secure API communication with signature verification
- 🎯 Built-in exception handling for various API scenarios
- 🛠️ Symfony console commands for batch operations
- 📝 Comprehensive entity relationships with Doctrine ORM

Installation
------------

[](#installation)

```
composer require tourze/cainiao-pickup-bundle
```

After installation, register the bundle in your `config/bundles.php`:

```
return [
    // ...
    CainiaoPickupBundle\CainiaoPickupBundle::class => ['all' => true],
];
```

Dependencies
------------

[](#dependencies)

This bundle requires the following:

### PHP Requirements

[](#php-requirements)

- PHP 8.1 or higher
- SPL, date, json, random extensions

### Symfony Requirements

[](#symfony-requirements)

- Symfony 7.3 or higher
- Doctrine ORM 3.0+
- Doctrine DBAL 4.0+
- Symfony HttpClient component

### Internal Dependencies

[](#internal-dependencies)

- `tourze/doctrine-indexed-bundle`
- `tourze/doctrine-snowflake-bundle`
- `tourze/doctrine-timestamp-bundle`
- `tourze/doctrine-track-bundle`
- `tourze/doctrine-user-bundle`
- `tourze/enum-extra`

All dependencies are automatically managed by Composer.

Quick Start
-----------

[](#quick-start)

### 1. Configure Cainiao API Credentials

[](#1-configure-cainiao-api-credentials)

First, create a Cainiao configuration in your database:

```
use CainiaoPickupBundle\Entity\CainiaoConfig;

$config = new CainiaoConfig();
$config->setName('Main Warehouse')
    ->setAppKey('your_app_key')
    ->setAppSecret('your_app_secret')
    ->setAccessCode('your_access_code')
    ->setProviderId('your_provider_id')
    ->setApiGateway('https://gateway.cainiao.com/gateway/api');

$entityManager->persist($config);
$entityManager->flush();
```

### 2. Create a Pickup Order

[](#2-create-a-pickup-order)

```
use CainiaoPickupBundle\Service\PickupService;
use CainiaoPickupBundle\Enum\ItemTypeEnum;

$pickupService = $container->get(PickupService::class);

$orderData = [
    // Sender information
    'senderName' => 'John Doe',
    'senderPhone' => '13800138000',
    'senderFullAddress' => 'Building A, 123 Street, Beijing',
    'senderProvince' => 'Beijing',
    'senderCity' => 'Beijing',
    'senderArea' => 'Chaoyang District',

    // Receiver information
    'receiverName' => 'Jane Smith',
    'receiverPhone' => '13900139000',
    'receiverFullAddress' => 'Building B, 456 Avenue, Shanghai',
    'receiverProvince' => 'Shanghai',
    'receiverCity' => 'Shanghai',
    'receiverArea' => 'Pudong District',

    // Item details
    'itemType' => ItemTypeEnum::PACKAGE->value,
    'weight' => 2.5, // in kg
    'itemQuantity' => 1,
    'itemValue' => 100.00,
    'remark' => 'Fragile items',

    // Pickup time window (optional)
    'expectPickupTimeStart' => '2024-01-20 14:00:00',
    'expectPickupTimeEnd' => '2024-01-20 18:00:00',
];

$order = $pickupService->createPickupOrder($orderData);

echo "Order created: " . $order->getOrderCode();
echo "Tracking number: " . $order->getMailNo();
```

### 3. Track Order Status

[](#3-track-order-status)

```
// Get order by code
$order = $pickupService->getOrderDetail('PK20240120123456');

// Check current status
echo "Current status: " . $order->getStatus()->getLabel();

// Get logistics details
$cainiaoHttpClient = $container->get(CainiaoHttpClient::class);
$logistics = $cainiaoHttpClient->queryLogisticsDetail($order);

foreach ($logistics['logisticsDetails'] as $detail) {
    echo $detail['time'] . ' - ' . $detail['desc'] . PHP_EOL;
}
```

### 4. Cancel an Order

[](#4-cancel-an-order)

```
try {
    $cancelledOrder = $pickupService->cancelPickupOrder($order, 'Customer request');
    echo "Order cancelled successfully";
} catch (OrderCannotBeCancelledException $e) {
    echo "Cannot cancel order: " . $e->getMessage();
}
```

Console Commands
----------------

[](#console-commands)

### Sync Pickup Orders

[](#sync-pickup-orders)

Synchronize pickup order details from Cainiao API:

```
# Sync all unfinished orders
bin/console cainiao:pickup:sync-orders

# Sync a specific order by order code
bin/console cainiao:pickup:sync-orders --order-code="PK20240120123456"
```

This command will:

- Update order status and details from Cainiao API
- Sync all unfinished orders if no order code is specified
- Handle errors gracefully for individual orders in batch operations

Sync Logistics Details
----------------------

[](#sync-logistics-details)

Synchronize logistics tracking information for pickup orders:

```
# Sync logistics for all orders with warehouse confirmed status
bin/console cainiao:pickup:sync-logistics

# Sync logistics for a specific order
bin/console cainiao:pickup:sync-logistics --order-code="PK20240120123456"
```

This command will:

- Query and update logistics tracking details from Cainiao API
- Replace existing logistics details with fresh data
- Include courier information when available
- Process all warehouse-confirmed orders if no order code is specified

Configuration
-------------

[](#configuration)

### Entity Relationships

[](#entity-relationships)

The bundle provides the following main entities:

- **CainiaoConfig**: API configuration for different warehouses/providers
- **PickupOrder**: Main order entity with full lifecycle tracking
- **AddressInfo**: Embedded value object for sender/receiver addresses
- **LogisticsDetail**: Tracking information for orders

### Order Status Types

[](#order-status-types)

The bundle supports 20+ order statuses, including:

- `CREATE` (0): Order created
- `WAREHOUSE_ACCEPT` (100): Warehouse accepted
- `ACCEPT` (400): Package picked up
- `TRANSPORT` (500): In transit
- `DELIVERING` (600): Out for delivery
- `SIGN` (1000): Delivered
- `CANCELLED`: Order cancelled

### Item Types

[](#item-types)

Supported item types:

- `DOC`: Documents
- `SPX`: Small packages
- `PACKAGE`: Standard packages
- `OTHER`: Other items

Advanced Usage
--------------

[](#advanced-usage)

### Pre-query Service Availability

[](#pre-query-service-availability)

```
$availability = $cainiaoHttpClient->preQueryPickupService($order);

if ($availability['isFull']) {
    echo "Service is full for the requested time";
} else {
    echo "Available time slots:";
    foreach ($availability['availableTimeSlots'] as $slot) {
        echo $slot['startTime'] . ' - ' . $slot['endTime'] . PHP_EOL;
    }
}
```

### Modify an Existing Order

[](#modify-an-existing-order)

```
$modificationData = [
    'weight' => 3.0, // Update weight
    'remark' => 'Updated: Handle with extra care',
    'expectPickupTimeStart' => '2024-01-21 09:00:00',
    'expectPickupTimeEnd' => '2024-01-21 12:00:00',
];

try {
    $modifiedOrder = $pickupService->modifyPickupOrder($order, $modificationData);
    echo "Order modified successfully";
} catch (OrderModificationFailedException $e) {
    echo "Cannot modify order: " . $e->getMessage();
}
```

### Query Orders by Status

[](#query-orders-by-status)

```
use CainiaoPickupBundle\Enum\OrderStatusEnum;
use CainiaoPickupBundle\Repository\PickupOrderRepository;

$orderRepository = $container->get(PickupOrderRepository::class);

// Get all orders in transit
$ordersInTransit = $orderRepository->findByStatus(OrderStatusEnum::TRANSPORT);

// Get all delivered orders
$deliveredOrders = $orderRepository->findByStatus(OrderStatusEnum::SIGN);

// Get all unfinished orders
$unfinishedOrders = $orderRepository->findUnfinishedOrders();
```

Exception Handling
------------------

[](#exception-handling)

The bundle provides specific exceptions for different scenarios:

- `ConfigurationException`: When Cainiao API configuration is missing or invalid
- `CainiaoApiException`: General API communication errors
- `InvalidResponseException`: When API returns unexpected response format
- `OrderNotFoundException`: When requested order doesn't exist
- `OrderCannotBeCancelledException`: When order status doesn't allow cancellation
- `OrderCancellationFailedException`: When cancellation request fails
- `OrderModificationFailedException`: When modification request fails

Security
--------

[](#security)

### API Security

[](#api-security)

This bundle implements several security measures:

- **Signature Verification**: All API requests to Cainiao are signed using HMAC-SHA256
- **HTTPS Communication**: All API calls are made over HTTPS
- **Access Token Management**: Secure storage and handling of API credentials
- **Input Validation**: All user input is validated using Symfony's validator component

### Data Protection

[](#data-protection)

- **Sensitive Data**: API keys and secrets are stored securely in the database
- **Logging**: Sensitive information is excluded from logs by default
- **Data Encryption**: Consider encrypting sensitive configuration data at rest

### Best Practices

[](#best-practices)

1. **Credential Management**:

    - Store API credentials in environment variables or secure configuration
    - Rotate API keys regularly
    - Use different credentials for different environments
2. **Network Security**:

    - Use HTTPS for all API communications
    - Implement rate limiting to prevent API abuse
    - Monitor API usage for unusual patterns
3. **Database Security**:

    - Use proper database permissions
    - Encrypt sensitive data columns if required
    - Regular security audits of stored data

If you discover a security vulnerability, please send an e-mail to  instead of using the issue tracker.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on submitting patches and the contribution workflow.

Testing
-------

[](#testing)

```
# Run all tests
./vendor/bin/phpunit packages/cainiao-pickup-bundle/tests

# Run specific test suite
./vendor/bin/phpunit packages/cainiao-pickup-bundle/tests/Service
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Support
-------

[](#support)

For bugs and feature requests, please use the [issue tracker](https://github.com/tourze/cainiao-pickup-bundle/issues).

Credits
-------

[](#credits)

- [Tourze Team](https://github.com/tourze)
- [All Contributors](../../contributors)

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance72

Regular maintenance activity

Popularity0

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity25

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

177d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-cainiao-pickup-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-cainiao-pickup-bundle/health.svg)](https://phpackages.com/packages/tourze-cainiao-pickup-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
