微信小程序 获取手机号登录

2021/7/9 12:06:58

本文主要是介绍微信小程序 获取手机号登录,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

微信小程序

login.wxml 页面

<button bindtap="getUserInfo" open-type="getUserInfoProFile">授权登录</button>
<button bindtap="getPhoneLogin">手机号登录</button>

login.js 授权登录

//授权登录
getUserInfo(e) {
    wx.getUserProfile({
      desc: 'desc',
      success: res => {
        // console.log(res)
        let userInfo = res.userInfo
        wx.login({
          success: even => {
            // console.log(even)
            let code = even.code
            wx.request({
              url: 'http://www.1902a.com/get_token',
              method: 'GET',
              data: {
                code,
                nickname: userInfo.nickName,
                avatar: userInfo.avatarUrl
              },
              success: res => {
                // console.log(res.data)
                let token = res.data.result
                wx.setStorageSync('token', token)
                if (res.data.errCode == 0) {
                  wx.navigateBack({
                    delta: 1,
                  })
                }
              }
            })
          }
        })
      }
    })
  },

PHP 后台

//获取token
    public function getToken()
    {
        $param = input();
        //获取小程序的code
        $code = $param['code'];
        // AppID:wxf13a256d46f75fe4
        // AppSecret:668a6e30a946616b2cd18d77d1da0b98
        $appid = 'AppID';
        $secret = 'AppSecret';
        //微信小程序授权的url
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        //请求回调
        $data = geturl($url);
        //获取用户信息
        $userInfo = User::where('openid',$data['openid'])->find();
        //如果为空进行创建新用户
        if(empty($userInfo)){
            $param['openid'] = $data['openid'];
            $param['session_key']=$data['session_key'];
            User::create($param,true);
        }
        //生成token
        $token = md5($data['openid'].rand(1,999999).date('Y-m-d',time()));

        //存入缓存
        Cache::set($token,$userInfo,7200);

        return checkJson($token);
    
    }

phone_login.wxml 手机号登录页面

<view class="container">
 <view class='row'>
   <input placeholder='请输入手机号' bindinput='bindPhoneInput'/> 
 </view>
 <view class='row'>
   <input placeholder='请输验证码' bindinput='bindCodeInput' style='width:70%;'/> 
   <button class='codeBtn' bindtap='getCode' >获取验证码</button>
 </view>
 <view>
   <button class='save' bindtap='save' >保存</button>
 </view>
</view>

phone_login.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    code: '',
  },
  //手机号输入
  bindPhoneInput(e) {
    // console.log(e.detail.value);
    var val = e.detail.value;
    this.setData({
      phone: val
    })
  },
  //获取短信验证码
  getCode(e) {
    let phone = this.data.phone
    console.log(phone)
    let str = /^1\d{10}$/
    if (phone.length !== 11) {
      wx.showToast({
        title: '手机号不正确',
        icon: 'error'
      })
      return false
    }
    if (!str.test(phone)) {
      wx.showToast({
        title: '手机号不正确',
        icon: 'error'
      })
      return false
    }
    wx.request({
      url: 'http://www.1902a.com/get_code?phone=' + phone,
      method: 'GET',
      success: res => {
        console.log(res.data.result)
      }
    })
  },

  //验证码输入
  bindCodeInput(e) {
    this.setData({
      code: e.detail.value
    })
  },
  save(){
    let phone = this.data.phone
    let str = /^1\d{10}$/
    if (phone.length !== 11) {
      wx.showToast({
        title: '手机号不正确',
        icon: 'error'
      })
      return false
    }
    if (!str.test(phone)) {
      wx.showToast({
        title: '手机号不正确',
        icon: 'error'
      })
      return false
    }
    console.log(phone)
    let phoneCode = this.data.code
    console.log(phoneCode)
    wx.request({
      url: 'http://www.1902a.com/phone_login',
      method:'POST',
      data:{
        phone,
        phoneCode
      },
      success:res=>{
        console.log(res.data.result)
        wx.setStorageSync('token', res.data.result)
        wx.navigateBack({
          delta: 2,
        })
      }
    })
  },
}

获取验证码

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

验证手机号与验证码是否正确

 public function phoneLogin()
    {
        $phone = input('phone');
        // print_r($phone);
        $chars = "/^1[34578]\d{9}$/";
        if(!preg_match($chars,$phone,$matches) || strlen($phone)!=11){
            return checkJson([],'手机号不正确','10001');
        }
        $phoneCode = input('phoneCode');
        // print_r($phoneCode);
        if($phoneCode!=Cache::get('phone_code') || empty($phoneCode)){
            return checkJson([],'验证码不正确','10002');
        }
        //获取用户信息
        $userInfo = User::where('phone',$phone)->find();
        //如果为空进行创建新用户
        if(empty($userInfo)){
            User::create([
                'phone' => $phone
            ]);
        }
        //生成token
        $token = md5($phone.rand(1,999999).date('Y-m-d',time()));

        //存入缓存
        Cache::set($token,$userInfo);

        return checkJson($token);
    }



这篇关于微信小程序 获取手机号登录的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程