# 微信 H5 获取用户头像昵称(前端接入指南) ## 一、目标 在微信内打开 H5 页面,获取用户: - 昵称(nickname) - 头像(headimgurl) - openid --- ## 二、核心方案 使用微信网页授权(OAuth2): - 必须使用:`snsapi_userinfo` - 才能获取头像 + 昵称 --- ## 三、整体流程 ``` 用户进入页面 ↓ 判断是否有 code ↓ 没有 → 跳微信授权 ↓ 用户同意授权 ↓ 微信回调(带 code) ↓ 前端把 code 传给后端 ↓ 后端换 token + 获取用户信息 ↓ 返回前端 ``` --- ## 四、前端代码(可直接用) ### 1️⃣ 获取 code 并跳授权 ```js const getCode = () => { const params = new URLSearchParams(window.location.search); return params.get("code"); }; const redirectToWxAuth = () => { const appid = "你的appid"; const redirectUri = encodeURIComponent(window.location.href); const url = `https://open.weixin.qq.com/connect/oauth2/authorize ?appid=${appid} &redirect_uri=${redirectUri} &response_type=code &scope=snsapi_userinfo &state=123#wechat_redirect`; window.location.href = url; }; // 执行 const code = getCode(); if (!code) { redirectToWxAuth(); } ``` --- ### 2️⃣ 拿 code 调后端 ```js const code = new URLSearchParams(location.search).get("code"); if (code) { fetch(`/api/wx/userinfo?code=${code}`) .then(res => res.json()) .then(data => { console.log("用户信息", data); // data.nickname // data.headimgurl }); } ``` --- ## 五、后端要做什么(你只需要对接) 前端只需要知道: ```http GET /api/wx/userinfo?code=xxx ``` 后端返回: ```json { "openid": "xxx", "nickname": "张三", "headimgurl": "https://xxx.jpg" } ``` --- ## 六、重要配置(必须) ### 1️⃣ 微信后台配置 在公众号后台: - 设置 → 开发 → 网页授权域名 - 填你的 H5 域名(必须) --- ### 2️⃣ 必须在微信内打开 ```js const isWechat = /micromessenger/i.test(navigator.userAgent); if (!isWechat) { alert("请在微信中打开"); } ``` --- ## 七、常见坑 ### ❗1. redirect_uri 报错 原因:域名没配置 --- ### ❗2. 一直循环授权 原因:没有正确判断 code --- ### ❗3. 拿不到头像昵称 原因:用了 `snsapi_base` --- ### ❗4. 页面刷新重复授权 解决:拿到 code 后清掉 ```js window.history.replaceState({}, "", location.pathname); ``` --- ## 八、优化建议(推荐) ### ✔️ 第一次 - 用 `snsapi_userinfo` - 获取完整用户信息 ### ✔️ 后续 - 用 `snsapi_base` - 用 openid 换你自己的用户数据 --- ## 九、适用范围 | 场景 | 是否可用 | |------|----------| | 微信内 H5 | ✅ | | 小程序 | ❌ | | 浏览器打开 | ❌ | --- ## 十、一句话总结 👉 想拿头像昵称: 必须走 **微信授权 + snsapi_userinfo + 后端换数据** --- ## 完