laravel 手机短信 验证码登录
<?php
namespace App\Http\Controllers\M\Member;
use App\Library\Common;
use App\Library\Sms;
use App\Library\Util;
use App\Library\Y;
use App\Models\Area;
use App\Models\Company\Company;
use App\Models\EmailCode;
use App\Models\Member\Member;
use App\Models\Member\MemberConnect;
use App\Models\SmsCode;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
class IndexController extends Controller
{
//
protected function guard()
{
return Auth::guard('member');
}
/**
* 手机登录
* @param Request $request
* @return mixed
*/
public function mobile_login(Request $request){
$current_name = '手机登录';
$menu = 'member';
if($request->isMethod('post'))
{
$phone = trim($request->get('phone'));
$code = trim($request->get('code'));
//判断手机验证码是否正确
$phoneCode = SmsCode::where(['phone' => $phone])->where(['code' => $code])->where(['type' => 'login'])->where(['status' => 1])->where('created_at', '>', date("Y-m-d H:i:s", strtotime("-10 minute")))->first();
if (!$phoneCode) {
return Y::error('手机短信验证码不正确!', ["code" => "VERIFY_ERROR"]);
}
$member = Member::where('phone','=',$phone)->first();
if(!$member){
return Y::error('手机号码没有注册!');
}
$this->guard()->login($member);
//$this->guard()->loginUsingId($member->id);
return Y::success('登录成功!' ,["code"=>"SUCCESS"]);
}else{
return view('new_m.index.mobile_login', compact('current_name', 'menu'));
}
}
*/
public function send_phone_login_code(Request $request){
$phone = $request->get('phone');
if (!Util::isMobile($phone)) {
return Y::error('手机号码验证失败!', ["code" => "ERROR_FORMAT"]);
}
//判断手机是否注册过
$member = Member::where('phone', '=', $phone)->first();
if(!$member){
return Y::error('手机号码还没注册,请先注册!');
}
//判断数据库是否有3分钟内没验证的code
$smsCode = SmsCode::where(['phone' => $phone])->where(['status' => 1])->where('type','=','login')->where('created_at', '>', date("Y-m-d H:i:s", strtotime("-3 minute")))->take(1)->orderBy('id', 'desc')->get();
if (!$smsCode->isEmpty()) {
return Y::error('请不要重复发送!', ["code" => "ERROR_REPEAT"]);
}
$ip = $request->getClientIp();
//1个ip 一天只能发送获取10次
if(Common::verifySmsCount($ip) >20){
return Y::error('您当天累计已发送20次!', ["code" => "ERROR_REPEAT"]);
}
//生成6位code,保存email code表
$code = mt_rand(100000, 999999);
$data = array(
'phone' => $phone,
'code' => $code,
'type' => 'login',
'status' => 1,
'ip'=> $ip
);
$createData = SmsCode::create($data);
if (!$createData) {
return Y::error('发送失败,请联系管理员!', ["code" => "ERROR_CREATE"]);
}
$msg['code'] = $code;
$template = 'bs_login';
Sms::sendSms($phone, $msg, $template);
return Y::success('发送短信成功!请查收!', ["code" => "SUCCESS"]);
}
}
阿里短信-适用Laravel、Yii、Thinkphp等任何PHP项目
安装composer require flc/dysms
<?php
namespace App\Library;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
class Sms
{
//发短信
public static function sendSms($mobile,$msg,$template='buy_register')
{
$config = [
'accessKeyId' => config('app.sms.AccessKeyId'),
'accessKeySecret' => config('app.sms.AccessKeySecret')
];
$template = config('app.sms.template')[$template];
$client = new Client($config);
$sendSms = new SendSms();
$sendSms->setPhoneNumbers($mobile);
$sendSms->setSignName(config('app.sms.Signature'));
$sendSms->setTemplateCode($template);
$sendSms->setTemplateParam($msg);
$sendSms->setOutId('demo');
return $client->execute($sendSms);
}
}
config app.php 配置文件
<?php return [ 'sms' => [ 'AccessKeyId' => 'BLTAI4KRPdEZTPNIuCl', 'AccessKeySecret' => 'PYNzU78mnNVBoPLORxDmtBAJzGNdfX8', 'Signature' => '一览网', 'template' => [ 'bs_login'=> 'SMS_204287763', 'bs_register'=> 'SMS_204440138' ] ], ];
php view模板
@extends('new_m.base')
@section('content')
<form id="login_form" action="{{route('m.mobile_login')}}" method="post">
@csrf
<div class="m_block">
<ul>
<li>
<input name="phone" id="phone" type="text" class="line-input" placeholder="请输入手机号码" autocomplete="off">
</li>
<li>
<input name="code" id="code" type="text" class="line-input" placeholder="请输入短信验证码" autocomplete="off"><input type="button" class="yzm" id="sendPhoneLoginCode" value="获取验证码">
</li>
</ul>
</div>
<div class="m_block_btn">
<button type="button" class="submit_btn" onclick="javascript:mobile_login();">登录</button>
</div>
</form>
@endsection
JS处理
// 定时器
var wait = 180;
get_code_time = function (o) {
if (wait == 0) {
o.removeAttribute("disabled");
o.value = "获取验证码";
wait = 180;
} else {
o.setAttribute("disabled", true);
o.value = "(" + wait + ")秒后重新获取";
wait--;
setTimeout(function () {
get_code_time(o)
}, 1000)
}
};
/**
* 短信登录
* @returns {boolean}
*/
function mobile_login() {
var phone = $.trim($("#phone").val());
var code = $.trim($("#code").val());
if (isPhoneNo(phone) == false) {
$("#phone").focus();
layer.msg('请输入合法的号码');
return false;
}
if (code.length != 6){
$("#code").focus();
layer.msg('请输入正确的验证码');
return false;
}
$.ajax({
url: $("#login_form").attr('action'),
data: $("#login_form").serializeArray(),
type: 'post',
cache: false,
dataType: 'json',
success: function (data) {
if(data.code == 0){
layer.msg(data.msg, {
time: 1000, end: function () {
window.location.href = '/member/index';
}
});
}else{
layer.msg(data.msg);
return false;
}
},
error: function () {
layer.msg('系统异常,请联系客服人员!');
}
});
}
$("#sendPhoneLoginCode").click(function(){
var phone = $.trim($("#phone").val());
var _token = $("input[name='_token']").val();
var o = this;
if (isPhoneNo(phone) == false) {
$("#phone").focus();
layer.msg('请输入合法的号码');
return false;
}
//发送验证码
$.ajax({
url: "/users/send_phone_login_code",
data: { "_token": _token, "phone": phone},
type: "post",
dataType: 'json',
success:function (data) {
if(data.code == 0){
get_code_time(o);
}
layer.msg(data.msg);
},
error:function (data) {
layer.msg(data.msg);
}
});
});
发送短信sql
CREATE TABLE `c_sms_codes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `phone` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '' COMMENT '验证邮件', `code` char(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '' COMMENT '验证码', `ip` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '', `status` tinyint(4) NULL DEFAULT 1 COMMENT '0已验证 1 未验证', `type` char(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '' COMMENT '类型', `created_at` timestamp(0) NULL DEFAULT NULL, `updated_at` timestamp(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '手机验证验证码' ROW_FORMAT = Dynamic;