小程序模板:专业的小程序模板与静态模板分享平台
小程序
教程
搜索
当前位置 : 首页> 小程序教程> uniapp微信小程序2024手机号快速验证及无感登录教程

uniapp微信小程序2024手机号快速验证及无感登录教程

WXML


手机号一键登录

js

getPhoneNumber(e) {
    console.log(e.detail.code) // 动态令牌
    let that = this;
    uni.request({
        url: 'https://******/api/mini_getuserphone.php',
        data: {
            phonecode: e.detail.code
        },
        method: 'POST',
        header: {
            'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
        },
        success: (res) = >{
            console.log(res.data.data) if (res.data.code == 100) {
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none'
                });

            } else if (res.data.code == 200) {
                //返回数据接收成功
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none'
                });
                var errcode = res.data.data['errcode'];
                if (errcode == 0) {
                    //登陆成功
                    var openids = res.data.data['phone_info']['phoneNumber'];
                    //注册事件
                    // 跳转事件
                    uni.setStorageSync('openid', openids);
                    //注册判断携带unionid
                    const unionid = uni.getStorageSync('unionid');

                    that.mini_userphoneregidst(openids, unionid);
                    setTimeout(function() {
                        // 调用全局MQTT连接函数,进行MQTT连接
                        getApp().check_account_mqtt_connect();
                        uni.switchTab({
                            url: '/pages/index/index'
                        });
                    },
                    1200);

                } else {
                    uni.showToast({
                        title: res.data.data['errmsg'],
                        icon: 'none'
                    });
                }

            }
        }
    })

},

后端

//mini_getuserphone.php
 100,
            'data' => '',
            'msg' => '请求出错!'
        ),480));
    } else {
        // 打印返回的内容
        $result=json_decode($data,true);
        if (array_key_exists("errcode",$result))
          {
        //   echo "键存在!";
       
         die(
        json_encode(
            array(
            'code' => 100,
            'data' => '',
            'msg' => '获取token失败!'.$result['errmsg']
        ),480));
        
          }
        else
          {
      //token获取成功 继续获取手机号
      $access_token=$result['access_token'];
      curl_close($curl);
      
      
    //   请求新的连接
$url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $access_token;

$data = array('code' => $phonecode); // 请确保$code变量已经定义

$options = array(
    'http' => array(
        'header' => "Content-Type: application/json\r\n",
        'method' => 'POST',
        'content' => json_encode($data)
    )
);

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

$result = json_decode($response, true);

          

        
    //   请求新的连接
    
         die(
        json_encode(
            array(
            'code' => 200,
            'data' => $result,
            'msg' => ''
        ),480));
          }
          
    }


          
} 
else {
            // 已被处理或者不存在 请求重新登陆
            die(
        json_encode(
            array(
            'code' => 100,
            'data' => '',
            'msg' => '非法操作'
        ),480)
);
        }
curl_close($curl);

无感登录

一键登录成功后,将openid记录到数据库,用户在点击收取按登陆前进行调用判断,可以省去一笔开支

onload事件

onShow() {
	// #ifdef MP-WEIXIN
	//小程序登录检测
	this.mini_login()
	// #endif

},

无感登录方法

mini_login() {
	let that = this;

	uni.login({
		provider: 'weixin',
		success: loginRes => {
			console.log(loginRes);
			that.code = loginRes.code;
			// 2. 将用户登录code传递到后台置换用户SessionKey、OpenId等信息
			uni.request({
				url: 'https://dcloud.taila.club/api/mini_login2.php', //仅为示例,并非真实接口地址。
				data: {
					code: loginRes.code
				},
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
				},
				success: (res) => {
					console.log(res.data);

					uni.hideLoading()
					if (res.data.code == 200) {
						//存取session
						uni.setStorageSync('unionid', res.data.data.openid);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});


						//判断逻辑
						that.pd_login(res.data.data.openid);


					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}


				}
			});


		},
		fail: () => {
			uni.showToast({
				title: '获取 code 失败',
				icon: 'none'
			});
		}
	});

},


登录判断

pd_login(unionid) {
	let that = this;
	uni.request({
		url: 'https://******/mini_login_check.php',
		data: {
			unionid: unionid
		},
		method: 'POST',
		header: {
			'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
		},
		success: (res) => {
			console.log(res.data)
			if (res.data.code == 201) {
				//unionid在数据库没有记录 记录就可以不需要操作
				console.log('unionid在数据库没有记录 记录就可以不需要操作')
			} else if (res.data.code == 200) {
				var openids = res.data.data;
				uni.showModal({
					title: '提示',
					content: '检测到该账户已授权是否直接登录?',
					success: function(res) {
						if (res.confirm) {
							//登陆成功 由于之前开发问题openid就是手机号、账号 ||unionid才是真真的openid
							uni.setStorageSync('openid', openids);
							uni.setStorageSync('unionid', unionid);
							// 调用全局MQTT连接函数,进行MQTT连接
							getApp()
								.check_account_mqtt_connect();
							uni.switchTab({
								url: '/pages/my/my'
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		}
	})
},


后端

 400,
            'msg' => '缺少参数'
        ),480)
);
} 

$unionid=$_POST['unionid'];
$sql="SELECT * FROM `user` WHERE `UnionID` = '$unionid'";
// 执行查询
$result = $conn->query($sql);


if ($roows=mysqli_fetch_assoc($result)) {
  //success
   // 查到数据直接返回手机号进行登录
 echo json_encode(array('code' => 200, 'msg' => '登陆成功', 'data' => $roows['openid']));
 
} else {
  //fail
  // 查不到数据
echo json_encode(array('code' => 201, 'msg' => '尚未注册', 'data' => ''));
}
 100,
            'data' => '',
            'msg' => '请求出错!'
        ),480));
    } else {
        // 打印返回的内容
        $result=json_decode($data,true);
        if (array_key_exists("errcode",$result))
          {
        //   echo "键存在!";
       
         die(
        json_encode(
            array(
            'code' => 100,
            'data' => '',
            'msg' => '获取token失败!'.$result['errmsg']
        ),480));
        
          }
        else
          {
        //   echo "键不存在!";
              // 开启redius
       
         //写入redius session_key名命的openid数据 默认存储2天
        curl_close($curl);
         die(
        json_encode(
            array(
            'code' => 200,
            'data' => $result,
            'msg' => '获取token成功'
        ),480));
          }
          
    }


          
} 
else {
            // 已被处理或者不存在 请求重新登陆
            die(
        json_encode(
            array(
            'code' => 100,
            'data' => '',
            'msg' => '非法操作'
        ),480)
);
        }

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了