微信小程序手机号+授权登录

wxml页面

<view class="input-container">
    <view class="input-button-container row-center">
        <view class="input-hint">手机号</view>
        <input class="input flex1" model:value="{{ phoneNumber }}"  type="number" maxlength="11" placeholder="请输入手机号" bindinput="inputChange" bindblur="phone" />
    </view>
    <view class="divider"></view>
    <view class="input-button-container row-center">
        <view class="input-hint">短信验证码</view>
        <input class="input flex1" model:value="{{ messageCode }}" type="number" maxlength="6" placeholder="请输入验证码"
            bindinput="inputChange" bindblur="codePhone" />
        <view class="code-button" bindtap="sendMessage">{{waitingCode?waiteTime:'发送验证码'}}{{waitingCode?'s':''}}
        </view>
    </view>
    <view class="divider"></view>
</view>

<button class="login-button" disabled="{{!confirmable}}"
    style="background:{{confirmable?'#0B7BFBFF':'#D8D8D8'}};color:white"
    bindtap="onConfirm">确认</button>

<button bindtap="login">微信授权登录</button>

js

// pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
 //按钮是否可用
 confirmable: false,
 //发送短信等待中
 waitingCode: false,
 waiteTime: 0,
 interval: -1, //计时器
 phoneNumber: "",
 messageCode: "",
 nickName:'',
 avatarUrl:''
    // phone:'',
    // codephone:''
  },
  // phone(e){
  //   var phone=e.detail.value
  //   this.setData({
  //     phone:phone
  //   })
  // },
  // codePhone(e){
  //   var codephone=e.detail.value
  //   this.setData({
  //     codephone:codephone
  //   })
  // },
  inputChange() {
    this.setData({
        confirmable: !this.isEmpty(this.data.phoneNumber) && !this.isEmpty(this.data.messageCode)
    })
},

isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else {
        return false;
    }
},
sendMessage() {
  
  var url=getApp().globalData.url;
  var url=url+"api/codephone"
  //正在等待

  if(this.data.waitingCode) {
      return
  }
  
  if (this.data.phoneNumber == '') {
      wx.showToast({
          title: '请先填写手机号',
      })
      return
  }

  wx.showLoading({
      title: '正在发送短信',
  })
  
  let that = this
  wx.request({
      url: url,
      data: {
          mobile: this.data.phoneNumber,
      },
      success: function(res) {
        console.log(res)
      wx.hideLoading()
      wx.showToast({
          title: '发送短信成功',
      })
      that.setData({
          waitingCode: true,
          waiteTime: 60,
                  //设置倒计时60秒,每秒触发一次,拿到interval用于关闭
          interval: setInterval(function (res) {
              if (that.data.waiteTime > 0) {
                  that.setData({
                      waiteTime: --that.data.waiteTime
                  })
              } else {
                      //注意关闭定时器
                that.clearMessage()
               that.setData({
                  waitingCode: false,
                  waiteTime: 0
              })
          }
      }, 1000)
  })
      }
  })
},

//关闭定时器
clearMessage() {
  clearInterval(this.data.interval)
  this.setData({
      waitingCode: false,
      waiteTime: 0,
      interval: -1
  })
},

onConfirm(e) {
  var url=getApp().globalData.url;
  var url=url+"api/matephone"
  let that = this
  wx.request({
      url: url,
      data: {
          mobile: this.data.phoneNumber,
          code: this.data.messageCode
      },
      success: function(res) {
        console.log(res)
        if(res.data.code==0){
          wx.showToast({
            title: res.data.msg,
            icon:"none"
          })
          wx.switchTab({
            url: '/pages/lists/lists',
          })
        }

        if(res.data.code==1){
          wx.showToast({
            title: res.data.msg,
            icon:"none"
          })
        }
          
      }
  })
},

login(){
  wx.getUserProfile({
    desc:"获取当前页面信息",
    success:function(e){
      console.log(e)
      var avatarUrl=e.userInfo.avatarUrl;
      var nickName=e.userInfo.nickName;
      var gender=e.userInfo.gender;
      wx.login({
        success:function(res){
          var codes=res.code
          var url=getApp().globalData.url;
          var url=url+"api/impowerlogin";
          wx.request({
            url: url,
            data:{
              avatarUrl,
              nickName,
              gender,
              codes
            },
            method:"POST",
            header:{'content-type':'application/x-www-form-urlencoded'},
            success:function(e){
              var token=e.data.data;
              wx.setStorageSync('token', token)
            }
          })
        }

      })
    }
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

控制器方法手机号验证码+60秒倒计时

    */
    public function CodePhone(Request $request)
    {
        if (time()-Cache::get('time')<60){
            return  json_encode(['code'=>1,'msg'=>'1分钟之内不能重复发送验证码']);
        }

        $phones=$request->get('mobile');
        $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );
        $smsapi = "http://api.smsbao.com/";
        $user = "*****"; //短信平台帐号
        $pass = md5("****"); //短信平台密码
        $rand=rand(1000,9999);
        $time=time();
        Cache::put('time',$time);
        Cache::put('code',$rand);
        $content = "测试验证码".$rand;//要发送的短信内容
        $phone = "$phones";//要发送短信的手机号码
        $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
        $result = file_get_contents($sendurl);
        if (!$result){
            return json_encode(['code'=>1,'msg'=>$statusStr[$result]]);
        }
        return  json_encode(['code'=>0,'msg'=>'发送成功']);
    }

    /**
     * 匹配手机号和验证码是否相等
     * @param Request $request
     * @return false|\Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|string
     */
    public function matePhone(Request $request)
    {
        $data=$request->all();

        $validator = Validator::make($data, [
            'code' => 'required',
            'mobile' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect('post/create')
                ->withErrors($validator)
                ->withInput();
        }
        $matePhone=CodePhone::matePhone($data['mobile']);
        if (!$matePhone){
            return  json_encode(['code'=>1,'msg'=>'手机号错误或不存在']);
        }
        if ($data['code']!=Cache::get('code')){
            return  json_encode(['code'=>1,'msg'=>'验证码错误']);
        }
        return  json_encode(['code'=>0,'msg'=>'登录成功']);
    }

控制器小程序授权登录

/**
     * 微信授权登录
     * @param Request $request
     * @return false|\Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|string
     */
    public function impowerLogin(Request $request)
    {
        $data=$request->all();
        $validator = Validator::make($data, [
            'codes' => 'required',
            'avatarUrl' => 'required',
            'nickName' => 'required',
            'gender' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect('post/create')
                ->withErrors($validator)
                ->withInput();
        }
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=wx053ae920bf4b2a00&secret=c55bd9edf5b61292defc1d6e53695f74&js_code=".$data['codes']."&grant_type=authorization_code";
        $res=Common::geturl($url);
        $arr=[
            'openid'=>$res['openid'],
            'nickname'=>$data['nickName'],
            'avatarurl'=>$data['avatarUrl'],
            'gender'=>$data['gender'],
            'session_key'=>$res['session_key'],
        ];
        $openid=CodePhone::where('openid',$arr['openid'])->first();
        $token=Common::createToken($openid['id']);
        if ($openid){
            $update=CodePhone::where('openid',$arr['openid'])->update(['session_key'=>$arr['session_key']]);
            if ($update){
                return  json_encode(['code'=>0,'msg'=>'已有账户,欢迎再次登录','data'=>$token]);
            }
        }else{
            $res=CodePhone::create($arr);
            if ($res){
                return  json_encode(['code'=>0,'msg'=>'登录成功','data'=>$data]);
            }
        }
    }

解析code码 拿到session_key,openid

<?php
namespace App\Common;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

class Common
{
    /**
     * 解析code
     * 得到session_key,openid
     * @param $url
     * @return mixed
     */
    public static function geturl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }
    
    public static function createToken($uid = null)
    {
        $signer = new Sha256();//加密规则
        $time = time();//当前时间

        $token = (new Builder())
            ->issuedBy('teacher')//签发人
            ->canOnlyBeUsedBy('student')//接收人
            ->identifiedBy('MarsLei', true) //标题id
            ->issuedAt($time)//发出令牌的时间
            ->canOnlyBeUsedAfter($time) //生效时间(即时生效)
            ->expiresAt($time + 3600) //过期时间
            ->with('uid', $uid) //用户id
            ->sign($signer, 'my') //签名
            ->getToken(); //得到token
        return (string)$token;
    }

    public static function verifyToken($token=null){
        //检测是否接收到了token
        if(empty($token)){
            return 0;
        }
        //转化为可以验证的token
        $token = (new Parser())->parse((string) $token);
        //验证基本设置
        $data = new ValidationData();
        $data->setIssuer('teacher');
        $data->setAudience('student');
        $data->setId('MarsLei');

        if(!$token->validate($data)){
            return 0;
        }
        //验证签名
        $signer = new Sha256();
        if(!$token->verify($signer, 'my')){
            return 0;
        }
        //验证通过,返回用户id
        return $token->getClaim('uid');
    }



}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值