Программно добавить заказ D7

Скрипт js, в котором собираем необходимые данные в sendData и с помощью ajax отправляем их в файл обработки order.php:

var form = $('.registr__desc'),
    btn = $('.registr__btn');
function checkInput(){
$('.registr__desc').find('.required').each(function(){
if($(this).val() != ''){
$(this).removeClass('empty_field');
$(this).removeAttr('style');
} else {
$(this).addClass('empty_field');
}
});
}
function lightEmpty(){
form.find('.empty_field').css({'border-color':'rgba(217, 31, 67, 0.5)'});
$(".alert_required").text("Заполнены не все поля");
}
setInterval(function(){
checkInput();
var sizeEmpty = form.find('.empty_field').size();
if(sizeEmpty > 0){
if(btn.hasClass('disabled')){
return false
} else {
btn.addClass('disabled')
}
} else {
$(".alert_required").text("");
btn.removeClass('disabled')
}
},500);
$('body').on('click', '.registr__btn', function () {
if($(this).hasClass('disabled')){
lightEmpty();
return false
}
$payment = $('input[name=user__payment]:checked');
$delivery = $('input[name=user__delivery]:checked');
var sendData = {
name: $('input[name=user__name]').val(),
second_name: $('input[name=user__secondname]').val(),
last_name: $('input[name=user__lastname]').val(),
phone: $('input[name=user__phone]').val(),
address: $('input[name=user__address]').val(),
payment: $payment.val(),
delivery: $delivery.val(),
paymentName: $payment.parent().find('.site-bar__text').text(),
deliveryName: $delivery.parent().find('.site-bar__text').text()
};
$.ajax({
url: '/ajax/order.php',
type: 'POST',
data: ({sendData: sendData}),
dataType: "html",
error: error,
success: successOrder
})
})
function error(){
alert('Ошибка при загрузке данных!');
}
function successOrder(result){
console.log(result);
str = '/payment.php?ORDER_ID=';
str += result;
window.location.href = str;
}

Содержимое файла order.php:

<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php"); 
global $USER;
use Bitrix\Main,
Bitrix\Main\Localization\Loc as Loc,
Bitrix\Main\Loader,
Bitrix\Main\Config\Option,
Bitrix\Sale\Delivery,
Bitrix\Sale\PaySystem,
Bitrix\Sale,
Bitrix\Sale\Order,
Bitrix\Sale\DiscountCouponsManager,
Bitrix\Main\Context;

if (!Loader::IncludeModule('sale'))
die();
$siteId = \Bitrix\Main\Context::getCurrent()->getSite();
$fio = $_POST['sendData']['name'];
$phone = $_POST['sendData']['phone'];
$address = $_POST['sendData']['address'];
$currencyCode = Option::get('sale', 'default_currency', 'RUB');
DiscountCouponsManager::init();
if ($USER->IsAuthorized()){
$email = $USER->GetEmail();
} else {

$log = str_replace([' ', '(', ')', '-'], '', $phone);
$psw = rand(111111, 999999);
$user = new CUser;
$email = 'info@info.ru';
$arFields = Array(
"EMAIL" => 'info@info.ru',
"NAME" => $fio,
"PERSONAL_PHONE" => $phone,
"LOGIN" => $log,
"LID" => "ru",
"ACTIVE" => "Y",
"GROUP_ID" => array(2, 3, 4),
"PASSWORD" => $psw,
"CONFIRM_PASSWORD" => $psw
);

$ID = $user->Add($arFields);

if (intval($ID) > 0){
$arAuthResult = $USER->Login($log, $psw, "Y");
$APPLICATION->arAuthResult = $arAuthResult;
}else{
$error_box = "";
$error_box .= "<span style='color: red;'>".$user->LAST_ERROR."</span><br/>";
echo json_encode(array(
'errors' => $error_box
));
}
}
$order = Order::create($siteId, $USER->GetID());
$order->setPersonTypeId(2);
$basket = Sale\Basket::loadItemsForFUser(\CSaleBasket::GetBasketUserID(), $siteId)->getOrderableItems();


$order->setBasket($basket);
/*Shipment*/
$shipmentCollection = $order->getShipmentCollection();
$shipment = $shipmentCollection->createItem();
$shipmentItemCollection = $shipment->getShipmentItemCollection();
$shipment->setField('CURRENCY', $order->getCurrency());
foreach ($order->getBasket() as $item)
{
$shipmentItem = $shipmentItemCollection->createItem($item);
$shipmentItem->setQuantity($item->getQuantity());
}
$arDeliveryServiceAll = Delivery\Services\Manager::getRestrictedObjectsList($shipment);
$shipmentCollection = $shipment->getCollection();

if (!empty($arDeliveryServiceAll)) {
reset($arDeliveryServiceAll);
$deliveryObj = current($arDeliveryServiceAll);

if ($deliveryObj->isProfile()) {
$name = $deliveryObj->getNameWithParent();
} else {
$name = $deliveryObj->getName();
}

$shipment->setFields(array(
'DELIVERY_ID' => $_POST['sendData']['delivery'],
'DELIVERY_NAME' => $_POST['sendData']['deliveryName'],
'CURRENCY' => $order->getCurrency()
));

$shipmentCollection->calculateDelivery();
}
/**/

/*Payment*/
$arPaySystemServiceAll = [];
$paySystemId = $_POST['sendData']['payment'];
$paymentCollection = $order->getPaymentCollection();

$remainingSum = $order->getPrice() - $paymentCollection->getSum();
if ($remainingSum > 0 || $order->getPrice() == 0)
{
$extPayment = $paymentCollection->createItem();
$extPayment->setField('SUM', $remainingSum);
$arPaySystemServices = PaySystem\Manager::getListWithRestrictions($extPayment);

$arPaySystemServiceAll += $arPaySystemServices;

if (array_key_exists($paySystemId, $arPaySystemServiceAll))
{
$arPaySystem = $arPaySystemServiceAll[$paySystemId];
}
else
{
reset($arPaySystemServiceAll);

$arPaySystem = current($arPaySystemServiceAll);
}
if (!empty($arPaySystem))
{
$extPayment->setFields(array(
'PAY_SYSTEM_ID' => $_POST['sendData']['payment'],
'PAY_SYSTEM_NAME' => $_POST['sendData']['paymentName']
));
}
else
$extPayment->delete();
}
$order->doFinalAction(true);
$order->setField('CURRENCY', $currencyCode);
//Комментарий менеджера
$order->setField('COMMENTS', 'Комментарии менеджера');
//Комментарий покупателя
$order->setField('USER_DESCRIPTION', 'Комментарии покупателя');
/**/
function getPropertyByCode($propertyCollection, $code) {
foreach ($propertyCollection as $property)
{
if($property->getField('CODE') == $code){
return $property;
}
}
}
$propertyCollection = $order->getPropertyCollection();

if($_POST['sendData']['delivery'] != 3){
$addressProperty=getPropertyByCode($propertyCollection,'ADDRESS');
$addressProperty->setValue($address);
}
$emailProperty = getPropertyByCode($propertyCollection, 'EMAIL');
$emailProperty->setValue($email);
$nameProperty = getPropertyByCode($propertyCollection, 'NAME');
$nameProperty->setValue($fio);
$phoneProperty = getPropertyByCode($propertyCollection, 'PHONE');
$phoneProperty->setValue($phone);

$order->save();
$orderId = $order->GetId();
echo $orderId;


require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");
?>
Скрипт создания заказа содержит в себе неточности, касающиеся создания нового пользователя, а также добавления заказа только для одного типа плательщика, что легко может быть доработано посредством передачи и получения необходимых полей.



bitrixone © 2024