小程序模板:专业的小程序模板与静态模板分享平台
小程序
教程
搜索
当前位置 : 首页> 小程序教程> UniApp + UniCloud 实现微信小程序静默登录

UniApp + UniCloud 实现微信小程序静默登录

1. 环境配置

// manifest.json 微信配置
"mp-weixin": {
  "appid": "wx1234567890",
  "cloud": true, // 开启云开发
  "requiredPrivateInfos": ["login"]
}

// uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json
{
  "passwordSecret": "your-secret-key",
  "mp-weixin": {
    "appid": "wx1234567890",
    "appsecret": "your-app-secret"
  }
}

2. 数据库设计

创建 uni-id-users 集合结构:

{
  "bsonType": "object",
  "required": ["wx_openid"],
  "properties": {
    "wx_openid": {"bsonType": "string"},
    "wx_unionid": {"bsonType": "string"},
    "session_key": {"bsonType": "string"},
    "last_login": {"bsonType": "timestamp"}
  }
}

3. 前端静默登录逻辑

// utils/auth.js
export default {
  async silentLogin() {
    try {
      // 获取微信code
      const { code } = await uni.login({ provider: 'weixin' })
      
      // 调用云函数
      const { result } = await uniCloud.callFunction({
        name: 'uni-id-co',
        data: {
          action: 'loginByWeixin',
          params: { code }
        }
      })
      
      // 存储登录态
      uni.setStorageSync('uni_id_token', result.token)
      uni.setStorageSync('uni_id_token_expired', result.tokenExpired)
      
      return result
    } catch (e) {
      console.error('登录失败:', e)
      throw e
    }
  }
}

4. 云函数处理(基于uni-id)

// uniCloud/cloudfunctions/uni-id-co/index.js
const uniID = require('uni-id-common')
exports.main = async (event) => {
  const uniIDIns = uniID.createInstance({ context: event.context })
  
  switch (event.action) {
    case 'loginByWeixin':
      const { code } = event.params
      const { uid, userInfo, token, tokenExpired } = await uniIDIns.loginByWeixin({
        code,
        needUserInfo: false // 静默模式不获取用户信息
      })
      
      // 更新最后登录时间
      await db.collection('uni-id-users').doc(uid).update({
        last_login: Date.now()
      })
      
      return { uid, token, tokenExpired }
  }
}


联系客服 意见反馈

签到成功!

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

知道了