微信小程序获取用户信息(纯前端)

特别说明

2022年10月25日起,小程序 wx.getUserProfile 接口将被收回

微信官方不希望开发者直接拿用户的昵称和头像,若小程序需要设置昵称和头像,可以单独开发一个设置页,由用户手动选择是否使用微信的头像和昵称


本文只说明纯前端的作法,有服务端的可查看 微信小程序获取用户信息(含服务端)

获取 openid

1、 页面加载时,调用 wx.login() 获取 code
2、通过 code 向微信后台发送请求获取用户的 openid

const appid = '';
const secret = '';
wx.login({
  success: ({ code }) => {
    // 微信服务地址
    let url =
      'https://api.weixin.qq.com/sns/jscode2session?appid=' +
      appid +
      '&secret=' + secret + '&js_code=' +
      code + '&grant_type=authorization_code';

    wx.request({
      url,
      success: result => {
        const { openid } = result.data;
        console.log(openid);
      },
      fail(err) {
        console.log(err.message);
      }
    })

  }
});

一般情况是通过 code 请求服务端,服务端调用微信服务后拿到 openid 返回给前端,因为调用微信服务需要用到 appid 和 appSecret,放在后端会更安全。

获取用户信息

使用 wx.getUserProfile() 获取除 openid 外的用户信息。
(2021-04-28 后 wx.getUserInfo() 只能获取默认昵称和头像,详见:接口调整说明)

特别说明

  • 需在页面产生事件后直接调用
  • 该 API 不支持在事件中使用异步操作
  • 若无需 openid,可不调用 wx.login()
<button bindtap="getUserProfile"></button>

getUserProfile() {
  // 调用 wx.getUserProfile 前不能有其他异步操作
  wx.getUserProfile({
    desc: "完善用户信息",
    success: (infoRes) => {
      const { userInfo } = infoRes;
      console.log(JSON.stringify(userInfo, null, 2));
    }
  });
}

获取结果如下:
在这里插入图片描述

以前若只需显示头像和昵称无需存储,可直接使用 <open-data> ,但 2022-02-21 后微信小程序平台回收了改能力,详情见: 公告

完整示例 (uni-app)

<template>
	<view class="app">
		<view class="imgDiv">
			<image :src="userInfo.avatarUrl"></image>
		</view>
		<view>{{userInfo.nickName}}</view>
		<button @click="getUserProfile">
			微信登录
		</button>
	</view>
</template>

<script>
	const config = {
		appid: 'xxxxxx',
		appSecret: 'xxxxxx'
	}
	export default {
		data() {
			return {
				userInfo: {}
			}
		},
		onLoad() {
			this.getOpenId();
		},
		methods: {
			getUserProfile() {
				wx.getUserProfile({
					desc: "完善用户信息",
					success: (infoRes) => {
						const { userInfo } = infoRes;
						this.userInfo = userInfo;
						console.log(JSON.stringify(userInfo, null, 2));
					}
				});
			},
			async getOpenId() {
				const { appid, appSecret } = config;
				const { code } = await wx.login();
				// 微信服务地址
				let url =
					'https://api.weixin.qq.com/sns/jscode2session?appid=' +
					appid +
					'&secret=' + appSecret + '&js_code=' +
					code + '&grant_type=authorization_code';

				uni.request({
					url,
					success: result => {
						const { openid } = result.data;
						console.log('openid', openid);
					},
					fail(err) {
						console.log(err.message)
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.app {
		text-align: center;
		padding: 20px;
	}

	.imgDiv {
		width: 200rpx;
		height: 200rpx;
		margin: 50px auto;

		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}
</style>

由于不能在 getUserProfile() 里先执行 wx.login() 再调用 wx.getUserProfile() (原因见上述特别说明) ,故一进来就调用 wx.login()

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值