微信小程序实现网站登录

需要的工具

  • HBuilder X
  • 微信开发者工具
  • 微信小程序账号
  • 服务器(这里推荐使用腾讯云服务器服务器首单2H2G一年45元,已经购买过的创建一个新账号即可,每个身份证可以创建5个账号购买链接:https://curl.qcloud.com/TknSK05u)

HBuilderX配置

打开HBuilder X 后点击工具->插件安装,安装下图插件

图片[1]-微信小程序实现网站登录-七彩云资源网
HBuilder X安装插件

配置小程序运行配置

HBuilder X 上方工具->设置->运行配置,找到小程序运行配置填写你微信小程序开发者工具安装地址

图片[2]-微信小程序实现网站登录-七彩云资源网

配置完成后点击文件->新建->项目,选择uniapp模板使用默认的即可

图片[3]-微信小程序实现网站登录-七彩云资源网
图片[4]-微信小程序实现网站登录-七彩云资源网

在编辑器左上方选择创建的项目,找到pages这个目录右键新建页面页面名称写Login

图片[5]-微信小程序实现网站登录-七彩云资源网
新建uniapp页面

在根目录找到pages.json文件修改“navigationBarTitleText”字段为登录保存,打开根目录的manifest.json文件找到微信小程序配置有一个微信小程序APPID设置里面写你的微信小程序appid

图片[6]-微信小程序实现网站登录-七彩云资源网
微信小程序appid配置

login.vue代码

<template>
	<view>
		<u-modal v-model="show" title="登录提示" content="确定使用当前账号授权登录吗?" show-cancel-button="true" @confirm="success"
			@cancel="error" confirm-text="确认授权" cancel-text="取消授权"></u-modal>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code:'',
				show:false
			}
		},
		onLoad(options){
			if(options.scene){
				var query = this.getRequestParameters(decodeURIComponent(options.scene))
			}else{
				var query = options
			}
			var openid = uni.getStorageSync('openid')
			this.code = query.code;
			if (this.code=='undefined') {
				uni.navigateBack();
			} else {
				if (openid == '') {
					this.Wxlogin();
				} else {
					this.show = true
				}
			}
		},
		methods: {
			getRequestParameters(params = "") {
				let theRequest = new Object();
				if (params != undefined) {
					let strs = params.split("&");
					for (let i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
					}
				}
				return theRequest;
			},
			Wxlogin(){
				var thia=this
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success:function(res){
						thia.code = data.code,
						uni.request({
							header:{
								'content-type': 'application/json;charset=UTF-8'
							},
							url: '',//获取用户信息接口
							data:{
								code:thia.code
							},
							method:'POST',
							success:function(res){
								thia.openid = res.data.data.openid
							}
						})
					}
				})
			},
			success(){
				var openid = uni.getStorageSync('openid')
				var thia = this
				uni.request({
					url: '',//授权接口
					method: 'POST',
					data: {
						code: thia.code,
						openid: openid,
						type: 'success'
					},
					success: (res) => {
						if(res.data.code == 204){
							uni.showToast({
								title: '二维码已失效',
								icon: 'error',
								duration: 2000
							})
						}else{
							uni.showToast({
								title: '授权成功',
								icon: 'success',
								duration: 2000
							})
						}
					},
			}
		},
		error(){
			var openid = uni.getStorageSync('openid')
			var thia = this
			uni.request({
				url: '',//授权接口
				method: 'POST',
				data: {
					code: thia.code,
					openid: thia.openid,
					type: 'error'
				},
				success: () => {
					uni.navigateTo({
						url: '../index/index'
					})
				}
			})
		}
	}
</script>

<style>

</style>

获取用户信息php代码

<?php
$code=$_POST['code'];
$userinfo=json_decode(file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid=微信小程序appid&secret=秘钥&js_code='.$code.'&grant_type=authorization_code'),true);
    $openid=$userinfo['openid'];
    $session=$userinfo['session_key'];
    if($openid==''){
        echo(json(201,array('msg'=>'获取失败')));
    }else{
        echo(json(200,array('openid'=>$openid,'session'=>$session)));
    }
?>

授权接口代码

<?php
include('config.php');
include('function.php');
$code = $data['code'];
$openid = $data['openid'];
$type = $data['type'];

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);


switch ($type) {
    case 'success':
        if($redis->get($code) !== 'null'){
            echo json(204,array('msg'=>'当前二维码已失效'));
        }else{
            $redis->set($code, $openid);
            $redis->expire($code, 300);
        }
        
        break;

    case 'error':
        $redis->set($code, 'error');
        $redis->expire($code, 100);
        break;
    case 'action':
        if ($redis->get($code) == 'null') {
            echo json(201, array('msg' => '用户未授权'));
        } elseif ($redis->get($code) == 'error') {
            echo json(202, array('msg' => '用户拒绝授权'));
        } elseif($redis->get($code)==''){
            echo json(203, array('msg' => '非法访问'));
        } else {
            unset($openid);
            $openid=$redis->get($code);
            $user = mysqli_query($db, "SELECT * FROM `user` WHERE `openid` = '$openid'");
            $info = mysqli_fetch_assoc($user);
            if (!$info) {
                printf("Error: %s\n", mysqli_error($db));
                exit();
            }
            $uuid=md5($openid.time());
            $userdata=base64_encode(json_encode(array('uid' => $info['id'], 'name' => $info['name'], 'user_img' => $info['user_img'], 'group' => $info['user_group'], 'condition' => $info['condition'],'token'=>$code)));
            $redis->set($uuid,$userdata);
            $redis->expire($uuid,86400);
            $redis->del($code);
            exit(json(200,array('uuid'=>$uuid)));

        }
        break;
}

获取小程序登录二维码代码

<?php
include('function.php');
$redis=new Redis();
$redis->connect('127.0.0.1',6379);
//获取access_token
$access_token=json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=微信小程序appid&secret=秘钥'),true);
$access_token=$access_token['access_token'];
$rand=rand(100000,9999999);
//获取小程序码
$data=array(
    'page'=>'pages/Login',
    'scene'=>"'code':'$rand'",
    'env_version'=>'develop',
    "check_path"=>false
    );
$qrcode=curl('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token,json_encode($data));
$file=fopen('./qrcode/'.$rand.'.jpg','w');
$qr=fwrite($file,$qrcode);
$redis->set($rand,'null');
$redis->expire($rand,300);
echo json_encode(array('code'=>200,'qrcode'=>'https://域名/api/qrcode/'.$rand.'.jpg','tokencode'=>$rand));
fastcgi_finish_request();
time_sleep_until(time()+300);
unlink('./qrcode/'.$rand.'.jpg');

网页端登录代码

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://www.qicaiy.cn/open/layer-v3.5.1/layer/layer.js"></script>
    <title>登录</title>
</head>

<body>
    <div class='qr'>
        <img src="" id="qrcode">
    </div>
    <script type="text/javascript">
        var token = ''
        $.ajax({
            url: 'http://域名/qrcode.php',//更换为你的域名
            method: 'GET',
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    document.getElementById('qrcode').setAttribute('src', res.qrcode);
                    token = res.tokencode
                    console.log(token);
                    login();
                } else {
                    layer.alert('获取登录二维码失败', { icon: 5 })
                }
            }
        })
        function login() {
            $.ajax({
                url: 'http://127.0.0.1/oauth.php',
                dataType: 'json',
                method: 'POST',
                data: {
                    type: 'action',
                    code: token
                },
                success: function (res) {
                    if (res.code == 200) {
                       layer.alert('登录成功,正在跳转!',{icon:1})
                    }else if (res.code == 203){
                        layer.alert('当前二维码已失效,请刷新页面重新获取',{icon: 5})
                        return;
                    }else if (res.code == 202){
                        layer.alert('已取消授权',{icon: 5})
                        return;
                    }
                    else {
                        setTimeout(function () {
                            login();
                        },3000)
                    }
                }
            })

        }

    </script>
</body>

</html>

演示视频暂时没有,小程序没提交微信审核上线,生成不存在的目录二维码接口有限制所以就在以前搞的时候测试过,当时没有录屏

© 版权声明
THE END
喜欢就支持一下吧
点赞16 分享
评论 共2条

请登录后发表评论