用户授权获取手机号码
index.wxml
xml
复制
<view class="container">
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号码</button>
<view wx:if="{{phoneNumber}}">您的手机号码是:{{phoneNumber}}</view>
</view>
index.js
JavaScript
复制
Page({
data: {
phoneNumber: null // 用于存储手机号码
},
getPhoneNumber: async function (e) {
if (e.detail.errMsg !== "getPhoneNumber:ok") {
wx.showToast({
title: '授权失败,请重试',
icon: 'none'
});
return;
}
wx.showLoading({ title: '获取中...', mask: true });
try {
const res = await wx.cloud.callFunction({
name: 'getPhoneNumber',
data: {
cloudID: e.detail.cloudID
}
});
if (res.result.success && res.result.phoneNumber) {
this.setData({
phoneNumber: res.result.phoneNumber
});
wx.showToast({
title: '获取成功',
icon: 'success'
});
} else {
wx.showToast({
title: '手机号码获取失败',
icon: 'none'
});
}
} catch (err) {
console.error('获取手机号码失败', err);
wx.showToast({
title: '获取手机号码失败',
icon: 'none'
});
} finally {
wx.hideLoading();
}
}
});
app.js
JavaScript
复制
App({
onLaunch: function () {
wx.cloud.init({
env: 'your-env-id', // 替换为你的云开发环境ID
traceUser: true
});
}
});
cloudfunctions/getPhoneNumber/index.js
JavaScript
复制
constrequire'wx-server-sdk'env'your-env-id'// 替换为你的云开发环境IDasyncconsttryconstawaitopenidcloudidListconstJSON0returnsuccesstruecatchconsole'解密手机号码失败'returnsuccessfalseerror'解密失败'
};
}
};
编译获取不了手机号,提示为:
wx.getSystemInfoSync is deprecated.Please use wx.getSystemSetting/wx.getAppAuthorizeSetting/wx.getDeviceInfo/wx.getWindowInfo/wx.getAppBaseInfo instead.
ye @ VM4137:1
(anonymous) @ VM4137:1
t @ VM4137:1
s @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
t @ VM4137:1
s @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
f @ VM4137:1
l @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
t @ VM4137:1
s @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
c @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
t @ VM4137:1
s @ VM4137:1
Promise.then (async)
t @ VM4137:1
s @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
t @ VM4137:1
s @ VM4137:1
(anonymous) @ VM4137:1
(anonymous) @ VM4137:1
u @ VM4137:1
s @ VM4137:1
(anonymous) @ VM4137:1
o.<computed> @ VM4137:1
_callee$ @ index.js? [sm]:18
s @ regeneratorRuntime.js?forceSync=true:1
(anonymous) @ regeneratorRuntime.js?forceSync=true:1
(anonymous) @ regeneratorRuntime.js?forceSync=true:1
asyncGeneratorStep @ asyncToGenerator.js?forceSync=true:1
c @ asyncToGenerator.js?forceSync=true:1
(anonymous) @ asyncToGenerator.js?forceSync=true:1
(anonymous) @ asyncToGenerator.js?forceSync=true:1
getPhoneNumber @ index.js? [sm]:6
请注意 showLoading 与 hideLoading 必须配对使用
上述返回已提示 wx.getSystemInfoSync() 已经弃用了