> 技术文档 > uni-app 中开发微信小程序时,点击登录获取微信用户信息通常使用 uni.getUserProfile 或 uni.getUserInfo 接口

uni-app 中开发微信小程序时,点击登录获取微信用户信息通常使用 uni.getUserProfile 或 uni.getUserInfo 接口

在 uni-app 中开发微信小程序时,点击登录获取微信用户信息通常使用 uni.getUserProfileuni.getUserInfo 接口(推荐使用 uni.getUserProfile,官方已逐步弃用 uni.getUserInfo)。
uni-app 中开发微信小程序时,点击登录获取微信用户信息通常使用 uni.getUserProfile 或 uni.getUserInfo 接口

以下是完整的 获取微信用户信息的详细代码示例


✅ 1. 使用 uni.getUserProfile 获取用户信息(推荐)

📄 模板部分(

<template> <view class=\"container\"> <button @click=\"login\">点击登录并获取用户信息</button> <view v-if=\"userInfo\"> <image :src=\"userInfo.avatarUrl\" mode=\"aspectFill\"></image> <text>昵称:{{ userInfo.nickName }}</text> <text>性别:{{ userInfo.gender === 1 ? \'男\' : \'女\' }}</text> <text>城市:{{ userInfo.city }}</text> <text>省份:{{ userInfo.province }}</text> </view> </view></template>

⚙️ 脚本部分(

<script>export default { data() { return { userInfo: null, // 存储用户信息 }; }, methods: { async login() { try { // 请求获取用户信息 const { userInfo } = await uni.getUserProfile({ desc: \'用于完善用户资料\', // 声明获取用户个人信息后的用途 }); console.log(\'获取到的用户信息:\', userInfo); this.userInfo = userInfo; } catch (err) { console.error(\'获取用户信息失败:\', err); uni.showToast({ title: \'授权失败\', icon: \'none\' }); } } }};</script>

🎨 样式部分(

<style scoped>.container { padding: 20px;}image { width: 100px; height: 100px; border-radius: 50%;}</style>

✅ 2. 使用 uni.getUserInfo(旧版接口,不推荐)

虽然仍可使用,但官方建议迁移至 uni.getUserProfile。以下为兼容性写法:

uni.getUserInfo({ success: (res) => { console.log(\'用户信息:\', res.userInfo); this.userInfo = res.userInfo; }, fail: (err) => { console.error(\'获取用户信息失败:\', err); uni.showToast({ title: \'获取用户信息失败\', icon: \'none\' }); }});

🔐 注意事项

项目 说明 微信用户信息授权 需用户主动点击按钮触发,不能自动调用 安全机制 用户信息加密字段需通过后端解密(如需敏感数据) 授权弹窗 uni.getUserProfile 会自动弹出授权窗口 小程序 AppID 需配置合法域名或开启不校验合法域名(仅限开发环境)

📋 补充:用户信息字段说明(userInfo 对象)

字段名 类型 描述 nickName string 用户昵称 avatarUrl string 用户头像 URL gender number 性别:1男,2女,0未知 city string 城市 province string 省份 country string 国家 language string 语言版本

✅ 总结对比表

方法 是否推荐 是否需要用户授权 弹窗提示 备注 uni.getUserProfile ✅ 推荐 是 自动弹窗 支持最新微信授权流程 uni.getUserInfo ❌ 不推荐 是 不自动弹窗 已逐步废弃

如需进一步实现 登录凭证换取用户唯一标识(openid、unionid)后台解密用户敏感信息,请继续提问,我可以提供完整服务端 + 客户端交互方案。

物业知识详解