Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Описание

Для упрощения работы с онлайн кассами мы разработали функционал на основе языка PHP.

Представленный ниже блок кода является базовым для создания merchantReceipt. Все что нужно сделать - скопировать код в файл, где нужно получить merhantReceipt и воспользоваться методами класса MerchantHelper.

Code Block
languagephp
themeConfluence
titleБазовые классы
class Item{
    public $price;
    public $quantity;
    public $title;
    public $tax;
    public function __construct($base_price, $quantity, $title, $tax, $discount) {
        $this->price = $base_price - round($base_price * $discount, 2);
        $this->quantity = $quantity;
        $this->tax = $tax;
        $this->title = $title;
    }
}

class MerchantReceiptHelper{
    private $common_price=0;
    private $items = array();
    private $recipient_amount;
    private $discount;
    private $group;
    private $inn;
    private $customer_contact;

    public function __construct($recipient_amount, $inn, $customer_contact, $group=null, $discount_value=0, $order_price=0) {
        $this->recipient_amount = $recipient_amount;
        $this->group = $group;
        $this->inn = $inn;
        $this->customer_contact = $customer_contact;
        $this->setDiscount($discount_value, $order_price);
    }

    public function addItem($base_price, $quantity, $title, $tax) {
        $item = new Item($base_price, $quantity, $title, $tax, $this->discount);
        $this->common_price += $item->price*$item->quantity;
        array_push($this->items, $item);
    }
    
    private function setDiscount($discount_value, $order_price){
        $discount = $discount_value;
        if($this->recipient_amount != $order_price){
            $discount += $order_price - $this->recipient_amount; 
        }
        if ($discount) {
            $discount = $discount / ($order_price+$discount_value);
        }
        $this->discount = $discount;
        if(empty($discount)){
            $this->discount = 0;
        }
    }
    
    public function generateMerchantReceipt(){
        $merchantReceipt = [
            "inn" => $this->inn,
            "group" => $this->group,
            "content" => [
                "type" => "1",
                "positions" => $this->getItems(),
                "customerContact" => $this->customer_contact
            ]
        ];
        return htmlentities(json_encode($merchantReceipt), ENT_QUOTES);
    }
    
    private function getItems(){
        $positions = array();
        $sum_difference = round($this->recipient_amount - $this->common_price, 2);

        foreach ($this->items as $item){
            if (abs($sum_difference) != 0) {
                echo $sum_difference;
                if ($item->quantity == 1){
                    $item->price += $sum_difference;
                } elseif ($item->quantity > 1){
                    $item->quantity--;
                    $positions[] = self::createElementForPositions(1, $item->price+$sum_difference, $item->tax, $item->title);
                } else { 
                    $item->price = $item->price + round($sum_difference/$item->quantity,2);
                }
                $sum_difference = 0;
            }
            $positions[] = $this->createElementForPositions($item->quantity, $item->price, $item->tax, $item->title);
        }

        return $positions;
    }
    
    private function createElementForPositions($quantity, $price, $tax, $title){
        return array(
            'quantity' => $quantity,
            'price' => $price,
            'tax' => $tax,
            'text' => $title
        );
    }
}

Варианты использования

Переменные используемые в демонстрируемых примерах

Название переменнойзначение переменной
$inn
Индивидуальный номер налогоплательщика
$customer_contact
Данные покупателю: email или номер телефона
$group
Группа устройств, можно указать как null, в этом случае будет использоваться группа устройств указанная по умолчанию - Main
$tax
Форма налогообложения целое число от 1 до 6
$products
Массив с товарами в корзине, товары по которым будет создаваться чек
$recipient_amount
Сумма к оплате, которая будет проведена через систему IntellectMoney
$discount_amount
Сумма скидки.
Нужно передать в том случае, если система интернет-магазина не рассчитывает новую стоимость товаров и новую сумму к оплате,
при применении скидок или скидочных купонов.
Если система магазина способна сама рассчитать новую стоимость товаров и сумму заказа - передать 0.
$order_priceСумма заказа к оплате
$merchant_helperПеременная содержит экземпляр класса MerchantHelper

Подготовка
Прежде чем перейти к вариантам использования, создадим переменные с данными для онлайн кассы (ИНН, данные покупателя, группа устройств, форма налогообложения)

Code Block
languagephp
themeConfluence
$inn = '58465584558245';//ИНН
$customer_contact = "mail@mail.ru";//email или телефон покупателя
$group = "Main";//группа устройств
$tax = 1; //Форма налогообложения


Вариант 1. Оплата счета без учета скидок и платежей другими способами оплаты

Начальные условия:

  1. Создан заказ на сумму 200 рублей.
  2. В корзине 3 товара (1 товар на сумму 100 рублей и два товара по 50 рублей) 

Создадим массив с товарами

Code Block
languagephp
themeConfluence
$products = array();// Список товаров в корзине
$products[0] = array(
        "PRICE" => 100.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 1"
        );
$products[1] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 2"
        );
$products[2] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 3"
        );

Создадим переменные с суммой к оплате, размером скидки, полной стоимостью заказа

Code Block
languagephp
themeConfluence
$recipient_amount = 200.00; //Сумма к оплате, которая будет проведена через систему IntellectMoney
$discount_amount = 0;//Сумма скидки, если система интернет-магазина не рассчитывает сумму
$order_price = 200.00; //сумма к оплате заказа


Вариант 2. Оплата счета без учета скидок, но с учетом платежей другими способами оплаты

Начальные условия:

  1. Создан заказ на сумму 200 рублей.
  2. В корзине 3 товара (1 товар на сумму 100 рублей и два товара по 50 рублей) .
  3. Покупатель производит оплату заказа на сумму 180 рублей с внутреннего счета.

Создадим массив с товарами

Code Block
languagephp
themeConfluence
$products = array();// Список товаров в корзине
$products[0] = array(
        "PRICE" => 100.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 1"
        );
$products[1] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 2"
        );
$products[2] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 3"
        );

Создадим переменные с суммой к оплате, размером скидки, полной стоимостью заказа

Code Block
languagephp
themeConfluence
$recipient_amount = 20.00; //Сумма к оплате 200 рублей сумма заказа - 180 рублей оплаченных пользователем = 20 рублей к оплате
$discount_amount = 0;//сумма скидки не оплачиваемая, может быть ноль, например когда есть скидочные купоны
$order_price = 200.00; //сумма к оплате заказа


Вариант 3. Оплата счета с учетом скидок и платежей другими способами оплаты.

Данный варинат подходит тем у кого CMS не способна вернуть цену товара из корзины в заказ перерасчитав стоимость товаров с учетом скидки.

Начальные условия:

  1. Создан заказ на сумму 222 рубля 30 копеек.
  2. В корзине 3 товара (1 товар на сумму 122 рубля 30 копеек и два товара по 50 рублей) .
  3. Покупатель активирует скидочный купон на сумму 22 рубля 23 копейки (10% от суммы заказа)
  4. Теперь товары стоят 120 рублей 7 копеек, 50 рублей и 50 рублей (рассчет процентов гуманитарный для простоты пояснения )
  5. Покупатель производит оплату заказа на сумму 180 рублей с внутреннего счета.
  6. Покупатель должен доплатить 20 рублей 7 копеек через систему IntellectMoney.

Создадим массив с товарами

Code Block
languagephp
themeConfluence
$products = array();// Список товаров в корзине
$products[0] = array(
        "PRICE" => 122.3,
        "QUANTITY" => 1,
        "NAME" => "Товар 1"
        );
$products[1] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 2"
        );
$products[2] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 3"
        );

Создадим переменные с суммой к оплате, размером скидки, полной стоимостью заказа

Code Block
languagephp
themeConfluence
$recipient_amount = 20.07; //Сумма к оплате
$discount_amount = 22.23;//сумма скидки не оплачиваемая, может быть ноль, например когда есть скидочные купоны
$order_price = 222.3; //сумма к оплате заказа

Получение MerchantReceipt

Создаем экземпляр класса MerchantHelper и заполняем конструктор

Code Block
languagephp
themeConfluence
$merchant_helper = new MerchantReceiptHelper($recipient_amount, $inn, $customer_contact, $group, $discount_amount, $order_price);

Добавляем товары из корзины в класс обработчик

Code Block
languagephp
themeConfluence
foreach ($products as $product){
    $merchant_helper->addItem($product["PRICE"], $product['QUANTITY'], $product['NAME'], $tax);
 }

создаем merchantReceipt

Code Block
languagephp
themeConfluence
echo $merchant_helper->generateMerchantReceipt();

Резултаты работы

ВариантРезультат
positionsmerchantReceipt
1
Code Block
languagephp
themeConfluence
Array ( 
	[0] => Array ( 
		[quantity] => 1
		[price] => 100
		[tax] => 1
		[text] => Товар 1 
	)
	[1] => Array (
		[quantity] => 1 
		[price] => 50 
		[tax] => 1 
		[text] => Товар 2 
	)
	[2] => Array ( 
		[quantity] => 1 
		[price] => 50
		[tax] => 1
		[text] => Товар 3
	) 
) 
Code Block
languagephp
themeConfluence
{"inn":"58465584558245","group":"Main","content":
{"type":"1","positions":
[{"quantity":1,"price":100,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 1"},
{"quantity":1,"price":50,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 2"},
{"quantity":1,"price":50,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 3"}],
"customerContact":"mail@mail.ru"}}
2
Code Block
languagephp
themeConfluence
Array ( 
    [0] => Array (
		[quantity] => 1
		[price] => 10
		[tax] => 1
		[text] => Товар 1
	)
    [1] => Array (
		[quantity] => 1
		[price] => 5
		[tax] => 1
		[text] => Товар 2
	)
    [2] => Array (
		[quantity] => 1
		[price] => 5
		[tax] => 1
		[text] => Товар 3
	)
) 
Code Block
languagephp
themeConfluence
{"inn":"58465584558245","group":"Main","content":
{"type":"1","positions":
[{"quantity":1,"price":10,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 1"},
{"quantity":1,"price":5,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 2"},
{"quantity":1,"price":5,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 3"}],
"customerContact":"mail@mail.ru"}}
3
Code Block
languagephp
themeConfluence
Array ( 
	[0] => Array (
		[quantity] => 1
		[price] => 11.05
		[tax] => 1
		[text] => Товар 1
	)
	[1] => Array (
		[quantity] => 1
		[price] => 4.51
		[tax] => 1
		[text] => Товар 2
	)
	[2] => Array (
		[quantity] => 1
		[price] => 4.51
		[tax] => 1
		[text] => Товар 3 )
	) 
Code Block
languagephp
themeConfluence
{"inn":"58465584558245","group":"Main","content":
{"type":"1","positions":
[{"quantity":1,"price":11.05,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 1"},
{"quantity":1,"price":4.51,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 2"},
{"quantity":1,"price":4.51,"tax":1,"text":"\u0422\u043e\u0432\u0430\u0440 3"}],
"customerContact":"mail@mail.ru"}}


Полный блок кода для всех вариантов

Code Block
languagephp
themeConfluence
<?php
class Item{
    public $price;
    public $quantity;
    public $title;
    public $tax;
    public function __construct($base_price, $quantity, $title, $tax, $discount) {
        $this->price = $base_price - round($base_price * $discount, 2);
        $this->quantity = $quantity;
        $this->tax = $tax;
        $this->title = $title;
    }
}

class MerchantReceiptHelper{
    private $common_price=0;
    private $items = array();
    private $recipient_amount;
    private $discount;
    private $group;
    private $inn;
    private $customer_contact;

    public function __construct($recipient_amount, $inn, $customer_contact, $group=null, $discount_value=0, $order_price=0) {
        $this->recipient_amount = $recipient_amount;
        $this->group = $group;
        $this->inn = $inn;
        $this->customer_contact = $customer_contact;
        $this->setDiscount($discount_value, $order_price);
    }

    public function addItem($base_price, $quantity, $title, $tax) {
        $item = new Item($base_price, $quantity, $title, $tax, $this->discount);
        $this->common_price += $item->price*$item->quantity;
        array_push($this->items, $item);
    }
    
    private function setDiscount($discount_value, $order_price){
        $discount = $discount_value;
        if($this->recipient_amount != $order_price){
            $discount += $order_price - $this->recipient_amount; 
        }
        if ($discount) {
            $discount = $discount / ($order_price+$discount_value);
        }
        $this->discount = $discount;
        if(empty($discount)){
            $this->discount = 0;
        }
    }
    
    public function generateMerchantReceipt(){
        $merchantReceipt = [
            "inn" => $this->inn,
            "group" => $this->group,
            "content" => [
                "type" => "1",
                "positions" => $this->getItems(),
                "customerContact" => $this->customer_contact
            ]
        ];
        return htmlentities(json_encode($merchantReceipt), ENT_QUOTES);
    }
    
    private function getItems(){
        $positions = array();
        $sum_difference = round($this->recipient_amount - $this->common_price, 2);

        foreach ($this->items as $item){
            if (abs($sum_difference) != 0) {
                echo $sum_difference;
                if ($item->quantity == 1){
                    $item->price += $sum_difference;
                } elseif ($item->quantity > 1){
                    $item->quantity--;
                    $positions[] = self::createElementForPositions(1, $item->price+$sum_difference, $item->tax, $item->title);
                } else { 
                    $item->price = $item->price + round($sum_difference/$item->quantity,2);
                }
                $sum_difference = 0;
            }
            $positions[] = $this->createElementForPositions($item->quantity, $item->price, $item->tax, $item->title);
        }

        return $positions;
    }
    
    private function createElementForPositions($quantity, $price, $tax, $title){
        return array(
            'quantity' => $quantity,
            'price' => $price,
            'tax' => $tax,
            'text' => $title
        );
    }
}

$inn = '58465584558245';//ИНН
$customer_contact = "mail@mail.ru";//email или телефон покупателя
$group = "Main";//группа устройств
$tax = 1; //Форма налогооблажения


$products = array();// Список товаров в корзине
$products[0] = array(
        "PRICE" => 100.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 1"
        );
$products[1] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 2"
        );
$products[2] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 3"
        );
$recipient_amount = 200.00; //Сумма к оплате
$discount_amount = 0;//сумма скидки не оплачиваемая, может быть ноль, например когда есть скидочные купоны
$order_price = 200.00; //сумма к оплате заказа
$merchant_helper = new MerchantReceiptHelper($recipient_amount, $inn, $customer_contact, $group, $discount_amount, $order_price);
foreach ($products as $product){
    $merchant_helper->addItem($product["PRICE"], $product['QUANTITY'], $product['NAME'], $tax);
 }
echo $merchant_helper->generateMerchantReceipt();


$products2 = array();// Список товаров в корзине
$products2[0] = array(
        "PRICE" => 100.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 1"
        );
$products2[1] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 2"
        );
$products2[2] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 3"
        );
$recipient_amount = 20.00; //Сумма к оплате
$discount_value = 0;//сумма скидки не оплачиваемая, может быть ноль, например когда есть скидочные купоны
$order_price = 200.00; //сумма к оплате заказа
$merchant_helper2 = new MerchantReceiptHelper($recipient_amount, $inn, $customer_contact, $group, $discount_value, $order_price);
foreach ($products2 as $product){
    $merchant_helper2->addItem($product["PRICE"], $product['QUANTITY'], $product['NAME'], $tax);
 }
echo $merchant_helper2->generateMerchantReceipt();


$products3 = array();// Список товаров в корзине
$products3[0] = array(
        "PRICE" => 122.3,
        "QUANTITY" => 1,
        "NAME" => "Товар 1"
        );
$products3[1] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 2"
        );
$products3[2] = array(
        "PRICE" => 50.00,
        "QUANTITY" => 1,
        "NAME" => "Товар 3"
        );
$recipient_amount = 20.07; //Сумма к оплате
$discount_value = 22.23;//сумма скидки не оплачиваемая, может быть ноль, например когда есть скидочные купоны
$order_price = 222.3; //сумма к оплате заказа
$merchant_helper3 = new MerchantReceiptHelper($recipient_amount, $inn, $customer_contact, $group, $discount_amount, $order_price);
foreach ($products3 as $product){
    $merchant_helper3->addItem($product["PRICE"], $product['QUANTITY'], $product['NAME'], $tax);
 }
 echo $merchant_helper3->generateMerchantReceipt();

Table of Contents