Услуги профессионального Битрикс-программиста

Форма обратной связи, купить в 1 клик


надоело искать исходники с разных проектов, поэтому решила запостить тут.
Внизу архив.
компонент не универсален, надо допиливать минимально под свой проект.
В нем есть:
component.php
<?if(isset($_REQUEST["ajax_call"]) && $_REQUEST["ajax_call"]=="Y"){
   require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
   if(check_bitrix_sessid()){

      if(empty($_POST["phone"])){   
         $result = "Введите телефон";
         $GLOBALS['APPLICATION']->RestartBuffer();
         echo json_encode($result);
      }
      else{
         $_POST["name"] = $_POST["name"] ?? "Не заполнено";
         $_POST["form_name"] = $_POST["form_name"] ?? "Свяжитесь с нами";
         $_POST["text"] = $_POST["text"] ?? "";
         $arFields = Array(
            "NAME" => $_POST["phone"]." ".$_POST["form_name"],
            "PREVIEW_TEXT" =>  $_POST["name"],            
            "DETAIL_TEXT" =>  $_POST["text"],
            "IBLOCK_ID" => 28
         );
         $text = $_POST["phone"]." Имя: ".$_POST["name"]."\n".$_POST["text"]; 
         CModule::IncludeModule('iblock');
         
         if(!empty($_POST["ids"]) && is_array($_POST["ids"])){
            $text .= "\nТовары в заказе:\n";
            $arProps = [
               500 => []
            ];
            
            $arFilter = Array(
              "IBLOCK_ID"=>9, 
               "ACTIVE"=>"Y",
               "ID" => $_POST["ids"]
            );
            $arSelect = Array("ID", "NAME", "IBLOCK_ID","PROPERTY_CML2_ARTICLE");
            $res = CIBlockElement::GetList(Array("sort"=>"asc"), $arFilter, false, Array("nPageSize"=>100,"iNumPage"=>1), $arSelect);

            while($arItem = $res->Fetch()){
                $arProps[500][] = $arItem["ID"];
                $text .= $arItem["NAME"]." арт.".$arItem["PROPERTY_CML2_ARTICLE_VALUE"];
            }
            $arFilter ["IBLOCK_ID"] = 10;
            $res = CIBlockElement::GetList(Array("sort"=>"asc"), $arFilter, false, Array("nPageSize"=>100,"iNumPage"=>1), $arSelect);
            while($arItem = $res->Fetch()){
                $arProps[500][] = $arItem["ID"];
                $text .= $arItem["NAME"]." арт.".$arItem["PROPERTY_CML2_ARTICLE_VALUE"];
            }
            $arFields["PROPERTY_VALUES"] = $arProps;
         }

         
         
         $el = new CIBlockElement;
         if($elemId = $el->Add($arFields)){
            
         }
         else{
              AddMessage2Log("Ошибка при добавлении: ".$el->LAST_ERROR);
            AddMessage2Log($arFields);
         }
         $subject = 'Заполнена форма "'.$_POST["form_name"].'"';         
         
         $to = COption::GetOptionString("sale", "order_email", "nikavero13@mail.ru");         
         $text = wordwrap($text, 70, "\r\n");
         mail($to, $subject, $text);
         $result = "ok";
         $GLOBALS['APPLICATION']->RestartBuffer();
         echo json_encode($result);
      }
   }
   require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");
   die();
}
else{
   if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
   global $USER;
   if($USER->IsAuthorized()){
      $rsUser = CUser::GetByID($USER->GetID());
      $arResult["USER"] = $rsUser->Fetch();
      $arResult["USER"]["FULL_NAME"] = $USER->GetFullName();
      $arResult["USER"]["PHONE_NUMBER"] = $arResult["USER"]["PERSONAL_PHONE"];
   }

   $arParams["PREFIX"] = empty($arParams["PREFIX"]) ? "" :"-".$arParams["PREFIX"];
   $arParams["UNIQ_ID"] = empty($arParams["PREFIX"]) ? uniqid() : uniqid("-".$arParams["PREFIX"]);
   $arParams["HEADER"] = $arParams["HEADER"] ?? "Свяжитесь с нами";
   $arParams["TEXT"] = $arParams["TEXT"] ?? "Оставьте заявку, и мы свяжемся с вами в ближайшее время";
   $arParams["SHOW_TEXT"] = (!empty($arParams["SHOW_TEXT"]) && ($arParams["SHOW_TEXT"]=="Y")) ? "Y" : "N";
   $this->IncludeComponentTemplate();

}
?>
шаблон для стандартной формы
.default
<?if(!defined("B_PROLOG_INCLUDED")||B_PROLOG_INCLUDED!==true)die();
CJSCore::Init(array('ajax'));
?>
<div class="popup-overlay" id="phone-panel<?=$arParams["UNIQ_ID"]?>">
     <div class="popup-wrap">
        <button class="button-close popup-close" type="button"><i class="icon-close"></i></button>
        <div class="popup-header">
            <div class="figure"><i class="icon-message"></i></div>
            <span id="callback<?=$arParams["UNIQ_ID"]?>-result-good"><?=$arParams["HEADER"]?></span>
            <p class="subtext"><?=$arParams["TEXT"]?></p>
            <p class="subtext" id="callback<?=$arParams["UNIQ_ID"]?>-error"></p>
        </div>
        
        <form class="auth-form" action="/" id="callback<?=$arParams["UNIQ_ID"]?>-form">
            <?=bitrix_sessid_post()?>
            <input class="field-dark" type="text" placeholder="Представьтесь" id="callback<?=$arParams["UNIQ_ID"]?>-name" value="<?=$arResult["USER"]["FULL_NAME"] ?? ""?>">
            <input class="field-dark" type="phone" placeholder="Ваш телефон" id="callback<?=$arParams["UNIQ_ID"]?>-phone" value="<?=$arResult["USER"]["PHONE_NUMBER"] ?? ""?>">
            <?if($arParams["SHOW_TEXT"]=="Y"):?>
                <textarea class="field-dark" placeholder="Комментарий" id="callback<?=$arParams["UNIQ_ID"]?>-text"></textarea>
            <?endif;?>
            <button class="button-basic flex-center w-100" type="submit" id="callback<?=$arParams["UNIQ_ID"]?>-send">Отправить</button>
        </form>
    </div>
</div>
<script>
    BX.ready(function(){
       
            $(".callback-button<?=$arParams["PREFIX"]?>").on("click", function(e) {       
                e.preventDefault(); 
                $("#phone-panel<?=$arParams["UNIQ_ID"]?>").addClass("active-modal");
            });
           $("#callback<?=$arParams["UNIQ_ID"]?>-send").click(function(e){
                e.preventDefault(); 
                $('#callback<?=$arParams["UNIQ_ID"]?>-error').html("");           
                let phone = $("#callback<?=$arParams["UNIQ_ID"]?>-phone").val();            
                if((phone == "") || (phone.indexOf('_')>0)){
                    $('#callback<?=$arParams["UNIQ_ID"]?>-error').html("Проверьте корректность телефона");                
                }
                else{
                    let postData = {
                        sessid: BX.bitrix_sessid(),
                        site_id: BX.message('SITE_ID'),
                        phone: phone,
                        name: $('#callback<?=$arParams["UNIQ_ID"]?>-name').val(),
                        ajax_call: 'Y',
                        form_name: "<?=$arParams["HEADER"]?>",
                        <?if($arParams["SHOW_TEXT"]=="Y"):?>
                        text: $('#callback<?=$arParams["UNIQ_ID"]?>-text').val(),
                        <?endif;?>
                    };               
                    BX.ajax({
                       url: '<?=$component->GetPath()?>/component.php',
                       method: 'POST',
                       data: postData,
                       dataType: 'json',                   
                       onsuccess: function(data){                        
                           if(data == "ok"){
                                $('#callback<?=$arParams["UNIQ_ID"]?>-result-good').html("Спасибо! Мы с Вами свяжемся!");
                                $('#callback<?=$arParams["UNIQ_ID"]?>-form').hide();
                                $('#phone-panel<?=$arParams["UNIQ_ID"]?> .subtext').hide();
                            }
                            else{
                                $('#callback<?=$arParams["UNIQ_ID"]?>-error').html(data);

                                
                            }
                       },
                       onfailure: function(error){
                          console.log(error);
                       } 
                    });
                    

                }
            });
        
    });   
</script>

купить в 1 клик в товаре (сделано как форма обратной связи)
<?if(!defined("B_PROLOG_INCLUDED")||B_PROLOG_INCLUDED!==true)die();
CJSCore::Init(array('ajax'));
?>
<div class="popup-overlay" id="phone-panel<?=$arParams["UNIQ_ID"]?>">
     <div class="popup-wrap">
        <button class="button-close popup-close" type="button"><i class="icon-close"></i></button>
        <div class="popup-header">
            <div class="figure"><i class="icon-message"></i></div>
            <span id="callback<?=$arParams["UNIQ_ID"]?>-result-good"><?=$arParams["HEADER"]?></span>
            <p class="subtext"><?=$arParams["TEXT"]?></p>
            <p class="subtext" id="callback<?=$arParams["UNIQ_ID"]?>-error"></p>
        </div>
        
        <form class="auth-form" action="/" id="callback<?=$arParams["UNIQ_ID"]?>-form">
            <?=bitrix_sessid_post()?>
            <input class="field-dark" type="text" placeholder="Представьтесь" id="callback<?=$arParams["UNIQ_ID"]?>-name" value="<?=$arResult["USER"]["FULL_NAME"] ?? ""?>">
            <input class="field-dark" type="phone" placeholder="Ваш телефон" id="callback<?=$arParams["UNIQ_ID"]?>-phone" value="<?=$arResult["USER"]["PHONE_NUMBER"] ?? ""?>">
            <?if($arParams["SHOW_TEXT"]=="Y"):?>
                <textarea class="field-dark" placeholder="Комментарий" id="callback<?=$arParams["UNIQ_ID"]?>-text"></textarea>
            <?endif;?>
            <button class="button-basic flex-center w-100" type="submit" id="callback<?=$arParams["UNIQ_ID"]?>-send">Отправить</button>
        </form>
    </div>
</div>
<script>
    BX.ready(function(){
       
            $(".callback-button<?=$arParams["PREFIX"]?>").on("click", function(e) {       
                e.preventDefault();
                $("#callback<?=$arParams["UNIQ_ID"]?>-send").data("id",$(e.target).data('id'));
                $("#phone-panel<?=$arParams["UNIQ_ID"]?>").addClass("active-modal");
            });
           $("#callback<?=$arParams["UNIQ_ID"]?>-send").click(function(e){
                e.preventDefault(); 
               
                $('#callback<?=$arParams["UNIQ_ID"]?>-error').html("");           
                let phone = $("#callback<?=$arParams["UNIQ_ID"]?>-phone").val();            
                if((phone == "") || (phone.indexOf('_')>0)){
                    $('#callback<?=$arParams["UNIQ_ID"]?>-error').html("Проверьте корректность телефона");                
                }
                else{
                    let postData = {
                        sessid: BX.bitrix_sessid(),
                        site_id: BX.message('SITE_ID'),
                        phone: phone,
                        name: $('#callback<?=$arParams["UNIQ_ID"]?>-name').val(),
                        ajax_call: 'Y',
                        form_name: "<?=$arParams["HEADER"]?>",
                        text: $('#callback<?=$arParams["UNIQ_ID"]?>-text').val(),
                        ids: [$(e.target).data('id')]
                    };               
                    BX.ajax({
                       url: '<?=$component->GetPath()?>/component.php',
                       method: 'POST',
                       data: postData,
                       dataType: 'json',                   
                       onsuccess: function(data){                        
                           if(data == "ok"){
                                $('#callback<?=$arParams["UNIQ_ID"]?>-result-good').html("Спасибо! Мы с Вами свяжемся!");
                                $('#callback<?=$arParams["UNIQ_ID"]?>-form').hide();
                                $('#phone-panel<?=$arParams["UNIQ_ID"]?> .subtext').hide();
                            }
                            else{
                                $('#callback<?=$arParams["UNIQ_ID"]?>-error').html(data);                                
                            }
                       },
                       onfailure: function(error){
                          console.log(error);
                       } 
                    });
                    

                }
            });
        
    });   
</script>
купить в 1 клик шаблон
<?if(!defined("B_PROLOG_INCLUDED")||B_PROLOG_INCLUDED!==true)die();
CJSCore::Init(array('ajax'));
?>
<div class="popup-overlay" id="phone-panel<?=$arParams["UNIQ_ID"]?>">
     <div class="popup-wrap">
        <button class="button-close popup-close" type="button"><i class="icon-close"></i></button>
        <div class="popup-header">
            <div class="figure"><i class="icon-message"></i></div>
            <span id="callback<?=$arParams["UNIQ_ID"]?>-result-good"><?=$arParams["HEADER"]?></span>
            <p class="subtext"><?=$arParams["TEXT"]?></p>
            <p class="subtext" id="callback<?=$arParams["UNIQ_ID"]?>-error"></p>
        </div>
        
        <form class="auth-form" action="/" id="callback<?=$arParams["UNIQ_ID"]?>-form">
            <?=bitrix_sessid_post()?>
            <input class="field-dark" type="text" placeholder="Представьтесь" id="callback<?=$arParams["UNIQ_ID"]?>-name" value="<?=$arResult["USER"]["FULL_NAME"] ?? ""?>">
            <input class="field-dark" type="phone" placeholder="Ваш телефон" id="callback<?=$arParams["UNIQ_ID"]?>-phone" value="<?=$arResult["USER"]["PHONE_NUMBER"] ?? ""?>">
            <?if($arParams["SHOW_TEXT"]=="Y"):?>
                <textarea class="field-dark" placeholder="Комментарий, адрес доставки, удобное время" id="callback<?=$arParams["UNIQ_ID"]?>-text"></textarea>
            <?endif;?>
            <button class="button-basic flex-center w-100" type="submit" id="callback<?=$arParams["UNIQ_ID"]?>-send">Отправить</button>
        </form>
    </div>
</div>
<script>
    BX.ready(function(){
       
            $(".callback-button<?=$arParams["PREFIX"]?>").on("click", function(e) {       
                e.preventDefault();
                $("#callback<?=$arParams["UNIQ_ID"]?>-send").data("id",$(e.target).data('id'));
                $("#phone-panel<?=$arParams["UNIQ_ID"]?>").addClass("active-modal");
            });
           $("#callback<?=$arParams["UNIQ_ID"]?>-send").click(function(e){
                e.preventDefault(); 
               
                $('#callback<?=$arParams["UNIQ_ID"]?>-error').html("");           
                let phone = $("#callback<?=$arParams["UNIQ_ID"]?>-phone").val();            
                if((phone == "") || (phone.indexOf('_')>0)){
                    $('#callback<?=$arParams["UNIQ_ID"]?>-error').html("Проверьте корректность телефона");                
                }
                else{
                    let postData = {
                        sessid: BX.bitrix_sessid(),
                        site_id: BX.message('SITE_ID'),
                        phone: phone,
                        name: $('#callback<?=$arParams["UNIQ_ID"]?>-name').val(),
                        ajax_call: 'Y',
                        form_name: "<?=$arParams["HEADER"]?>",
                        text: $('#callback<?=$arParams["UNIQ_ID"]?>-text').val(),                        
                    };               
                    BX.ajax({
                       url: '<?=$this->GetFolder()?>/ajax.php',
                       method: 'POST',
                       data: postData,
                       dataType: 'json',                   
                       onsuccess: function(data){                        
                           if(data == "ok"){
                                $('#callback<?=$arParams["UNIQ_ID"]?>-result-good').html("Спасибо! Мы с Вами свяжемся!");
                                $('#callback<?=$arParams["UNIQ_ID"]?>-form').hide();
                                $('#phone-panel<?=$arParams["UNIQ_ID"]?> .subtext').hide();
                            }
                            else{
                                $('#callback<?=$arParams["UNIQ_ID"]?>-error').html(data);                                
                            }
                       },
                       onfailure: function(error){
                          console.log(error);
                       } 
                    });
                    

                }
            });
        
    });   
</script>
ajax.php (который формирует заказ)
<?require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
define('SITE_ID', "s1");
define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/log.txt");
//use Bitrix\Main\Application;
//$request = Application::getInstance()->getContext()->getRequest();


use Bitrix\Main\Web\Uri;
use \Bitrix\Main\UserTable;
use \Bitrix\Main;
use \Bitrix\Main\Loader;
use \Bitrix\Sale\Delivery;
use \Bitrix\Sale\PaySystem;
use \Bitrix\Sale;
use \Bitrix\Sale\Order;
use \Bitrix\Sale\DiscountCouponsManager;
use Bitrix\Main\Localization\Loc;

Bitrix\Main\Loader::includeModule("sale");


if(empty($_POST["phone"])){ 
    $result = "Введите телефон";
    echo json_encode($result);
}
else{   
    
    $name = $_POST["name"] ?? "Не заполнено";        
    $text = $_POST["text"] ?? ""; 
    $formName = $_POST["form_name"] ?? "Купить в 1 клик: ";       
    $description = $formName.": ".$_POST["phone"]." Имя: ".$name."\n".$text; 

    global $USER;
    if($USER->IsAuthorized()){
        $userId  = $USER->GetID();
        $email = $USER->GetEmail(); 
    }
    else{
        $userId = 20;
        $email = "one_click@mail.ru";
    }
    
    
    DiscountCouponsManager::init();
    $order = \Bitrix\Sale\Order::create(SITE_ID, $userId,"RUB");
    $order->setPersonTypeId(1);
    $basket = Sale\Basket::loadItemsForFUser(Sale\Fuser::getId(), SITE_ID);
    $order->setBasket($basket);
    $order->setField("USER_DESCRIPTION",$description);

    //доставка
    $shipmentCollection = $order->getShipmentCollection();
    $shipment = $shipmentCollection->createItem();
    $deliveryId = Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); //доставка "без доставки"

    $service = Delivery\Services\Manager::getById($deliveryId);
     
    $shipment->setFields(array(
        'DELIVERY_ID' => $service['ID'],
        'DELIVERY_NAME' => $service['NAME'],                         
    ));
    $shipmentItemCollection = $shipment->getShipmentItemCollection();
    foreach ($order->getBasket() as $item){
        $shipmentItem = $shipmentItemCollection->createItem($item);
        $shipmentItem->setQuantity($item->getQuantity());
    }
    //оплата
    $paymentCollection = $order->getPaymentCollection();
    $payment = $paymentCollection->createItem(\Bitrix\Sale\PaySystem\Manager::getObjectById(2)); //$paySystemId  - ИД платежной системы
    $payment->setField('SUM', $order->getPrice());

    $propertyCollection = $order->getPropertyCollection();
    if($property = $propertyCollection->getItemByOrderPropertyCode("NAME")){
        $property->setValue($name);
    }    
    if($property = $propertyCollection->getItemByOrderPropertyCode("PHONE")){
        $property->setValue($phone);
    }   
    if($property = $propertyCollection->getItemByOrderPropertyCode("EMAIL")){
        $property->setValue($email);
    }
   
    $order->doFinalAction(true);
     
    $error = false;  
    try {
        $resultOrder = $order->save(); 
    } catch (Exception $e) {
        AddMessage2Log($e->getMessage());
        $error = true; //$e->getMessage();      
         
    }
             
   
    if(!$error){    
        if ($resultOrder->isSuccess()) {
            $result = "ok";            
        } 
        else {                       
            AddMessage2Log($resultOrder->getError());            
        }
    }
                
    $result = "ok";
    $GLOBALS['APPLICATION']->RestartBuffer();    
    echo json_encode($result);
    die();
}

вызов форм в футере
<?$APPLICATION->IncludeComponent(
      "nikaverro:feedback.call",
      "",
      Array(
        "IBLOCK_ID" => 28,
        "PREFIX" => ""
      )
    );?>
    <?if($APPLICATION->GetCurPage() == "/partners/"):?>  
      <?$APPLICATION->IncludeComponent(
        "nikaverro:feedback.call",
        "",
        Array(
          "IBLOCK_ID" => 28,
          "PREFIX" => "partner",
          "HEADER" => "Стать партнером",
          "SHOW_TEXT" => "Y"
        )
      );?>
    <?elseif($APPLICATION->GetCurPage() == "/basket/"):?>
      <?$APPLICATION->IncludeComponent(
        "nikaverro:feedback.call",
        "basket_one_click",
          Array(
             "IBLOCK_ID" => 28,
             "PREFIX" => "basket-one-click",
             "HEADER" => "Купить в 1 клик",
             "TEXT" => "Оставьте заявку, и мы свяжемся с вами в ближайшее время"
          )
      );?>
    <?endif;?>
в деталке товара
обязательно в кнопке, которая "купить в 1 клик" атрибут
data-id="<?=$arResult["ID"]?>"
<?$APPLICATION->IncludeComponent(
    "nikaverro:feedback.call",
    "element_one_click",
    Array(
       "IBLOCK_ID" => 28,
       "PREFIX" => "one-click",
       "HEADER" => "Купить в 1 клик",
       "TEXT" => "Оставьте заявку на товар ".$arResult["NAME"].", и мы свяжемся с вами в ближайшее время",
       "SHOW_TEXT" = > "Y"
    )
);?>