javascript Bitrix Mail使用验证码和短信发送

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Bitrix Mail使用验证码和短信发送相关的知识,希望对你有一定的参考价值。

<?
if(isset($_POST['USE_JSON'])) {
    define('STOP_STATISTICS', true);
    define("NO_KEEP_STATISTIC", true);
    define("NO_AGENT_CHECK", true);
    define('PUBLIC_AJAX_MODE', true);
    require_once($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php");
    $APPLICATION->ShowIncludeStat = false;
    $GLOBALS['APPLICATION']->RestartBuffer();
    
    echo json_encode(Array(
        'auth' => Auth::isAuth(),
        'captcha' => isset($_SESSION['CAPTCHA']) ? $_SESSION['CAPTCHA'] : false,
    ), APP_JSON_OPTIONS);

    require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/epilog_after.php");
    return;
}


define("NEED_AUTH", true);
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

if (isset($_REQUEST["backurl"]) && strlen($_REQUEST["backurl"])>0) 
	LocalRedirect($backurl);

$APPLICATION->SetTitle("Авторизация");
?>
<p>Вы зарегистрированы и успешно авторизовались.</p>
 
<p>Используйте административную панель в верхней части экрана для быстрого доступа к функциям управления структурой и информационным наполнением сайта. Набор кнопок верхней панели отличается для различных разделов сайта. Так отдельные наборы действий предусмотрены для управления статическим содержимым страниц, динамическими публикациями (новостями, каталогом, фотогалереей) и т.п.</p>
 
<p><a href="<?=SITE_DIR?>">Вернуться на главную страницу</a></p>

<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>
<?

if (isset($_POST['USE_JSON'])) {
    define('STOP_STATISTICS', true);
    define("NO_KEEP_STATISTIC", true);
    define("NO_AGENT_CHECK", true);
    define('PUBLIC_AJAX_MODE', true);
    require_once($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php");
    $APPLICATION->ShowIncludeStat = false;
    $GLOBALS['APPLICATION']->RestartBuffer();

    $request = \Bitrix\Main\Application::getInstance()->getContext()->getRequest();
    $data = $request->getPost("REGISTER");

    $result = false;
    $captcha = false;
    $userid = 0;
    $msg = '';
    if (isset($_POST["captcha_sid"]) && $_POST["captcha_sid"]) {
        global $APPLICATION;

        $data['LOGIN'] = preg_replace('/[^0-9]/', '', $data['LOGIN']);
        $data['PASSWORD'] = $data['CONFIRM_PASSWORD'] = $_SESSION['CONFIRM_CODE'] . $data['PASSWORD'];
        $rsUser = CUser::GetByLogin($data['LOGIN']);

        if (!$rsUser->Fetch()) {
            $confirmCode = isset($_SESSION['CONFIRM_CODE']) && $_SESSION['CONFIRM_CODE'] === intval($_POST['PHONE_CODE']);
            if ($confirmCode && $APPLICATION->CaptchaCheckCode($_POST["captcha_word"], $_POST["captcha_sid"])) {
                $user = new CUser;
                
                $arFields = Array(
                    "NAME" => $data['NAME'],
                    "EMAIL" => $data['EMAIL'],
                    "LOGIN" => $data['LOGIN'],
                    "LID" => "ru",
                    "ACTIVE" => "Y",
                    "GROUP_ID" => array(3, 4, 5),
                    "PASSWORD" => $data['PASSWORD'],
                    "CONFIRM_PASSWORD" => $data['CONFIRM_PASSWORD'],
                    "PERSONAL_BIRTHDAY" => $data['PERSONAL_BIRTHDAY'],
                    'PERSONAL_GENDER' => $data['PERSONAL_GENDER'],
                    'PERSONAL_STREET' => $data['PERSONAL_STREET'],
                    'PERSONAL_ZIP' => $data['PERSONAL_ZIP'],
                );
                
                if ($userid = $user->Add($arFields)) {
                    $captcha = true;
                    
                    global $USER;
                    $USER->Authorize($userid);
                }
            }
        } else {
            $msg = 'Пользователь с таким телефоном уже зарегистрирован';
        }
    }

    echo json_encode(Array(
        'auth' => Auth::isAuth(),
        'captcha' => $captcha,
        '$userid' => $userid,
        'msg' => $msg
            ), APP_JSON_OPTIONS);

    require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/epilog_after.php");
    return;
}
?>
<?
AddEventHandler("main", "OnBeforeUserLogin", "OnBeforeUserLoginHandler");

function OnBeforeUserLoginHandler(&$arFields) {
    $_SESSION["CAPTCHA"] = false;
    $_SESSION['CONFIRM_CODE'] = false;
    if (isset($_POST["captcha_code"]) && $_POST["captcha_code"]) {
        global $APPLICATION;

        $arFields['LOGIN'] = preg_replace('/[^0-9]/', '', $arFields['LOGIN']);
        $rsUser = CUser::GetByLogin($arFields['LOGIN']);

        if ($arUser = $rsUser->Fetch()) {
            $_SESSION['CONFIRM_CODE'] = $arUser['CONFIRM_CODE'] && $arUser['CONFIRM_CODE'] === $arFields['PASSWORD'];
            if ($_SESSION['CONFIRM_CODE']) {
                $_SESSION["CAPTCHA"] = $APPLICATION->CaptchaCheckCode($_POST["captcha_word"], $_POST["captcha_code"]);
                
                if (!$_SESSION["CAPTCHA"]) {
                    $arFields['LOGIN'] = '';
                } else {
                    global $USER;

                    $USER->Authorize($arUser['ID']);
                    $user = new CUser;
                    $res = $user->Update($arUser["ID"], array("CONFIRM_CODE" => 0));
                }
            }
        }
    }
}
<?
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true)
    die();
$cpt = $arResult['cpt'];
?>

<? if ($arResult['isAuth'] === false) : ?>
    <div class="registration_modal form-modal" modal="login">
        <a href="javascript:showCFormWindow('content-login');">
            <img src="<?= SITE_TEMPLATE_PATH ?>/images/close_big.png" class="close_big"/>
        </a>
        <form data-auth id="aut" method="post" action="/auth/index.php?login=yes">
            <input type="hidden" id="USER_REMEMBER" name="USER_REMEMBER" value="Y">
            <input
                type="hidden"
                value="<?= $arResult['bxAjaxId'] ?>"
                name="bxajaxid"
                >
            <input type="hidden" name="AUTH_FORM" value="Y">
            <input type="hidden" name="USE_JSON" value="Y">
            <input type="hidden" name="TYPE" value="AUTH">
            <input type="hidden" name="backurl" value="<?= $arResult['backUrl'] ?>">
            <input name="captcha_code" class="captchaSid" value="<?= htmlspecialchars($cpt->GetCodeCrypt()); ?>" type="hidden">

            <h2>Войти</h2>
            <div class="form-row">
                <div class="form-label form-label--required"><label>По номеру телефона</label></div>
                <div class="form-field form-field--large">
                    <input 
                        type="text" 
                        placeholder="+7 ___ ___ ____" 
                        name="USER_LOGIN"
                        data-login
                        data-required
                        data-error-text="Для входа в систему, необходимо ввести email или
                        номер телефона указанные при регистрации"
                        value=""
                        data-phone
                        >
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-label"></div>
                <div class="form-field captchaBlock">
                    <div class="whiteBlock">
                        <img class="loaderImg" src="<?= SITE_TEMPLATE_PATH ?>/images/ajax-loader.gif" />
                    </div>
                    <img class="captchaImg" src="/bitrix/tools/captcha.php?captcha_code=<?= htmlspecialchars($cpt->GetCodeCrypt()); ?>">
                    <a class="reloadCaptcha">Обновить капчу</a>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-label"></div>
                <div class="form-field form-field--medium">
                    <input 
                        name="captcha_word" 
                        type="text" 
                        placeholder="Введите капчу"
                        id="captcha"
                        data-required
                        data-error-text="Введите код"
                        value=""
                        >
                </div>
            </div>

            <div class="form-row">
                <div class="form-label"></div>
                <div class="form-field form-field--small">
                    <button class="btn btn-action" data-sms="sms_get_code_first">Выслать код по СМС</button>
                </div>
            </div>

            <div class="form-row" hidden>
                <div class="form-label"></div>
                <div class="form-field form-field--small">
                    <input 
                        class="field-input--code"
                        type="text" 
                        placeholder="Код из смс" 
                        name="USER_PASSWORD" 
                        id="code"
                        data-required
                        data-error-text="Необходимо ввести код из смс"
                        value=""  
                        >

                </div>
                <div class="form-field" data-sms="sms_if_sent_code" hidden><span>Мы можем выслать код еще раз,<br>через <b data-sms="sms_timer" data-timer="1:00">1:00</b></span></div>
                <div class="form-field" data-sms="sms_get_code"><span>Выслать код еще раз</span></div>
            </div>
            <div class="form-row">
                <div class="form-label"></div>
                <div class="form-field">
                    <button class="btn btn-action btn-large" type="submit" name="Login" disabled>Войти</button>
                </div>
            </div>
        </form>
    </div>
<? endif; ?>
$(document)
        .ready(function () {
            var authErrorCount = 0, captcha = true;

            var authForm = new MyForm('form[data-auth]', {
                onSubmit: function ($authForm, action, formData) {
                    var $submit = $authForm.find('button[type="submit"]'), onAuthError;

                    $submit.prop('disabled', true);

                    if (authErrorCount > 99) {
                        window.location.href = '/auth/';
                        return false;
                    }

                    onAuthError = function () {
                        var msg = 'Ошибка авторизации';
                        if (!captcha) {
                            msg = 'Неверный код';
                        }
                        authErrorCount++;
                        authForm.pushError($submit, msg);
                        $submit.parent().addClass('has-error');
                        setTimeout(function () {
                            $submit.parent().removeClass('has-error');
                            $submit.prop('disabled', false);
                        }, 1500);
                    };

                    $.ajax({
                        url: action,
                        data: formData,
                        type: 'POST',
                        dataType: 'json',
                        success: function (res) {
                            console.log(res);
                            if (res && res.auth === true) {
                                window.location.href = '/cabinet/';
                            } else {
                                captcha = res.captcha;
                                onAuthError();
                            }
                        },
                        error: onAuthError
                    })
                }
            });
        });
<?

if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true)
    die();

$arResult['bxAjaxId'] = CAjax::GetComponentID('bitrix:system.auth.form', 'personal', '');
$arResult['backUrl'] = $APPLICATION->GetCurUri();
$arResult['isAuth'] = $USER && $USER->IsAuthorized();

include_once($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/captcha.php");
$cpt = new CCaptcha();
$captchaPass = COption::GetOptionString("main", "captcha_password", "");
if (strlen($captchaPass) <= 0) {
    $captchaPass = randString(10);
    COption::SetOptionString("main", "captcha_password", $captchaPass);
}
$cpt->SetCodeCrypt($captchaPass);
$arResult['cpt'] = $cpt;
<? if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die();

//.description
$arComponentDescription = array(
    "NAME"    => 'Компонент подгрузки модалки',
    "DESCRIPTION" => 'Компонент подгрузки модалки'
);

//.parametres
if(!CModule::IncludeModule("iblock"))
    return;

$arComponentParameters = array(
    "GROUPS" => array(
    ),
    "PARAMETERS" => array(
        "NPS_MODAL_ID" => array(
            "PARENT" => "BASE",
            "NAME" => "ID модалки",
            "TYPE" => "STRING",
            "DEFAULT" => '',
        ),
    )
);

//component.php
if (empty($arParams['NPS_MODAL_ID'])) {
    $arParams['NPS_MODAL_ID'] = uniqid('modal_');
}

$arParams['PREFIX_ID'] = uniqid('id_');

$this->IncludeComponentTemplate();
<?
$APPLICATION->IncludeComponent(
        "nopreset:modal",
        "auth",
        array(
            "COMPONENT_TEMPLATE" => "auth",
            "NPS_MODAL_ID" => "authorization"
        ),
        false
);
?>
<?
$APPLICATION->IncludeComponent(
        "bitrix:main.register",
        "sign_with_phone",
        array(
            "AUTH" => "Y",
            "CACHE_TYPE" => "N",
            "REQUIRED_FIELDS" => array(
                'NAME',
            ),
            "SET_TITLE" => "N",
            "SHOW_FIELDS" => Array("NAME", "SECOND_NAME", "LAST_NAME", "PERSONAL_PHONE", "PERSONAL_NOTES", "PERSONAL_GENDER", "PERSONAL_BIRTHDAY"), 
            "SUCCESS_PAGE" => "",
            "USER_PROPERTY" => array(
                0 => "",
            ),
            "USER_PROPERTY_NAME" => "",
            "USE_BACKURL" => "Y",
            "COMPONENT_TEMPLATE" => "sign_with_phone",
            "COMPOSITE_FRAME_MODE" => "A",
            "COMPOSITE_FRAME_TYPE" => "AUTO"
        ),
        false
);
?>
<?
if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true)
    die();
?>
<?

use Bitrix\Main\Context;
?>

<?
if (count($arResult["ERRORS"]) > 0):
    foreach ($arResult["ERRORS"] as $key => $error)
        if (intval($key) == 0 && $key !== 0)
            $arResult["ERRORS"][$key] = str_replace("#FIELD_NAME#", "&quot;" . GetMessage("REGISTER_FIELD_" . $key) . "&quot;", $error);

    ShowError(implode("<br />", $arResult["ERRORS"]));

elseif ($arResult["USE_EMAIL_CONFIRMATION"] === "Y"):
    ?>
    <p><? echo GetMessage("REGISTER_EMAIL_WILL_BE_SENT") ?></p>
<? endif ?>

<div class="registration_modal form-modal" modal="registration">
    <form action="/auth/reg/" name="regform" method="post">
        <input type="hidden" name="captcha_sid" class="captchaSid" value="<?= $arResult["CAPTCHA_CODE"] ?>" />
        <input type="hidden" name="is_regform" value="Y" />
        <input type="hidden" name="USE_JSON" value="Y">
        <img src="<?= SITE_TEMPLATE_PATH ?>/images/close_big.png" class="close_big"/>
        <h2>Зарегистрироваться</h2>
        <div class="form-row">
            <div class="form-label form-label--required"><label>Ваше полное имя</label></div>
            <div class="form-field form-field--large">
                <input 
                    type="text" 
                    name="REGISTER[NAME]" 
                    placeholder="Иванов Иван Иванович" 
                    data-required
                    value='test'
                    >
            </div>
        </div>
        <div class="form-row">
            <div class="form-label form-label--required"><label>Как к вам обращаться</label></div>
            <div class="form-field">
                <div class="toggle-controls">
                    <input type="hidden" name="REGISTER[PERSONAL_GENDER]" value="M">
                    <div class="toggle-controls__item active"><label>Джентельмен<input type="radio" name="PERSONAL_GENDER" value="M"></label></div>
                    <div class="toggle-controls__item"><label>Леди<input type="radio" name="PERSONAL_GENDER" value="F"></label></div>
                </div>
            </div>
        </div>
        <div class="form-row">
            <div class="form-label form-label--required"><label>Дата рождения</label></div>
            <div class="form-field form-field--medium">
                <input type="text" name="REGISTER[PERSONAL_BIRTHDAY]" placeholder="10.05.1991" value="" data-birthday data-required>
                <?
                $APPLICATION->IncludeComponent(
                        'bitrix:main.calendar',
                        '',
                        array(
                            'SHOW_INPUT' => 'N',
                            'FORM_NAME' => 'regform',
                            'INPUT_NAME' => 'REGISTER[PERSONAL_BIRTHDAY]',
                            'SHOW_TIME' => 'N'
                        ),
                        null,
                        array("HIDE_ICONS" => "Y")
                );
                ?>
            </div>
        </div>
        <div class="form-row">
            <div class="form-label"><label>Адрес</label></div>
            <div class="form-field form-field--wide"><input type="text" name="REGISTER[PERSONAL_STREET]" placeholder="Например, г. Саратов, ул. Лермонтова дом 239, квартира 318 "></div>
        </div>
        <div class="form-row">
            <div class="form-label"><label>Индекс</label></div>
            <div class="form-field form-field--medium"><input type="text" name="REGISTER[PERSONAL_ZIP]" placeholder=""></div>
        </div>
        <div class="form-row">
            <div class="form-label form-label--required"><label>Email</label></div>
            <div class="form-field form-field--large"> 
                <input type="text" name="REGISTER[EMAIL]" placeholder="" value="" data-required>
            </div>
        </div>
        <div class="form-row">
            <div class="form-label form-label--required"><label>Телефон</label></div>
            <div class="form-field form-field--large">
                <input 
                    type="text" 
                    name="REGISTER[LOGIN]" 
                    placeholder="+7 ___ ___ ____" 
                    data-phone 
                    data-login 
                    data-required
                    value=''
                    >
            </div>
            <!--TODO: REGISTER[PERSONAL_PHONE]-->
        </div>
        <div class="form-row">
            <div class="form-label"></div>
            <div class="form-field captchaBlock">
                <div class="whiteBlock">
                    <img class="loaderImg" src="<?= SITE_TEMPLATE_PATH ?>/images/ajax-loader.gif" />
                </div>
                <img class="captchaImg" src="/bitrix/tools/captcha.php?captcha_code=<?= $arResult["CAPTCHA_CODE"] ?>">
                <a class="reloadCaptcha">Обновить капчу</a>
            </div>
        </div>

        <div class="form-row">
            <div class="form-label"></div>
            <div class="form-field form-field--medium">
                <input type="text" name="captcha_word" placeholder="Введите капчу" data-required>
            </div>
        </div>

        <div class="form-row">
            <div class="form-label"></div>
            <div class="form-field form-field--small">
                <button class="btn btn-action" data-sms="sms_get_code_first" href="javascript:void(0);">Выслать код по СМС</button>
            </div>
        </div>
        <div class="form-row" hidden>
            <div class="form-label"></div>
            <div class="form-field form-field--small">
                <input 
                    class="field-input--code"
                    type="text" 
                    placeholder="Код из смс" 
                    name="PHONE_CODE" 
                    id="code"
                    data-required
                    data-error-text="Необходимо ввести код из смс"
                    value=""
                    >
                    <? $tmpPass = time(); ?>
                <input type="hidden" name="REGISTER[PASSWORD]" value="<?= $tmpPass ?>">
                <input type="hidden" name="REGISTER[CONFIRM_PASSWORD]" value="<?= $tmpPass ?>">
            </div>
            <div class="form-field" data-sms="sms_if_sent_code" hidden><span>Мы можем выслать код еще раз,<br>через <b data-sms="sms_timer" data-timer="1:00">1:00</b></span></div>
            <div class="form-field" data-sms="sms_get_code"><span>Выслать код еще раз</span></div>
        </div>            

        <div class="form-row">
            <div class="form-label"></div>
            <div class="form-field">
                <div class="checkbox-control"><input type="checkbox" checked id="license" data-required>
                    <div class="checkbox-control__item"></div><label for="license">Я согласен на <a href="#">обработку моих<br>персональных данных</a></label>
                </div>
            </div>
        </div>

        <div class="form-row">
            <div class="form-label"></div>
            <div class="form-field">
                <button class="btn btn-action btn-large" name="register_submit_button" type="submit" value="<?= GetMessage("AUTH_REGISTER") ?>" disabled>Зарегистрироваться</button>
            </div>
        </div>
    </form>
</div>

<script>
  $(document)
        .ready(function () {
            var genderToggle = '.toggle-controls__item',
                    genderInput = '[name="REGISTER[PERSONAL_GENDER]"]',
                    active = 'active';

            $('body').on('click', genderToggle + ':not(.active)', function () {
                var self = $(this),
                        val = self.find('input').val();

                $(genderToggle + '.' + active).removeClass(active);

                self.addClass(active);
                $(genderInput).val(val);
            });

            var authErrorCount = 0, captcha = true, msg = '';

            var authForm = new MyForm('form[name="regform"]', {
                onSubmit: function ($authForm, action, formData) {
                    var $submit = $authForm.find('button[type="submit"]'), onAuthError;

                    $submit.prop('disabled', true);

                    if (authErrorCount > 99) {
                        window.location.href = '/auth/';
                        return false;
                    }

                    onAuthError = function () {
                        if (!msg) {
                            msg = 'Ошибка авторизации';
                            if (!captcha) {
                                msg = 'Неверная капча';
                            }
                        }
                        authErrorCount++;
                        authForm.pushError($submit, msg);
                        console.log(authErrorCount);

                        $submit.parent().addClass('has-error');
                        setTimeout(function () {
                            $submit.parent().removeClass('has-error');
                            $submit.prop('disabled', false);
                        }, 1500);
                    };

                    console.log(formData, action);

                    $.ajax({
                        url: action,
                        data: formData,
                        type: 'POST',
                        dataType: 'json',
                        success: function (res) {
                            if (res && res.auth === true) {
                                window.location.href = '/cabinet/';
                            } else {
                                captcha = res.captcha;
                                msg = res.msg;
                                onAuthError();
                            }
                        },
                        error: onAuthError
                    })
                }
            });
        });
</script>

<style>
.field-text[hidden] {
  display: none;
}

.toggle-controls__item label {
    cursor: pointer;
}
</style>

$(document).ready(function () {
    var classForm = '.form-modal:visible',
            button = classForm + ' [type="submit"]';

    var $phone = $("[data-phone]");
    if ($phone.length) {
        paramsMask = {placeholder: "_", autoclear: true},
                mobileMask = "+7 999 999 9999";
        $phone.mask(mobileMask, paramsMask);
    }

    var $birthday = $('[data-birthday]');
    if ($birthday.length) {
        params = {placeholder: "_", autoclear: true};
        mask = "99.99.9999";

        $birthday.mask(mask, params);
    }

    var timerCls = classForm + ' [data-sms="sms_timer"]',
            getCodeCls = classForm + ' [data-sms="sms_get_code"]',
            getCodeFirst = classForm + ' [data-sms="sms_get_code_first"]',
            ifSentCode = classForm + ' [data-sms="sms_if_sent_code"]',
            phoneCls = classForm + ' [name="USER_LOGIN"]',
            phoneRegCls = classForm + ' [name="REGISTER[LOGIN]"]',
            formData = '';

    if ($(timerCls).length) {
        $(getCodeCls + ':not(.active)').click(function () {
            $(this).addClass('active');
            getCode();
        });
        $(getCodeFirst + ':not(.active)').click(function () {
            $(this).addClass('active');
            getCode();
        });
    }

    $(classForm + ' [data-login]').on('change', function () {
        if ($(this).val()) {
            $(getCodeFirst).prop('disabled', false);
        } else {
            $(getCodeFirst).prop('disabled', true);
        }
    });

    var inputs = classForm + ' [data-required]';
    $(inputs).on('change keyup', function () {
        var disabled = false;

        $.each($(inputs), function (i, v) {
            var self = $(v);

            if (self.attr('type') === 'checkbox' && !self.is(':checked') || !self.val()) {
                disabled = true;

                return false;
            }
        });

        $(button).prop('disabled', disabled);
    });

    $(classForm + ' .reloadCaptcha').click(function () {
        $(classForm).find('.whiteBlock').show();
        $.getJSON('reload_captcha.php', function (data) {
            $(classForm).find('.captchaImg').attr('src', '/bitrix/tools/captcha.php?captcha_sid=' + data);
            $(classForm).find('.captchaSid').val(data);
            $(classForm).find('.whiteBlock').hide();
        });
        return false;
    });

    function getCode() {
        if (!$(phoneCls).length) {
            phoneCls = phoneRegCls;
        }
        var $item = $(phoneCls).parents('.form-field');

        if ($(phoneCls).val()) {
            $(phoneCls).removeClass('has-error');
            $item.find('.error-message').remove();
            formData = $item.parents('form').serialize();
            sendSmsCode();
        } else {
            if (!$(phoneCls).val()) {
                $(phoneCls).addClass('has-error');
                label = $item.find('.field-label').text();
            }
        }
    }

    function sendSmsCode() {
        $.ajax({
            url: '/api/sms_code/',
            type: 'POST',
            data: formData,
            cache: false,
            dataType: 'json',
            success: function (data) {
                console.log(data);
                if (data.error === 0) {
                    if ($(getCodeFirst).length) {
                        $(getCodeFirst).parents('.form-row').empty();
                        $(getCodeCls).parents('.form-row').removeAttr('hidden');
                    }
                    $(ifSentCode).removeAttr('hidden');
                    $(getCodeCls).attr('hidden', '');
                    runTimer();
                }
                $(getCodeFirst).removeClass('active');
                $(getCodeCls).removeClass('active');
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                console.log(['ERRORS: ' + textStatus, errorThrown].join('|'));
                console.log(jqXHR);
            },
            complete: function () {}
        });
    }

    function runTimer() {
        var timer2 = $(timerCls).data('timer'),
                timer = timer2.split(':'),
                minutes = parseInt(timer[0], 10),
                seconds = parseInt(timer[1], 10);

        var interval = setInterval(function () {
            --seconds;
            minutes = (seconds < 0) ? --minutes : minutes;
            if (minutes < 0) {
                clearInterval(interval);
                $(getCodeCls).removeAttr('hidden');
                $(timerCls).text('1:00');
                $(ifSentCode).attr('hidden', '');
            } else {
                seconds = (seconds < 0) ? 59 : ((seconds < 10) ? '0' + seconds : seconds);

                value = minutes + ':' + seconds;
                $(timerCls).html(value);
                timer2 = value;
            }
        }, 1000);
    }
});


<?

define('STOP_STATISTICS', true);
define("NO_KEEP_STATISTIC", true);
define("NO_AGENT_CHECK", true);
define('PUBLIC_AJAX_MODE', true);
require_once($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php");
$GLOBALS['APPLICATION']->RestartBuffer();
?>

<?
$request = \Bitrix\Main\Application::getInstance()->getContext()->getRequest();
if ($request->getPost("is_regform")) {
    $data = $request->getPost("REGISTER");
    $phone = $data['LOGIN'];
} else {
    $phone = $request->getPost("USER_LOGIN");
}

$auth = new MySms($phone, $request->getPost("is_regform"));
$auth->sendSms();
$auth->result();
?>

<? require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/epilog_after.php"); ?>
<?

class MySms {

    private $phone;
    private $code;
    public $message;
    private $userData = '';
    private $updateUserCode;
    private $activeUser = false;
    public $userId;
    private $result = ['error' => 1];
    public $isReg = false;

    public function __construct($phone, $register = '') {
        $this->phone = preg_replace('/[^0-9]/', '', $phone);
        $this->code = rand(1000, 9999);
        $this->isReg = $register;
        $this->initUserData();
//        $this->sendSms();
    }

    private function initUserData() {
        $rsUser = CUser::GetByLogin($this->phone);
        if (($arUser = $rsUser->Fetch()) && !$this->isReg) {
            if ($arUser['ACTIVE'] === 'Y') {
                $this->activeUser = true;
                $this->userData = $arUser;
                $this->userId = $arUser['ID'];
                $this->updateUserCode();
            }
        } elseif ($this->isReg) {
            $this->updateUserCode = $this->activeUser = true;
            $_SESSION['CONFIRM_CODE'] = $this->code;
        }
    }

    private function updateUserCode() {
        $user = new CUser;
        $this->updateUserCode = $user->Update($this->userId, array("CONFIRM_CODE" => $this->code));
    }

    public function sendSms() {
        if ($this->updateUserCode && $this->activeUser) {
            $sms = new SendSMS();
            $this->result['error'] = $sms->sendSMS($this->phone, 'Ваш пароль для входа: ' . $this->code);
        } else {
            $this->result['text'] = 'Пользователь неактивирован';
        }
        __log($this, false, '/log/sms.log');
    }

    public function result() {
        echo json_encode($this->result);
    }

}
var emptyFunction = function () {

};

function MyForm(s, e) {

    this.ready = false;
    this.$container = {};
    this.selector = typeof s === 'string' ? s : '';
    this.errorScope = [];

    // construct events
    if (typeof e !== 'object') {
        e = {};
    }
    this.events = {
        onSubmit: typeof e.onSubmit === 'function' ? e.onSubmit : emptyFunction,
        onResetErrors: typeof e.onResetErrors === 'function' ? e.onResetErrors : emptyFunction,
        onRequiredIsEmpty: typeof e.onRequiredIsEmpty === 'function' ? e.onRequiredIsEmpty : emptyFunction,
        onFail: typeof e.onFail === 'function' ? e.onFail : emptyFunction,
        onReady: typeof e.onReady === 'function' ? e.onReady : emptyFunction,
        onInputFocus: typeof e.onInputFocus === 'function' ? e.onInputFocus : emptyFunction
    };

    // construct form
    var myForm = this;
    if (jQuery && $(myForm.selector).length) {
        myForm.ready = true;
        myForm.$container = $(myForm.selector);

        // delegate events
        myForm.$container.on('submit', function (jEvents) {
            // get data from form
            var formData = myForm.$container.serialize(),
                formAction = myForm.$container.prop('action'),
                hasError = false;

            jEvents.preventDefault();

            // очищаем старый ошибки
            if (myForm.errorScope.length) {
                myForm.$container.find('[data-form-error]').remove();

                myForm.errorScope.forEach(function (item) {
                    $(item).parent().removeClass('has-error')
                });

                myForm.events.onResetErrors(myForm.errorScope);
                myForm.errorScope = [];
            }

            // проверяем обязательные поля
            myForm.$container.find('input[data-required]').each(function () {
                if (!$(this).val().length) {
                    hasError = true;
                    myForm.pushError(this);
                }
            });

            // не допускаем к срабатыванию submit
            if (hasError) {

                myForm.errorScope.forEach(function (item) {
                    $(item).parent().addClass('has-error')
                });

                myForm.events.onRequiredIsEmpty(myForm.errorScope);
                return false;
            }

            return myForm.events.onSubmit(
                myForm.$container,
                formAction,
                formData
            );
        });
        myForm.$container.on('click', 'input', function () {
            //myForm.events.onInputFocus(this);
            var $scope = $(this).parent();
            if($scope.hasClass('has-error')) {
                $scope.removeClass('has-error');
                $scope.find('[data-form-error]').remove();
            }
        });

        myForm.events.onReady(myForm.$container);
    } else {
        myForm.events.onFail();
    }
}

MyForm.prototype.isReady = function () {
    return this.ready;
};

MyForm.prototype.pushError = function (el, text) {
    var self = this,
        errorText = text || $(el).data('errorText');
    self.errorScope.push(el);
    $(el).parent().append(
        self.constructErrorDom(errorText)
    );
};

MyForm.prototype.constructErrorDom = function (errorText) {
    var result = 'Поле обязательно к заполнению';
    if (typeof errorText === 'string' && errorText.length) {
        result = errorText;
    }
    return $('<div class="error" data-form-error>' +
        '<div class="error-content">' + result + '</div>' +
        '</div>');
};

以上是关于javascript Bitrix Mail使用验证码和短信发送的主要内容,如果未能解决你的问题,请参考以下文章

text IsAdmin_bitrix

php 带索引的bitrix搜索

php API Bitrix的$ DB查询

php bitrix,form.result.new

php [bitrix disk] #crm

php bitrix-php磁盘