Skip to content
This repository has been archived by the owner on Apr 25, 2023. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jhaoda committed Dec 23, 2017
0 parents commit 7d83dfb
Show file tree
Hide file tree
Showing 53 changed files with 3,854 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/tests export-ignore
/.styleci.yml export-ignore
/.travis.yml export-ignore
/.gitattributes export-ignore
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea/
vendor/
composer.lock
8 changes: 8 additions & 0 deletions .scrutinizer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
build:
environment:
php:
version: 7.1

filter:
excluded_paths:
- examples
23 changes: 23 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# The MIT License (MIT)

Copyright © appwilio <appwilio.com>
Copyright © JhaoDa <jhaoda@gmail.com>
Copyright © greabock <greabock17@gmail.com>

> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# SDK для СДЭК

[![Total Downloads](https://poser.pugx.org/appwilio/cdek-sdk/downloads)](https://packagist.org/packages/appwilio/cdek-sdk)
[![Latest Stable Version](https://poser.pugx.org/appwilio/cdek-sdk/version)](https://packagist.org/packages/appwilio/cdek-sdk)
[![License](https://poser.pugx.org/appwilio/cdek-sdk/license)](https://packagist.org/packages/appwilio/cdek-sdk)

### Это будет самое полное SDK для cdek.ru

Возможности:

- [x] получение списка пунктов выдачи заказов (ПВЗ) с фильтрацией
- [x] расчёт стоимости доставки
- [x] управление заказами
- [x] формирование новых заказов
- [ ] генерация квитанции в PDF
- [x] удаление заказов
- [x] получение информации по заказам (отчет «Информация по заказам»)
- [x] трекинг заказов (отчет «Статусы заказов»)
- [ ] прозвон получателя
- [ ] вызов курьера

> Работа с API возможна только при наличии договора с СДЭК.
## Установка

> Минимальные требования — PHP 7.1+.
```bash
composer require appwilio/cdek-sdk
```

## Использование


## Авторы

- [greabock](https://github.com/greabock)
- [JhaoDa](https://github.com/jhaoda)

## Лиценция

Данный SDK распространяется под лицензией [MIT](http://opensource.org/licenses/MIT).
41 changes: 41 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "appwilio/cdek-sdk",
"keywords": ["CDEK", "sdk", "delivery"],
"homepage": "https://github.com/appwilio/cdek-sdk",
"description": "CDEK API SDK (cdek.ru)",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Roman Sokharev",
"email": "greabock17@gmail.com",
"role": "Creator"
},
{
"name": "JhaoDa",
"email": "jhaoda@gmail.com",
"role": "Developer"
}
],
"support": {
"email": "jhaoda@gmail.com",
"issues": "https://github.com/appwilio/cdek-sdk/issues"
},
"require": {
"php": ">=7.1",
"jms/serializer": "^1.8",
"guzzlehttp/guzzle": "^6.3"
},
"require-dev": {
"phpunit/phpunit": "^6.3",
"illuminate/support": "5.1.* || 5.2.* || 5.3.* || 5.4.* || 5.5.*"
},
"autoload": {
"psr-4": {
"Appwilio\\CdekSDK\\": "src/"
}
},
"scripts": {
"test": "vendor/bin/phpunit"
}
}
22 changes: 22 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Test Suite">
<directory suffix="TestCase.php">tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
166 changes: 166 additions & 0 deletions src/CdekClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
<?php

/**
* This file is part of Cdek SDK package.
*
* © Appwilio (http://appwilio.com), greabock (https://github.com/greabock), JhaoDa (https://github.com/jhaoda)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Appwilio\CdekSDK;

use JMS\Serializer\Serializer;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\Handler\HandlerRegistry;
use GuzzleHttp\Client as GuzzleClient;
use Appwilio\CdekSDK\Requests\CdekRequest;
use Appwilio\CdekSDK\Requests\DeleteRequest;
use Appwilio\CdekSDK\Requests\CdekXmlRequest;
use Appwilio\CdekSDK\Requests\PvzListRequest;
use Appwilio\CdekSDK\Requests\CdekJsonRequest;
use Appwilio\CdekSDK\Requests\DeliveryRequest;
use Appwilio\CdekSDK\Requests\CdekParamRequest;
use Appwilio\CdekSDK\Requests\InfoReportRequest;
use Appwilio\CdekSDK\Requests\CalculationRequest;
use Appwilio\CdekSDK\Responses\CalculationResponse;
use Appwilio\CdekSDK\Responses\DeleteResponse;
use Appwilio\CdekSDK\Responses\PvzListResponse;
use Appwilio\CdekSDK\Responses\DeliveryResponse;
use Appwilio\CdekSDK\Responses\InfoReportResponse;
use Appwilio\CdekSDK\Requests\StatusReportRequest;
use Appwilio\CdekSDK\Responses\StatusReportResponse;
use Appwilio\CdekSDK\Serialization\NullableDateTimeHandler;

class CdekClient
{
protected $maps = [
'xml' => [
DeleteRequest::class => DeleteResponse::class,
PvzListRequest::class => PvzListResponse::class,
DeliveryRequest::class => DeliveryResponse::class,
InfoReportRequest::class => InfoReportResponse::class,
StatusReportRequest::class => StatusReportResponse::class,
],
'json' => [
CalculationRequest::class => CalculationResponse::class,
],
];

/** @var GuzzleClient */
private $http;

/** @var string */
private $account;

/** @var string */
private $password;

/** @var Serializer */
private $serializer;

public function __construct(string $account, string $password)
{
$this->account = $account;
$this->password = $password;

$this->http = new GuzzleClient();

$this->serializer = SerializerBuilder::create()->configureHandlers(function (HandlerRegistry $registry) {
$registry->registerSubscribingHandler(new NullableDateTimeHandler());
})->build();
}

protected function sendRequest(CdekRequest $request): string
{
$this->initRequest($request);

$response = $this->http->request(
$request->getMethod(),
$request->getAddress(),
$this->extractOptions($request)
);

return $response->getBody()->getContents();
}

public function sendPvzListRequest(PvzListRequest $request): PvzListResponse
{
return $this->process($request);
}

public function sendStatusReportRequest(StatusReportRequest $request): StatusReportResponse
{
return $this->process($request);
}

public function sendCalculationRequest(CalculationRequest $request): CalculationResponse
{
return $this->process($request);
}

private function extractOptions($request): array
{
if ($request instanceof CdekParamRequest) {
return ['form_params' => $request->getParams()];
}

if ($request instanceof CdekXmlRequest) {
return ['form_params' => ['xml_request' => $this->serializer->serialize($request, 'xml')]];
}

if ($request instanceof CdekJsonRequest) {
return [
'body' => json_encode($request->getBody()),
'headers' => ['Content-Type' => 'application/json'],
];
}

return [];
}

public function sendDeliveryRequest(DeliveryRequest $request): DeliveryResponse
{
return $this->process($request);
}

public function sendInfoReportRequest(InfoReportRequest $request): InfoReportResponse
{
return $this->process($request);
}

public function sendDeleteRequest($request): DeleteResponse
{
return $this->process($request);
}

public function process($request)
{
$class = get_class($request);

$response = $this->sendRequest($request);

foreach ($this->maps as $dataType => $map) {
if (array_key_exists($class, $map)) {
return $this->serializer->deserialize($response, $map[$class], $dataType);
}
}

throw new \Exception("Class [$class] not mapped.");
}

private function initRequest(CdekRequest $request): void
{
$date = new \DateTimeImmutable();

$request->date($date)->credentials($this->account, $this->getSecure($date));
}

private function getSecure(\DateTimeInterface $date): string
{
return md5($date->format('Y-m-d')."&{$this->password}");
}
}
56 changes: 56 additions & 0 deletions src/Common/AdditionalService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/**
* This file is part of Cdek SDK package.
*
* © Appwilio (http://appwilio.com), greabock (https://github.com/greabock), JhaoDa (https://github.com/jhaoda)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Appwilio\CdekSDK\Common;

use JMS\Serializer\Annotation as JMS;

class AdditionalService
{
use Fillable;

/**
* @JMS\XmlAttribute
* @JMS\SerializedName("ServiceCode")
* @JMS\Type("int")
*
* @var int
*/
protected $ServiceCode;

/**
* @JMS\XmlAttribute
* @JMS\SerializedName("Sum")
* @JMS\Type("float")
*
* @var float
*/
protected $Sum;

public function getServiceCode(): int
{
return $this->ServiceCode;
}

public function getSum(): float
{
return $this->Sum;
}

public static function create($code): self
{
return new static([
'ServiceCode' => $code,
]);
}
}
Loading

0 comments on commit 7d83dfb

Please sign in to comment.