Files
wx-h5-demo/README.md

41 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# wx-h5-demo · 独立示例 H5(小程序授权 / 跳转)
> 独立二级目录项目,由 box_app 挂载到 `/wx-h5-demo`(即 `https://mp.yizhezhe.com/wx-h5-demo/`)。
> 配套说明:`docs/h5-miniprogram-auth.md`。
## 两种场景
| 场景 | 流程 | 用到的小程序页 |
| --- | --- | --- |
| **场景1** | 微信(浏览器)打开 H5 链接 → 跳**小程序授权页**授权 → 授权后小程序用 web-view 加载本 H5(结果在 URL)→ “回到 H5” | `miniapp/scenario1-auth-bridge.*`(授权桥页) |
| **场景2** | 微信跳到**小程序 web-view 的 H5 应用** → H5 `postMessage` 请求授权 → 宿主弹原生授权面板 → 授权 → 更新 `web-view src`(带结果)→ H5 重载显示 | `miniapp/scenario2-host-page.*`(web-view 宿主页) |
> 说明:场景2 的宿主页 `scenario2-host-page` 同时是场景1 授权后 redirectTo 的落地页(从 `globalData` 读结果拼 H5 url)。
## 文件
```
wx-h5-demo/
├─ index.html # 示例 H5(自包含):环境检测(webview/微信浏览器/纯浏览器)、
│ # 场景1 跳小程序授权 或 场景2 postMessage 授权、读回传参数展示。
├─ miniapp/
│ ├─ scenario1-auth-bridge.wxml/.js # 场景1 小程序授权桥页(launch-weapp/URL Scheme 进入)
│ └─ scenario2-host-page.wxml/.js # 场景2 web-view 宿主页(也作场景1 落地页)
└─ README.md
```
## 怎么做
1. **H5**:改 `index.html`(H5 地址 = `https://mp.yizhezhe.com/wx-h5-demo/`)。
2. **小程序端**:把 `miniapp/*` 的两个页面代码并入你的小程序(如 CRMEB),改 3 处:
- `app.globalData.openid`(登录态)。
- `H5_BASE` 指向你的 H5。
- `https://YOUR_API/phone|avatar`(或注释里说明;手机号 `code`→后端换明文;头像需上传换正式地址)。
3. **入口**:
- 场景2:宿主页已用 `<web-view src="{{url}}">` 加载 H5,H5 点「在 web-view 里请求授权」即可。
- 场景1:H5 点「去小程序授权」→ 需给 `jumpToMiniAuth()` 配一个**小程序 URL Scheme**(后端用 appid+path 换)或把页面放进公众号/env 用 `<wx-open-launch-weapp path="/pages/demo/auth">`。
## 注意
- 手机号:前端只拿 `code`,**明文必须后端** `wx.business.getuserphonenumber` 换(旧 `code2Session`+解密已收紧)。
- 头像:`e.detail.avatarUrl` 是临时 URL,需 `wx.uploadFile` 上传存后端,回传正式地址。
- `getUserProfile` 已废弃(匿名);用 `getPhoneNumber` / `<input type="nickname">` / `chooseAvatar`。
- 身份:保留 `openid`(query);授权结果走 **hash**(`#phone/nickname/avatar`,微信 webview 丢 query 不丢 hash)。
- 纯浏览器打开 `index.html`:仅 UI 演示(有降级提示),无法真授权。