fastadmin后端+uniapp前端 微信小程序授权登录新

@[TOC]微信小程序授权登录thinkphp fastadmin

fastadmin后端+uniapp前端 微信小程序授权登录新

今天需要写一个微信授权登录的小程序端的方法

申请APPID和APPSERCERT

在微信小程序后台开发与服务->开发管理开发者ID,复制AppID(小程序ID),点击生成生成AppSecret(小程序密钥)。

前端代码

前端使用vue2.0

<template>
  <view class="container">
    <button @click="onLogin" class="login-btn">微信授权登录</button>
  </view>
</template>

javascript代码 唤起授权登录

<script>
export default {
  data() {
    return {
      userInfo: null
    };
  },
  methods: {
	reg(code,userInfo){
		console.log(userInfo.avatarUrl);
		//return false;
	
		console.log(userInfo);

		// 请求例子
		this.$api.wxlogin({
			code:code,
			avatarUrl:userInfo.avatarUrl,
			nickName:userInfo.nickName,
		}).then(res => {
			console.log(res);
		    if(res.code == 1){
		    	uni.setStorageSync('token',res.data.userinfo.token);
				this.$tools.msg('授权登录成功');
		    	this.$tools.switchGo('/pages/index/index');
		    }else {
				this.$tools.msg(res.msg);
				return false;
		    }
		}).catch(err => {
		
		});
	},
    onLogin() {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          if (res.code) {
            // 登录成功,获取 code,可用于后续换取用户唯一标识
            console.log('登录成功,code:', res.code);
            // 获取用户信息
            uni.getUserInfo({
              provider: 'weixin',
              success: (infoRes) => {
                this.userInfo = infoRes.userInfo;
                console.log('用户信息:', this.userInfo);
				this.reg(res.code,this.userInfo);
                // 这里可以将用户信息和 code 发送到后端进行处理
              },
              fail: (err) => {
                console.log('获取用户信息失败:', err);
              }
            });
          } else {
            console.log('登录失败:', res.errMsg);
          }
        },
        fail: (err) => {
          console.log('登录失败:', err);
        }
      });
    }
  }
};
</script>

CSS代码 简单修饰一下 按钮

<style scoped>
.container {
	background-size: 100%;
	    background-color: #121212;
	    min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-btn {
  background-color: #141b23;
  color:#fff;
  border-radius: 40px;
  height:40px;
  line-height: 40px;
  width:80vw;
}
</style>    

后端处理登录代码:

public function login()
    {
        // 获取前端传来的 code 和用户信息
        $code = $this->request->post('code');
        //$userInfo = $this->request->post('userInfo');
        $avatarUrl = $this->request->post('avatarUrl');
        $nickName = $this->request->post('nickName');
        if (!$code) {
            return json(['code' => 0, 'msg' => '缺少必要参数']);
        }

        // 通过 code 获取微信用户唯一标识 openid
        $appid = Config::get('site.wx_app_id');
        $secret = Config::get('site.wx_app_sercert');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $result = file_get_contents($url);
        $result = json_decode($result, true);


        if (isset($result['errcode'])) {
            return json(['code' => 0, 'msg' => '获取 openid 失败']);
        }

        $openid = $result['openid'];

        // 查询数据库中是否存在该 openid 的用户
        $user = Db::name('user')->where('openid', $openid)->find();
        $salt='';
        if (!$user) {
            // 用户未注册,进行注册操作
            $res=$this->auth->wxregister($nickName,$avatarUrl,$openid,$salt);
            if ($res) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Sign up successful'), $data);
            }
            
        }else{
             $ret = $this->auth->direct($user['id']);
             if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Sign up successful'), $data);
            }
        }

    }

图片演示

1.获取code
在这里插入图片描述
2.注册成功之后是这样的

code: 1
data: {userinfo: {id: 5, username: "wx_pAalV1EKXRCg", nickname: "微信用户", mobile: "",}}
userinfo: {id: 5, username: "wx_pAalV1EKXRCg", nickname: "微信用户", mobile: "",}
avatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
createtime: 1744522612
expires_in: 2592000
expiretime: 1747114612
id: 5
mobile: ""
nickname: "微信用户"
score: 0
token: "4a6e0fa8-505d-4a4b-b8f2-f4b913a3b434"
user_id: 5
username: "wx_pAalV1EKXRCg"
msg: "Sign up successful"
time: "1744522612"
至此微信授权登录就完成了 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值