该问题请在专业群( uni-app 官方技术交流群 1 ) 咨询,群中有相关专业的管理员和群友。
在 uni-app 开发的微信小程序里,通过 web-view 加载 H5 页面时,H5 无法直接调用 wx.login 获取 code,因此必须由小程序端先拿到 code,再传给 H5。下面给出最稳妥、官方推荐的实现步骤,您可直接套用。
──────────────────
步骤 1:小程序端获取 code 并拼接到 web-view 的 URL
pages/index/index.vue(或承载 web-view 的页面)
<template>
<web-view :src="webUrl" @message="onMessage" />
</template>
<script>
export default {
data() {
return {
webUrl: ''
}
},
async onLoad() {
// 1. 获取微信登录凭证
const [err, res] = await uni.login({ provider: 'weixin' }).catch(e => [e, null])
if (err || !res.code) {
uni.showToast({ title: '获取 code 失败', icon: 'none' })
return
}
// 2. 把 code 作为参数拼到 H5 地址
// 注意:H5 域名必须配置在小程序后台「开发 → 开发设置 → 业务域名」
const h5Origin = 'https://xxx.com' // 您的 H5 域名
const h5Path = '/form.html' // 您的表单页面
this.webUrl = `${h5Origin}${h5Path}?code=${res.code}`
},
methods: {
// 可选:接收 H5 回传的数据
onMessage(e) {
console.log('收到 H5 消息:', e.detail.data)
}
}
}
</script>
──────────────────
步骤 2:H5 页面接收 code 并换取 openid
form.html(或对应的 H5 页面)
<script>
// 1. 从 URL 中取出 code
const code = new URLSearchParams(location.search).get('code')
if (!code) {
alert('缺少微信登录凭证')
}
// 2. 把 code 发给自己的后端,后端再去调微信接口
fetch('https://您的后端.com/api/wx-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
})
.then(r => r.json())
.then(res => {
// res.openid 即所需
console.log('openid:', res.openid)
// 3. 表单上传时把 openid 一并带上即可
})
.catch(console.error)
</script>
──────────────────
步骤 3:后端用 code 换取 openid(示例)
GET https://api.weixin.qq.com/sns/jscode2session
?appid=您的小程序 appid
&secret=您的小程序 secret
&js_code=前端传来的 code
&grant_type=authorization_code
返回 JSON 中的 openid 回传给前端即可。
──────────────────
注意事项
- web-view 的
src 域名必须配置在小程序后台「开发 → 开发设置 → 业务域名」。
- code 只能用一次,有效期 5 分钟;建议获取后立刻换 openid 并缓存。
- 如果 H5 有多页面跳转,可把 openid 存到
localStorage,避免反复带在 URL。
- 若仍需在 H5 内使用微信 JS-SDK(分享、拍照等),请再按 JS-SDK 文档 配置,但获取 code 仍推荐上述小程序端方式,避免 302 跳转被限制。
1 个回复
Ask小助手 - Ask社区AI助手
在 uni-app 开发的微信小程序里,通过 web-view 加载 H5 页面时,H5 无法直接调用
wx.login获取 code,因此必须由小程序端先拿到 code,再传给 H5。下面给出最稳妥、官方推荐的实现步骤,您可直接套用。──────────────────
步骤 1:小程序端获取 code 并拼接到 web-view 的 URL
pages/index/index.vue(或承载 web-view 的页面)
──────────────────
步骤 2:H5 页面接收 code 并换取 openid
form.html(或对应的 H5 页面)
──────────────────
步骤 3:后端用 code 换取 openid(示例)
返回 JSON 中的
openid回传给前端即可。──────────────────
注意事项
src域名必须配置在小程序后台「开发 → 开发设置 → 业务域名」。localStorage,避免反复带在 URL。要回复问题请先登录或注册
公告
更多>相关问题