微信小程序获取用户头像和昵称一个开放接口是wx.getUserInfo,2021年4月5日被废弃,原因是很多开发者在打开小程序时就通过组件方式唤起getUserInfo弹窗,如果用户点击拒绝,无法使用小程序,这种做法打断了用户正常使用小程序的流程,同时也不利于小程序获取新用户,后面新添加的一个开放接口wx.getUserProfile,也是用于获取用户头像和昵称。
下面是调整公告
在这里插入图片描述
但如果我们现在再使用类似的方法时,往往无法得到自动获取用户头像昵称的效果。微信小程序开发现已不支持使用wx.getUserProfile 接口获取用户头像,同时也无法使用wx.getUserInfo 接口获取用户头像和昵称,因此在使用微信小程序获取头像昵称时,可能出现模拟器中成功但真机调试无法获取头像昵称的情况。

那么我们怎么获取呢?这时候就需要我们让用户自己手动授权微信头像昵称。

解决方案

  • 获取头像:需要将 button 组件 open-type 的值设置为 chooseAvatar,当用户选择需要使用的头像之后,可以通过 bindchooseavatar 事件回调获取到头像信息的临时路径。
<view class="avatarUrl">
	<button type="balanced" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
		<image :src="avatarUrl" class="refreshIcon"></image>
	</button>
</view>

在这里插入图片描述
用户可以选择微信头像,可以选择相册或者拍照。这里我给了默认头像。

  • 获取昵称:需要将 input 组件 type 的值设置为 nickname,当用户在此input进行输入时,键盘上方会展示微信昵称。
<view class="userName">
	<text>昵称:</text>
	<input :clearable="false" type="nickname" class="weui-input" :value="userName" @blur="bindblur"
		placeholder="请输入昵称" @input="bindinput" />
</view>

在这里插入图片描述

当用户获取输入框焦点的的时候,下方会弹出微信昵称,点击直接改变输入框内容,也可以自定义,这里我给了默认2到6个汉字。

因为我们获取到的头像地址是临时地址,所以拿到地址以后我们要将图片上传到自己的服务器上面。

下面是总体界面,界面可以自己随便改,最主要的就是button组件和input组件的type值

在这里插入图片描述
最后的最后,干货来了,直接贴代码,拿上直接用,只需要改一下图片上传地址就行。

<template>

	<view class="containar">
		<cu-custom bgColor="none" :isBack="false">
			<block slot="content"><span style="color: #333;font-weight: 400;">获取用户头像昵称</span></block>
		</cu-custom>


		<view class="avatarUrl">
			<button type="balanced" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
				<image :src="avatarUrl" class="refreshIcon"></image>
			</button>
		</view>
		<view class="userName">
			<text>昵称:</text>
			<input :clearable="false" type="nickname" class="weui-input" :value="userName" @blur="bindblur"
				placeholder="请输入昵称" @input="bindinput" />
		</view>

		<view style="width: 100%;height: 1px; background: #EEE;">

		</view>
		<view style="width: 700rpx; height: 20px; font-size: 13px; margin: auto; margin-top: 40rpx;">
			· 申请获取以下权限
		</view>
		<view style="width: 700rpx; height: 20px; font-size: 13px; margin: auto; color: #cbcbcb; margin-top: 25rpx;">
			· 获得你的信息(昵称、头像等)
		</view>

		<view class="btn">
			<u-button @click="onSubmit" type="primary">保存</u-button>
		</view>
	</view>
</template>
<script>
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools'
	import {
		uploadNameImg,
		uploadImg
	} from '@/api/owner-login.js';

	export default {
		data() {
			return {
				// 下面我都给了默认值,根据自己的需求可以决定需不需要默认值
				avatarUrl: 'https://youzhen123.oss-cn-huhehaote.aliyuncs.com/WechatOwnerProperty/images/mrtx.png',
				userName: this.getRandomName(Math.floor(Math.random() * (6 - 2) + 3))
			};
		},
		onLoad(option) {
			this.appUserId = option.appUserId
			console.log('option', option.appUserId);
		},
		onShow() {},
		methods: {
			bindblur(e) {
				this.userName = e.detail.value; // 获取微信昵称
			},
			bindinput(e) {
				this.userName = e.detail.value; // 获取微信昵称
			},
			onChooseavatar(e) {
				let self = this;
				let {
					avatarUrl
				} = e.detail;
				this.avatarUrl = avatarUrl
			},
			onSubmit() {
				var that = this
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						const name = that.userName
						// 判断头像以及昵称不为空 再上传
						if (that.userName && that.avatarUrl) {
								console.log(that.avatarUrl) // 返回的是零时图片地址
								// 这里是图片上传的方法,是我封装好的axios,到时候只需要请求自己的图片上传就OK,
								uploadImg({pic:that.avatarUrl}).then(resResult => {
									// 拿到自己服务器的图片地址保存就可以了
									that.avatarUrl = resResult.data
									that.save()
								})
						} else {
							uni.showToast({
								icon: 'none',
								title: '请上传头像并填写昵称'
							})
							return false;
						}
					},
					fail: function(err) {
						console.log('err', err);
					}
				})
			},

            /**
             * @description 保存事件,用于保存用户头像昵称
             * 
             * */

			save() {
				uni.showLoading({
					title: '加载中'
				});
				const data = {
					nickName: this.userName,
					headImgUrl: this.avatarUrl
				}
				uploadNameImg(data).then(res => {
					uni.reLaunch({
						url: '../index/index'
					});
				})
			},
            
            /**
             * @description 生成随机名字方法
             * */

			randomAccess(min, max) {
				return Math.floor(Math.random() * (min - max) + max)
			},

			decodeUnicode(str) {
				//Unicode显示方式是\u4e00
				str = "\\u" + str
				str = str.replace(/\\/g, "%");
				//转换中文
				str = unescape(str);
				//将其他受影响的转换回原来
				str = str.replace(/%/g, "\\");
				return str;
			},

			getRandomName(NameLength) {
				let name = ""
				for (let i = 0; i < NameLength; i++) {
					let unicodeNum = ""
					unicodeNum = this.randomAccess(0x4e00, 0x9fa5).toString(16)
					name += this.decodeUnicode(unicodeNum)
				}
				return name
			},
		}
	}
</script>
<style lang="scss" scoped>
	.containar {
		width: 100vw;
		height: 100vh;
		background: #fff;
		box-sizing: border-box;
		padding: 0 30rpx;

		.avatarUrl {
			padding: 80rpx 0 40rpx;
			background: #fff;

			button {
				background: #fff;
				line-height: 80rpx;
				height: auto;
				border: none !important;
				width: auto;
				// padding: 20rpx 30rpx;
				margin: 0;
				display: flex;
				border: none;
				justify-content: center;
				align-items: center;

				&::after {
					border: none;
				}

				.refreshIcon {
					width: 160rpx;
					height: 160rpx;
					border-radius: 50%;
					background-color: #ccc;
				}

				.jt {
					width: 14rpx;
					height: 28rpx;
				}
			}
		}

		.userName {
			background: #fff;
			padding: 20rpx 30rpx 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.weui-input {
				padding-left: 60rpx;
			}
		}

		.btn {
			margin-top: 30rpx;
		}
	}
</style>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐