小程序效果
代码
<view class='content'>
<form bindsubmit="formSubmit">
<view class='phone-box'>
<text class='phone'>手机号</text>
<input name="phone" type='number' placeholder="请输入手机号" maxlength='11' name="phone" class='number' bindinput='lovePhone' />
</view>
<view class='phone-box'>
<text class='phone'>验证码</text>
<input name="phoneCode" placeholder="请输入验证码" class='number' placeholder-style='color:#bbb' bindinput="yanLoveInput" />
<view bindtap='yanLoveBtn' class='getNum'>{{getText2}}</view>
</view>
<button formType="submit" class='submit'>登录</button>
</form>
</view>
js
// pages/login/login.js
Page({
/**
* 页面的初始数据
*/
data: {
// 验证手机号
loginPhone: false,
loginPwd: false,
loveChange: true,
hongyzphone: '',
// 验证码是否正确
zhengLove: true,
huoLove: '',
getText2: '获取验证码',
},
// 手机验证
lovePhone: function (e) {
let phone = e.detail.value;
this.setData({
hongyzphone: phone
})
},
// 验证码按钮
yanLoveBtn: function () {
let loveChange = this.data.loveChange;
let lovePhone = this.data.lovePhone;
let phone = this.data.hongyzphone;
let res = this.phoneCkeck(phone)
if (!res) {
return false
}
let n = 59;
let that = this;
//获取验证码接口写在这里
wx: wx.request({
url: 'http://www.teacherapi.com/api/code',
data: {
phone: phone
},
success: (result) => {
console.log(result)
if (result.data.code == 200) {
this.setData({
huoLove: result.data.data
})
wx.showToast({
title: '验证码发送成功',
icon: 'success',
duration: 1000
})
//开始倒计时
let lovetime = setInterval(function () {
let str = '(' + n + ')' + '重新获取'
that.setData({
getText2: str
})
if (n <= 0) {
that.setData({
loveChange: true,
getText2: '重新获取'
})
clearInterval(lovetime);
}
n--;
}, 1000);
}
},
})
},
phoneCkeck(phone) {
// 验证手机号不能为空
if (phone.length == 0) {
wx.showToast({
title: '手机号不能为空',
icon: 'none',
duration: 1000
})
return false;
}
// 验证手机号格式
if (!(/^1[34578]\d{9}$/.test(phone))) {
wx.showToast({
title: '手机号格式错误',
icon: 'none',
duration: 1000
})
return false;
}
return true;
},
codeCheck(code) {
let reg = /^[0-9]\d{3}$/;
// 验证码不能为空 纯数字
if (code.length == 0) {
wx.showToast({
title: '验证码不能为空',
icon: 'none',
duration: 1000
})
return false;
}
if (!reg.test(code)) {
wx.showToast({
title: '验证码格式不正确',
icon: 'none',
duration: 1000
})
return false;
}
//长度不能小于4位
if (code.length < 4) {
wx.showToast({
title: '验证码格式不正确',
icon: 'none',
duration: 1000
})
return false;
}
return true;
},
//form表单提交
formSubmit(e) {
let val = e.detail.value
var phone = val.phone //电话
var phoneCode = val.phoneCode //验证码
// 验证验证码格式
var codechecks = this.codeCheck(phoneCode);
var bool = this.phoneCkeck(phone);
if (!codechecks) {
if (!bool) {
return false;
}
return false;
}
// 携带手机号码和验证码到后端验证验证码是否正确
wx: wx.request({
//
url: 'http://www.teacherapi.com/api/getphone',
method: 'post',
data: {
phone,
phoneCode
},
success: (result) => {
console.log(result)
if (result.data.code == 200) {
wx.showToast({
title: '登录成功',
icon: 'success',
duration: 1000
});
wx.setStorage({
data: result.data.data.tel,
key: 'user_tel',
})
wx.switchTab({
url: '/pages/personal_center/personal_center?tel=' + result.data.data.tel,
})
} else {
wx.showToast({
title: result.data.msg,
icon: 'none',
duration: 1000
})
}
},
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//判断如果缓存中有登录信息直接跳转到个人中心页
wx.getStorage({
key: 'user_tel',
success: function (res) {
if (res.data) {
wx.switchTab({
url: '/pages/personal_center/personal_center?user_tel=' + res.data,
})
}
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
json
{
"navigationBarTitleText": "授权登录",
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#3478F7",
"navigationBarTextStyle": "white",
"enablePullDownRefresh": true
}
css
.content {
width: 100%;
height: auto;
padding: 0 50rpx;
box-sizing: border-box;
}
.phone-box {
width: 100%;
height: 89rpx;
border-bottom: 1rpx solid #efefef;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
}
.phone {
color: #333;
margin-right: 60rpx;
font-size: 28rpx;
}
.number {
color: #333;
font-size: 28rpx;
width: 200rpx;
}
.getNum {
width:210rpx;
height:48rpx;
background:#3478F7;
border-radius:8rpx;
font-size:28rpx;
font-family:PingFang-SC-Medium;
color:rgba(255, 255, 255, 1);
line-height:48rpx;
margin-right:36rpx;
text-align:center;
}
.submit {
width: 480rpx;
height: 80rpx;
background:#3478F7;
border-radius: 8rpx;
margin-top: 80rpx;
color: #fff;
font-size: 32rpx;
}
laravel8
用到了这几个(Aliyun封装的阿里云的短信接口)
<?php
namespace App\Common\Lib;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
class Aliyun extends Model
{
//阿里云短信接口(装置composer sdk)
public static function sendCode($phone,$code){
if(empty($phone || empty($code))){
return false;
}
AlibabaCloud::accessKeyClient("LTA???1R","glS46nEh?????GIxP")
->regionId("cn-hangzhou")
->asDefaultClient();
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
// ->scheme('https') // https | http
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host("dy??pi.a??uncs.com")
->options([
'query' => [
'PhoneNumbers' => $phone,
'SignName' =>"??商城",
'TemplateCode' =>"SMS_213744714",
'TemplateParam'=>json_encode(['code'=>$code])
],
])
->request();
Log::info($result->toArray());
} catch (ClientException $e) {
Log::error( $e->getErrorMessage() . PHP_EOL );
return false;
} catch (ServerException $e) {
Log::error( $e->getErrorMessage() . PHP_EOL );
return false;
}
if(isset($result['Code']) && $result['Code'] == "OK"){
return true;
}
}
}
控制器层
<?php
namespace App\Http\Controllers;
use App\Common\Lib\Aliyun;
use App\Http\Controllers\Controller;
use App\Models\AdminUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Cache;
class CodeController extends Controller
{
/**
* 接收手机号发送验证码
* @return string
*/
public function index(Request $request)
{
$phone = $request->get('phone');//接受传递的手机号
if (empty($phone)) return json_encode(['code'=>403,'msg'=>'手机号不能为空','data'=>[]]);
//生成4位验证码
$code = rand(1111,9999);
//调用发送短信的接口
$res = Aliyun::sendCode($phone,$code);
//将验证码存入缓存里(缓存时间)
Cache::put('make'.$phone,$code,6000);
if ($res) return json_encode(['code'=>200,'msg'=>'发送验证码成功','data'=>$code]);
}
/**
* 用户第一次使用手机号注册
*/
public function login(Request $request)
{
$phone = $request->get('phone');//接受传递的手机号
$code = $request->get('phoneCode');//接受传递的验证码
//验证没有测试哦 自己写下哦~~~
// $validator = Validator::make($request->all(), [
// 'tel' => 'required|regex:/^1[3456789][0-9]{9}$/',
// ]);
// // 验证失败 输出错误信息
// if ($validator) return json_encode(['code'=>500,'msg'=>$validator->getError(),'data'=>null]);
// 取出缓存里面存的验证码
$codes = Cache::get('make'.$phone);
// 跟发过来的验证码作对比
if($code!=$codes) return json_encode(['code'=>403,'msg'=>'验证码错误','data'=>null]);
//查询表中手机号是否有记录,如果有那么就直接告知用户登录成功
$getPhone = AdminUsers::getPhone($phone);
if(!empty($getPhone))return json_encode(['code'=>200,'msg'=>'用户已注册','data'=>$getPhone]);
//验证码通过后给用户一个默认的用户名密码
$data=[
'username'=>'教师'.rand(11111,99999),
'password'=>md5('root'),
'head_portrait'=>'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1031084171,3750714591&fm=26&gp=0.jpg',
'tel'=>$phone
];
//调用模型层方法插入用户数据
$user = AdminUsers::setUsers($data);
if($user){
return json_encode(['code'=>200,'msg'=>'注册成功','data'=>$user]);
}
return json_encode(['code'=>403,'msg'=>'注册失败','data'=>null]);
}
/**
* 用户登录接口
* @param Request $request
*/
public function getLogin(Request $request)
{
$phone = $request->get('phone');//接受传递的手机号
if(empty($phone))return json_encode(['code'=>403,'msg'=>'手机号不能为空','data'=>null]);
//调用模型层查询用户数据(根据手机号获取用户信息)
$getUser = AdminUsers::getPhone($phone);
if (empty($getUser)) return json_encode(['code'=>403,'msg'=>'该用户不存在','data'=>null]);
//处理手机号
$getUser['tel'] = substr_replace($getUser['tel'], '****', 3, 4);
return json_encode(['code'=>200,'msg'=>'登录成功','data'=>$getUser]);
}
}
models层
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class AdminUsers extends Model
{
use HasFactory;
protected $guarded=[];//设置黑名单
/**
* 根据手机号获取用户信息
* @param $phone
* @return array
*/
public static function getPhone($phone)
{
if (empty($phone))return [];
return self::where('tel',$phone)->first();
}
/**
* 该手机没有的话就创建一条用户信息
* @param $phone
* @return array
*/
public static function setUsers($data)
{
if (empty($data))return [];
return self::create($data);
}
}
Laravel8路由配置不一样哦(想了解可以查看官网)
接下来记得配置路由i
撒花~~~~~
结束!!!