uni-app 中开发微信小程序时,点击登录获取微信用户信息通常使用 uni.getUserProfile 或 uni.getUserInfo 接口
在 uni-app 中开发微信小程序时,点击登录获取微信用户信息通常使用 uni.getUserProfile
或 uni.getUserInfo
接口(推荐使用 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
会自动弹出授权窗口📋 补充:用户信息字段说明(userInfo
对象)
nickName
avatarUrl
gender
city
province
country
language
✅ 总结对比表
uni.getUserProfile
uni.getUserInfo
如需进一步实现 登录凭证换取用户唯一标识(openid、unionid) 或 后台解密用户敏感信息,请继续提问,我可以提供完整服务端 + 客户端交互方案。