Integration API of the CDEK delivery service

This document describes the implementation of information exchange between Falcon Space and the CDEK delivery service.

General input data:

  • Departure city (Flag - from the door);
  • City of receipt (Flag-up to the door);
  • Length, cm;
  • Width, cm;
  • Height, cm;
  • Weight, g.

 General algorithm:

  1. Forming the request text with parameters
  2. Sending a request
  3. Getting a response to a request
  4. response Parsing, getting data.

Useful CDEK services

Services -https://cdek.ru/services

Rates for individuals -https://cdek.ru/individuals/tariffs

Calculation of the delivery cost -https://cdek.ru/calculate

Integration -https://cdek.ru/integration

Integration-Frequently asked questions -https://cdek.ru/integration#questions

Option with authorization

What do I need to do to integrate?

Step 1: Integration is only possible if there is a contract (an online store or a contract for the provision of courier services) and if it has the status "signed" In our systems.

  

Option without authorization

Can I use the fare calculator API without a contract?

Yes, the account parameters (Account and Secure) are optional, but you will not be able to calculate rates for online stores and personal discounts will not be taken into account.

Technical parameters

Interaction with the service takes place online using the standard HTTPS Protocol and theJSONformat.

Messaging must be encoded inUTF-8.

  

CALCULATOR WITHOUT AUTHORIZATION-VERSION v1.5 API integration

https://confluence.cdek.ru/pages/viewpage.action?pageId=15616129#id-Протоколобменаданными(v1.5)-4.14CalculatorКалькулятор

The exchange procedure is implemented under the item - 4.14.1. Calculation of the cost for tariffs with priority

CDEK - rates – PROCEDURE [api_ruCDEKTariff_request]

To get the cost and delivery time, you must send thejsonobject to the CDEK server.

When passing a json object, specify the appropriate Content-Type in the header.

  • URL: http://api.cdek.ru/calculator/calculate_price_by_json.php
  • Content-Type: application/json
  • request Method: POST
  • output Format: JSON

Request input data – procedure parameters PROCEDURE [api_ruCDEKTariff_request]

Variable

Type

Default

Describtion

Note

1

@dateExecute2

nvarchar(10)

''

The planned date of sending the order in the format “YYYY-MM-DD

2

@senderCityId

int

36528

The area code of the sender from the base of CDEK

 

3

@receiverCityId       

int

288  

The area code of the reciever from the base of CDEK

 

4

@tariffId

int

1

Selected rate code

 

 

 goods    Overall characteristics of the package

5

@weight

int

300

Weight (gram)

RECALCULATION! Package weight (in kilograms)

6

@length

int

5

Packing length (in centimeters)

 

7

@width

int

20

Package width (in centimeters)

 

 

@height

int

10

Package height (in centimeters)

 

Appendix 1. Services (rates) and modes of delivery CDEK

Rates for regular delivery 

Код

Tariff name

Mode of delivery

Weight restriction

Service

Describtion

1

Express Lite door-to-door

door-to-door (D-D)

up to 30 kg

Express

Classic Express delivery of documents and cargo up to 30 kg in Russia.

3

Super Express up to 18

door-to-door (D-D)

up to 30 kg

Urgent delivery

Urgent delivery of documents and cargo «from hand to hand » across Russia by a certain hour.

5

Economical Express warehouse-warehouse

warehouse-warehouse (W-W)

 

Economical delivery

Low-cost delivery of goods across Russia by railway and motor transport (delivery of goods with an increase in terms).

  

recipient cities from the CDEk base

  • Id - city ID based on the CDEK database (CityCode)
  • FullName - Full name of the city/locality including regional affiliation
  • CityName - city Name does not include regional affiliation

ID

FullName

CityName

OblName

36528

5663234234, Moscow

Moscow

438

Rostov-on-don

Rostov-on-don

Rostov region

402

Arkhangelsk

Arkhangelsk

Arkhangelsk region

288

Vladivostok

Vladivostok

Primorskiy region

  

The example of request text - request.

URL: http://api.cdek.ru/calculator/calculate_price_by_json.php  

JSON - BODY  

{
"version":"1.0",
"dateExecute":"2020-06-03",
"senderCityId":"36528",
"receiverCityId":"288",
"tariffId":"1",
"goods":
[
                {
                "weight":"0.300",
                "length":"5",
                "width":"20",
                "height":"10"
                }
]
}

The example of the response text - response.

{
    "result": {
        "price": "1370",
        "deliveryPeriodMin": 7,
        "deliveryPeriodMax": 10,
        "deliveryDateMin": "2020-06-10",
        "deliveryDateMax": "2020-06-13",
        "tariffId": "1",
        "priceByCurrency": 1370,
        "currency": "RUB"
    }
}

CREATE PROCEDURE [dbo].[api_ruCDEKTariff_request]
	@parameters ExtendedDictionaryParameter READONLY,  -- incoming parameters for internal processing (use Key, Value2)
	@username nvarchar(32)  -- curent user.
    --
    -- INCOMING PARAMETER
, @dateExecute2 nvarchar(10) = ''		--'2020-07-19'	-- Date of dispatch of the order, which is planned in the format “YYYY-MM-DD”
, @senderCityId          int = 36528 -- The area code of the sender from the base of CDEK integer
, @receiverCityId        int = 288   -- The area code of the reciever from the base of CDEK  integer
, @tariffId              int = 1     -- Code of the selected fare
-- goods	Overall characteristics of the package
, @weight                int = 300   -- Weight (gram )	– RECALCULATION! Package weight (in kilograms) numeric(20,3)
, @length                int = 5		-- Packing length (in centimeters)	integer
, @width                 int = 20		-- Package width (in centimeters)	integer
, @height                int = 10		-- Package high (in centimeters)	integer
AS
BEGIN


-- Weight (gram )	– RECALCULATION! Package weight (in kilograms) numeric(20,3) -
-- 1 Gram (gr) = 0.001 kilogram (кг)
DECLARE @weightKG numeric(20,3)
SET     @weightKG = @weight * 0.001


-- Planned order delivery date in format “YYYY-MM-DD”
-- 23 	ISO8601 	YYYY-MM-DD
IF  LEN(  ISNULL ( @dateExecute2   , '' ) )=0
SET @dateExecute2  =  CONVERT ( nvarchar(10) , GETDATE() , 23 )
-- exec as_print @str = @dateExecute2

DECLARE @apiUrl 		nvarchar(max) = '' 		-- Final line to send -- @apiStr -- IN FACT IT IS Url
DECLARE @apiCommomStr 	nvarchar(max) = '' 	    -- Common part for all queries
DECLARE @jsonRequest 	nvarchar(max) = '' 	    -- text of the json-object

-- you must send the son-object to the CDEK server.
-- When passing a json-object, specify the appropriate Content-Type in the header.
-- URL :	http://api.cdek.ru/calculator/calculate_price_by_json.php
-- Type:	Content-Type: application/json	--  specify THIS SHOULD BE IN HEADER

SET     @apiCommomStr = N'http://api.cdek.ru/calculator/calculate_price_by_json.php' --

SET     @jsonRequest  = N'{' + CHAR(10)
                      + N'"version":"1.0",'  + CHAR(10)
                      + N'"dateExecute":"'   + @dateExecute2 +'",'+ CHAR(10)
                      + N'"senderCityId":"'  + TRY_CAST ( @senderCityId   AS nvarchar )  +'",'+  CHAR(10)
                      + N'"receiverCityId":"'+ TRY_CAST ( @receiverCityId AS nvarchar )  +'",'+  CHAR(10)
                      + N'"tariffId":"'      + TRY_CAST ( @tariffId       AS nvarchar )  +'",'+  CHAR(10)
                      + N'"goods":'			+ CHAR(10)
                      + N'['				+ CHAR(10)
                      + CHAR(9)+ N'{'				+ CHAR(10) -- табуляции CHAR(9)
                      + CHAR(9)+ N'"weight":"'  + TRY_CAST ( @weightKG AS nvarchar )  +'",'+  CHAR(10)
                      + CHAR(9)+ N'"length":"'  + TRY_CAST ( @length   AS nvarchar )  +'",'+  CHAR(10)
                      + CHAR(9)+ N'"width":"'   + TRY_CAST ( @width    AS nvarchar )  +'",'+  CHAR(10)
                      + CHAR(9)+ N'"height":"'  + TRY_CAST ( @height   AS nvarchar )  +'" '+  CHAR(10) -- Last line without a comma
                      + CHAR(9)+ N'}' + CHAR(10)
                      + N']' + CHAR(10)
                      + N'}'

-- PRINT @jsonRequest

SET  @apiUrl  =  @apiCommomStr -- + @jsonRequest

    -- DEBUG
    -- exec as_print @str='api_ruCDEKTariff_request'
	insert into as_trace ( header, text, username, code , created )   values( '@apiUrl Url', @apiUrl , @username, 'api_ruCDEKTariff_request' , GETDATE() )
	insert into as_trace ( header, text, username, code , created )   values( '@jsonRequest', @jsonRequest , @username, 'api_ruCDEKTariff_request' , GETDATE() )


	-- SELECT 1  Msg, Result, Url (address where the parcel will go)
	select '' Msg, 1 Result
          , @apiUrl Url
          , 'application/json' ContentType -- a clear indication for HEADER

	-- SELECT 2 PARAMETERS - parameters that will be passed to an external source
	 select 'id' name
           , @jsonRequest value -- это body
           , 'json' [type] -- form (in the form passed), header (в http headers), get send requests directly to URL
   -- How to send an outgoing POST request with a JSON body?
   -- To do this, specify the POST request type and pass only 1 parameter with type=json in the format of a string with JSON.
END

SDEK-rates - PROCEDURE [api_ruCDEKTariff_response]

the query Result can be either a message with information or an error message.

 A list of possible error messages.

  •  'Error! The @response string is not JSON!' (Checking the response with the ISJSON () operator)
  •  'Error! The @response query returned an error! '… @errorText.

If no errors are found in the response, the following data is selected from the response:

  •  deliveryPeriodMin             Minimum delivery time in days       integer
  •  deliveryPeriodMax            Maximum delivery time in days
  • deliveryDateMin                Minimum delivery date, in format 'YYYY-MM-DD'
  • deliveryDateMax               Maximal delivery date, in format 'YYYY-MM-DD'
  • tariffId                             Code of the fare used for calculating the delivery amount
  • priceByCurrency               Price in the settlement currency.
  • currency                          Currency of the online store

 

The example of text– result: "Delivery time: from 7 to 10 days. Dates: from 2020-06-10 to 2020-06-13. Amount: 1370 RUB."

PROCEDURE [dbo].[api_ruCDEKTariff_response]

CREATE PROCEDURE [dbo].[api_ruCDEKTariff_response]
	@response nvarchar(max),
	@parameters ExtendedDictionaryParameter READONLY,  -- incoming parameters for internal processing (use Key, Value2 - the same as on request)

	@username nvarchar(32)
AS
BEGIN
	-- DEBUG
    -- exec as_print @str='api_ruPostDelivery_response'
	insert into as_trace (text, username, code , created  ) values( @response, @username, 'api_ruCDEKTariff_response' , GETDATE() )

    DECLARE @json1 NVARCHAR(MAX)  = N''
	SET @json1 = @response

    -- To check whether the JSON format is correct, there is an ISJSON function that returns 1 if it is JSON, 0 — if it is not, and NULL if NULL was passed
    DECLARE @presentJSON bit = 0
    SELECT @presentJSON = ISNULL( ISJSON( @json1 ) , 0 )

    IF @presentJSON <> 1
    BEGIN
        SELECT 'Error! Line @response не является JSON!' Msg, 0 Result, @response Response
        RETURN
    END

	-- Handling an error in the response
    DECLARE @presentError bit = 0, @errorText NVARCHAR(MAX), @errorCode NVARCHAR(MAX), @errorMsg NVARCHAR(MAX)

	DECLARE @deliveryDateMin NVARCHAR(MAX)
          , @deliveryDateMax NVARCHAR(MAX)
          , @tariffId		 NVARCHAR(MAX)
          , @priceByCurrency NVARCHAR(MAX)
          , @currency		 NVARCHAR(MAX)
           --
    DECLARE @deliveryDaysMin NVARCHAR(MAX)
          , @deliveryDaysMax NVARCHAR(MAX)

    SELECT @presentError = IIF( JSON_QUERY( @json1, '$.error[0]') IS NULL  , 0 , 1 )  -- Checking the array JSON_QUERY  '$.error[0]'
           , @errorCode    = JSON_VALUE( @json1, '$.error[0].code')
           , @errorMsg     = JSON_VALUE( @json1, '$.error[0].text')
           -- Данные
           , @deliveryDaysMin = JSON_VALUE( @json1, '$.result.deliveryPeriodMin')
	 	   , @deliveryDaysMax = JSON_VALUE( @json1, '$.result.deliveryPeriodMax')

           , @deliveryDateMin = JSON_VALUE( @json1, '$.result.deliveryDateMin')
	 	   , @deliveryDateMax = JSON_VALUE( @json1, '$.result.deliveryDateMax')

           , @tariffId =		JSON_VALUE( @json1, '$.result.tariffId')
	 	   , @priceByCurrency = JSON_VALUE( @json1, '$.result.priceByCurrency')
	 	   , @currency =		JSON_VALUE( @json1, '$.result.currency')

      IF @presentError = 1
      BEGIN
		  SET @errorText = 'code:'+ ISNULL( @errorCode, '' ) +' text:'+ ISNULL( @errorMsg, '' )
          SELECT 'Error! Request @response вернул ошибку! '+ ISNULL( @errorText, '' ) Msg, 0 Result, @response Response
          RETURN
      END

    DECLARE @deliveryText NVARCHAR(MAX)
    -- Delivery time: 2 to 4 days.
	SET @deliveryText = 'Delivery time: from ' + ISNULL( @deliveryDaysMin, '' )+' before '+ISNULL( @deliveryDaysMax, '' )+' days. '
					   +'Dates: from ' + ISNULL( @deliveryDateMin, '' )+' while '+ISNULL( @deliveryDateMax, '' )+'. '
					   +'The amount: '  + ISNULL( @priceByCurrency, '' )+' '   +ISNULL( @currency, '' )+'.'
	-- SELECT 1
	select @deliveryText as Msg, 1 Result, @response Response

	-- SELECT 2 External action

END

Falcon Space is a functional web development platform on a narrow stack MS SQL/Bootstrap. Falcon Space Gettting started
{sp-shortDemostandLinks}

SQL-tool for creating personal accounts on the site

The essence of the approach and the history of the creation of Falcon Space
Web platform for creating personal accounts

Falcon Space Platform

This is a reduction in the cost of ownership

at the expense of fewer people to support

This is a quick change

while using the program

This is a modern interface

full adaptation for mobile devices

MS SQL web applications. Affiliate program for developers and web studios

You can develop on your own or collaborate with us on Falcon Space web development using only SQL and HTML.
See examples with SQL code
Platform documentation
Working on MS SQL Server
Note