34 lines
1.7 KiB
JavaScript
34 lines
1.7 KiB
JavaScript
// 场景1:授权桥页(H5 在微信浏览器 → 跳进本页 → 授权 → 回到 H5)
|
||
// 路径:/pages/demo/auth.js
|
||
// 入口:<wx-open-launch-weapp path="/pages/demo/auth"> 或 小程序 URL Scheme
|
||
// ⚠️ openid 由登录态/onLoad 取;授权结果放 globalData,webview 页再拼进 H5 url。
|
||
const app = getApp();
|
||
const H5_BASE = 'https://mp.yizhezhe.com/wx-h5-demo/'; // 示例 H5(独立二级目录项目)
|
||
|
||
Page({
|
||
data: { nickname: '', avatar: '' },
|
||
_phone: '', _nick: '', _avatar: '', _openid: '',
|
||
|
||
onLoad(q) { this._openid = q.openid || app.globalData.openid || 'YOUR_OPENID'; },
|
||
|
||
onPhone(e) {
|
||
if (e.detail.errMsg === 'getPhoneNumber:ok' && e.detail.code) {
|
||
wx.request({ url: 'https://YOUR_API/phone', method: 'POST', data: { code: e.detail.code },
|
||
success: r => { this._phone = r.data.phoneNumber; wx.showToast({ title: '已获取手机号', icon: 'none' }); } });
|
||
} else { wx.showToast({ title: '未授权手机号', icon: 'none' }); }
|
||
},
|
||
onNick(e) { this._nick = e.detail.value; this.setData({ nickname: this._nick }); },
|
||
onAvatar(e) {
|
||
const p = e.detail.avatarUrl;
|
||
wx.uploadFile({ url: 'https://YOUR_API/avatar', filePath: p, name: 'file',
|
||
success: (res) => { const r = JSON.parse(res.data || '{}'); this._avatar = r.url || p; this.setData({ avatar: this._avatar }); } });
|
||
},
|
||
|
||
// 授权完成 → 写 globalData → 去 webview 页加载 H5(结果在 URL)→ 即“回到 H5”
|
||
finishAuth() {
|
||
app.globalData.wxH5Result = { openid: this._openid, phone: this._phone, nickname: this._nick, avatar: this._avatar };
|
||
wx.redirectTo({ url: '/pages/demo/webview' });
|
||
},
|
||
cancel() { wx.navigateBack({}); },
|
||
});
|