微信小程序短信验证登录

首先小程序wxml页面

<!--pages/logins/logins.wxml-->
<view class="container">
  <view class="title">登录</view>
  <form catchsubmit="login">
    <view class="inputView">
      <input class="inputText" placeholder="请输入手机号" name="phone" bindblur="phone" />
    </view>
    <view class="inputView">
      <input class="inputText" placeholder="请输入验证码" name="code" bindblur="sms" />
      <button class="line" disabled="{{disabled}}" size="mini" bindtap="sendcode">{{codebtn}}</button>
    </view>
    <view class="loginBtnView">
      <button class="loginBtn" type="primary" formType="submit">登录</button>
    </view>
  </form>
</view>

wxss样式

.container { 
  display: flex;  
  flex-direction: column; 
  padding: 0; 
 } 
 .inputView { 
  line-height: 45px; 
  border-bottom:1px solid #999999;
 } 
.title{
  width: 80%;
  font-weight: bold;
  font-size: 30px;
}
 .inputText { 
  display: inline-block; 
  line-height: 45px; 
  padding-left: 10px; 
  margin-top: 11px;
  color: #cccccc; 
  font-size: 14px;
 } 
 
 .line {
  border: 1px solid #ccc;
  border-radius: 20px; 
  float: right; 
  margin-top: 9px;
  color: #cccccc;
 } 
 .loginBtn { 
  margin-top: 40px; 
  border-radius:10px;
 }

js页面书写

// pages/my/my.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    code: '',
    codebtn:'发送验证码',
    disabled:false,
  },
  /**
   * 获取手机号并验证
   */
  phone(e){
    let phone =e.detail.value
    let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if(!reg.test(phone)){
      // 弹窗提示
      wx.showToast({
        title: '手机号码格式不正确',
        icon:"none",
        duration:2000
      })
      return false;
    }
    this.setData({phone:phone})
  },
  /**
   * 发送验证码
   */
  sendcode(){
    let phone = this.data.phone
    wx.request({
      url: 'http://www.exercise.com/login.php/phone', //仅为示例,并非真实的接口地址
      data: {
        phone:phone
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        console.log(res)
        // 发送验证码错误信息
        if(res.data.code==100){
          let info = res.data.msg
          wx.showToast({
            title: info,
            icon:"error"
          })
        }
        // 验证码发送成功提示
        if(res.code==200){
          wx.showToast({
            title: '验证码已发送,请注意接收',
            icon:"success"
          })
        }
        // 频繁点击提示
        if(res.code==100){
          wx.showToast({
            title: '点击频繁',
            icon:"error"
          })
        }
      }
    })
},
/**
 * 登录点击事件
 */
login(e){
  console.log(e.detail.value.code)
  let sms=e.detail.value.code
  let phone = e.detail.value.phone
  if(phone==""){
    wx.showToast({
      title: '手机号不能为空',
      icon:"error"
    })
  }
  if(sms==""){
    wx.showToast({
      title: '验证码不能为空',
      icon:"error"
    })
  }
  wx.request({
    url: 'http://www.exercise.com/login.php/sms', //仅为示例,并非真实的接口地址
    data: {
      sms:sms,
      phone:phone
    },
    header: {
      'content-type': 'application/json' // 默认值
    },
    success:(e)=>{
      // 登录失败返回错误提示
      if(e.data.code==100){
        let info = e.data.msg
        wx.showToast({
          title: info,
          icon:"error"
        })
      }
      // 登陆成功跳转页面
      if(e.data.code==200){
        wx.switchTab({
          url: '/pages/list/list',
        })
      }
    }
  })
},
})

后端代码

发送短信验证码见(1条消息) 腾讯云短信发送php_呀哈的博客-CSDN博客_php发送腾讯云短信icon-default.png?t=M1L8https://blog.csdn.net/weixin_43321108/article/details/122139533?spm=1001.2014.3001.5501

 控制器层

/**
     * 发送短信验证码
     * @param Request $request
     * @return \think\response\Json|void
     */
    public function sendSms(Request $request){
        $phone=$request->get('phone');
        // 生成随机验证码
        $code=rand(00000,9999);
        if (Cache::get("$phone"."_time")){
            return fail('发送次数频繁');
        }
//        $res=SendSms::sendInfo($code,$phone);
        // 将验证码放入缓存
        Cache::set("$phone"."_code","$code",300);
        // 缓存验证码发送时间
        Cache::set("$phone"."_time",time(),60);
        return success($code);
    }

    /**
     * 验证短信
     * @param Request $request
     * @return \think\response\Json|void
     */
    public function smsLogin(Request $request){
        $sms=$request->get('sms');
        $phone=$request->get('phone');
        $code=Cache::get("$phone"."_code");
        $info=LoginBusiness::sms($code,$sms);
        if (!empty($info)){
            return fail($info);
        }
        Login::addUserByPhone($phone);
        return success($phone);
    }

business逻辑层

<?php

namespace app\login\business;

class SendSms
{
    public static function sendInfo($code,$phone){
        $app_id = config('sms.app_id');
        $app_key = config('sms.app_key');
        $template_id = config('sms.template_id');
        $sms_sign = config('sms.sms_sign');

        try {
            $sender = new \Qcloud\Sms\SmsSingleSender($app_id, $app_key);
            $params = [$code];
            $result = $sender->sendWithParam("86", $phone, $template_id,
                $params, $sms_sign, "", "");  // 签名参数未提供或者为空时,会使用默认签名发送短信
            $rsp = json_decode($result);
            if ($rsp->result == 0) {//0代表成功
                return '发送成功';
            }
            \think\facade\Log::error('发送短信验证码失败:' . $result);
        } catch (\Exception $e) {
        }
        return '发送失败';
    }


}

posted @   哎呀呀哈  阅读(59)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示