【uniapp】unicloud云开发获取token 一键登录

无论是用微信开发者工具还是uniapp开发小程序,基本上所有情况之下,登录是必不可少的。

简洁明了,直接开始

1.个人资料的获取

现在通过 uni.getUserProfile 获取的个人信息基本上回返回 灰色头像及" 微信用户",要想获得用户的微信头像和昵称,我们可以换个方法(这里但指头像和昵称,不含性别等其他)

头像

<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="width: 120rpx;">
  <view class="avatar" style="width: 120rpx; height: 120rpx; margin-left: -30rpx;">
    <image class="avatar-img" :src="avatarUrl" style="width: 100%; height: 100%;"></image>
  </view>
</button>
		data() {
			return {
				
				avatarUrl:"",
				 nickName: '' ,
				UserInfo:[],
			};
		},



   //选择头像函数
 onChooseAvatar(e) {
					console.log('微信头像信息', e)
			        // 将数据赋值
					const { avatarUrl } = e.detail 
					this.avatarUrl = avatarUrl
				},

昵称

   <view class="">
	   	  <input type="nickname"  placeholder="获取昵称"  @focus="onNicknameInput"/>
	   </view>

onNicknameInput 函数是为了获取到微信的昵称并保存,它和获取到的头像

2.关联unicloud ,并创建一个名为 user 的表

详细教程移步

https://blog.csdn.net/qq_40531408/article/details/126068789

3.创建login云函数

'use strict';
 
//小程序的AppID 和 AppSecret
const appid = "********************"
const secret = "********************"
// 创建user数据表实例
const db = uniCloud.database()

const user = db.collection('user')//你的表名
 
// 生成token和校验token公共模块
const {getToken,verifyToken} = require('wx-common')
 
exports.main = async (event, context) => {
 
    //获取用户openid和session_key
	const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
		method: 'GET',
		data: {
			appid: appid,
			secret: secret,
			js_code: event.code,// 客户端传递过来的code
			grant_type: 'authorization_code'
		},
		dataType: 'json'
	})
    //判断请求用户openid和session_key是否成功
	if (res.status === 200) {
        //成功返回的openid和session_key
		const wx_openid = res.data.openid
		const wx_session_key = res.data.session_key
		// 生成token
		const token = getToken(wx_openid)
        //查询数据库判断用户是否已经注册 根据openid查找
		const res_user = await user.where({
			openid: wx_openid
		}).get()
        //用户未注册存储用户信息
		if (res_user.data && res_user.data.length === 0) {
			user.add({
				avatarUrl: event.userinfo.avatarUrl,
				nickName: event.userinfo.nickName,
				gender: event.userinfo.gender,
				openid: wx_openid,
				session_key: wx_session_key,
				mobile:"",
				token:token
			})
		} else {
        //用户已经存在更新token和session_key
			user.where({
				openid: wx_openid
			}).update({
				session_key: wx_session_key,
				token:token
			})
		}
        //将需要的个人信息返回到客户端例如:头像 昵称 等
		return user.where({
			openid: wx_openid
		}).field({
			avatarUrl: true,
			gender: true,
			nickName: true,
			mobile:true,
			token:true,
		}).get()
 
	} else {
    //获取用户openid和session_key失败响应客户端
		return {
			msg: '获取微信服务失败',
			code: 500
		}
	}
};

4.在cloudfunctions目录下的common下新建新建公共模块wx-common

在wx-common目录下 npm i jsonwebtoken 下载依赖

下载后如图所示

5.在wx-common index.js 文件中

// 生成token方法
const jwt = require('jsonwebtoken')
 
// 密匙
const secret = '***'
 
//生成token
function getToken(value) {
	// sign(加密数据,加密辅助,过期时间(单位/s))
	return jwt.sign({value}, secret, {expiresIn: 10800});
}
//解密token
function verifyToken(token) {
	try {
		return jwt.verify(token,secret)
	}catch(e) {
		return false
	}
}
//导出方法
module.exports = {
	getToken,
	verifyToken
}

6.在需要使用公共模块的云函数右键管理公共模块或扩展依赖

点击确定并上传部署

7.新建login 页面

<template>
	<view>
<!--pages/about/about.wxml-->
<!-- 获取用户头像或昵称 -->
<view class="v1" style="margin-top: 100rpx;">
  <view class="v2" style="margin-top: 40rpx;">
<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="width: 120rpx;">
  <view class="avatar" style="width: 120rpx; height: 120rpx; margin-left: -30rpx;">
    <image class="avatar-img" :src="avatarUrl" style="width: 100%; height: 100%;"></image>
  </view>
</button>
    

    
    <view class="" style="margin-left: 150rpx; margin-top: 70rpx;display: flex;">
       <view class="" style="width: 100rpx;margin-top:36rpx ; margin-left: 11rpx;">
       	昵称
       </view>
	   <view class="">
	   	  <input type="nickname"  placeholder="获取昵称"  @focus="onNicknameInput"/>
	   </view>
    

      
    </view>
  
    <view class="denglu">
     <button open-type="getUserInfo" @getuserinfo="getUserInfo" >登录</button>
    
    </view>



   
  </view>
  </view>

 
</view>
			
	
	</view>
</template>
	// 
				onNicknameInput(e){ 
					console.log(e);
					this.nickName= e.detail.value
				},
				getUserInfo() {
					uni.showModal({
						title:"使用微信一键登录",
						showCancel:true,
						cancelColor:"#000000",
						confirmColor:"#42b983",
						success:(success) => {
							if(success.confirm) {
								uni.showLoading({
									title:'登录中...'
								})
								uni.getUserProfile({
									desc:'获取用户信息,进行登录',
									success: (res) => {
				                        //调用登录函数
										this.UserInfo=res.userInfo
										if(this.UserInfo.nickName=="微信用户")
										{ 
											this.UserInfo.nickName=this.nickName,
											this.UserInfo.avatarUrl=this.avatarUrl
										}
										if(this.UserInfo.nickName!="微信用户")
										{ 
											this.getLogin(this.UserInfo)
										}
										
									}
								})
							}
							if(success.cancel) {
								uni.showToast({
									title: '用户取消登录!',
									icon:'none',
									duration: 2000
								});
							}
							
							
						}
					})
				},
				// 微信登录
				getLogin(userInfo) {
					uni.login({
						provider:'weixin',
						success: (res) => {
							// 调用云函数
							uniCloud.callFunction({
								name:'login', // 云函数名称
								data:{ // 需要传递给云函数的参数
									userinfo:userInfo,
									code:res.code
								}
							}).then(ress => {
								console.log(ress);
								console.log();
				                //判断是否返回了用户数据
								if(ress.result.affectedDocs != 0) {
									console.log(ress.result.data);
				                    //存储用户信息
									
									// 存储token
									uni.setStorage({
										key:'Token',
										data:ress.result.data[0].token
									})
									// token
									// 设置默认的过期时长,例如3小时
									const defaultExpiresIn = 3 * 3600 * 1000;
									uni.setStorageSync("expiresIn", new Date().getTime() + defaultExpiresIn);
									uni.setStorage({
										key:'UserInfo',
										data:this.UserInfo
									})
									uni.showToast({
										title:'登录成功',
										icon:'none',
										duration: 2000
									});
									setTimeout(() => {
										// 跳转首页
										uni.switchTab({
											url:'/pages/first/first'
										})
									},2000)
								}else {
									uni.showToast({
										title:'登录失败',
										icon:'none',
										duration: 2000
									});
								}
								uni.hideLoading()
								
								
							}).catch(err => {
								console.log(err);
								uni.showToast({
									title:'登录失败',
									icon:'none',
									duration: 2000
								});
							})
						} 
					})
				},
						

 

在传递UserInfo对象时,我将获取到的灰色头像和统一昵称重新设置为获取的微信头像和昵称,这个方法看起来不大聪明的样子,但作为白白的我只能想到这个方法了(可怜兮兮)

  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,你需要在服务端编写一个登录接口,用于验证用户的账号密码是否正确,并返回一个 token。接口的实现方式可以使用任何一种后端语言实现,比如 PHP、Java、Python 等。 下面以 PHP 为例,展示一个简单的登录接口示例: ```php <?php // 获取 POST 请求中的账号和密码 $username = $_POST['username']; $password = $_POST['password']; // 进行登录验证,这里假设账号密码都是 admin if ($username === 'admin' && $password === '123456') { // 登录成功,生成 token $token = md5($username . $password . time()); $result = array('code' => 0, 'msg' => '登录成功', 'data' => array('token' => $token)); } else { // 登录失败 $result = array('code' => -1, 'msg' => '账号或密码错误', 'data' => array()); } // 返回 JSON 格式的结果 echo json_encode($result); ``` 在客户端中,你可以使用 uni.request 方法发送登录请求,示例代码如下: ```javascript uni.request({ url: 'http://example.com/login.php', method: 'POST', data: { username: 'admin', password: '123456' }, success: function(res) { if (res.data.code === 0) { // 登录成功,保存 token 到本地存储中 uni.setStorageSync('token', res.data.data.token); } else { // 登录失败,弹出错误提示框 uni.showToast({ title: res.data.msg, icon: 'none' }); } }, fail: function(err) { // 网络请求失败,弹出错误提示框 uni.showToast({ title: err.errMsg, icon: 'none' }); } }); ``` 在登录成功后,将服务器返回的 token 保存到本地存储中,以备后续请求接口时使用。注意,这里只是一个简单示例,实际应用中需要对用户的账号密码进行更加严格的验证,并采取一定的安全措施,以防止被攻击。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值