![[猫头虎分享21天微信小程序基础入门教程]第7天:小程序的权限与API使用 🔐](https://img-blog.csdnimg.cn/direct/95a1ac60ea0b4764927e61c5bf307f81.gif)
第7天:小程序的权限与API使用 🔐
自我介绍
大家好,我是猫头虎,一名全栈软件工程师。今天我们将继续微信小程序的学习,重点了解如何使用微信小程序的API,以及如何管理和请求小程序的权限。通过这些知识,你将能够更好地利用微信提供的丰富功能。🚀
小程序的权限管理 🛡️
微信小程序需要通过权限管理系统来请求和使用一些敏感的API,比如用户信息、位置、摄像头等。在使用这些API之前,需要先在app.json中声明所需的权限。
声明权限
在app.json中添加permission字段,声明所需权限。
{
  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序的位置接口功能"
    }
  }
}
检查权限
在使用某些API时,需要检查并请求相应的权限。
wx.getSetting({
  success(res) {
    if (!res.authSetting['scope.userLocation']) {
      wx.authorize({
        scope: 'scope.userLocation',
        success() {
          // 用户同意授权
        },
        fail() {
          // 用户拒绝授权
        }
      });
    }
  }
});
常用API的使用 📱
微信小程序提供了丰富的API,涵盖了各个方面的功能。下面介绍一些常用的API及其使用方法。
获取用户信息 👤
获取用户信息需要用户授权。
wx.getUserProfile({
  desc: '用于完善会员资料',
  success: (res) => {
    console.log(res.userInfo);
  },
  fail: (err) => {
    console.error('获取用户信息失败', err);
  }
});
获取位置信息 📍
获取用户的地理位置信息。
wx.getLocation({
  type: 'wgs84',
  success(res) {
    const latitude = res.latitude;
    const longitude = res.longitude;
    console.log('纬度:', latitude, '经度:', longitude);
  },
  fail(err) {
    console.error('获取位置信息失败', err);
  }
});
拍摄照片 📸
使用相机拍摄照片。
wx.chooseImage({
  count: 1, // 默认9
  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  sourceType: ['album', 'camera'], // 从相册选择或使用相机拍摄
  success(res) {
    const tempFilePaths = res.tempFilePaths;
    console.log('选择的图片路径:', tempFilePaths);
  },
  fail(err) {
    console.error('拍摄照片失败', err);
  }
});
录音 🎤
使用录音功能。
const recorderManager = wx.getRecorderManager();
recorderManager.onStart(() => {
  console.log('recorder start');
});
recorderManager.onPause(() => {
  console.log('recorder pause');
});
recorderManager.onStop((res) => {
  const { tempFilePath } = res;
  console.log('recorder stop', tempFilePath);
});
const options = {
  duration: 60000, // 录音时长
  sampleRate: 44100, // 采样率
  numberOfChannels: 1, // 声道数
  encodeBitRate: 192000, // 编码码率
  format: 'aac' // 音频格式
};
recorderManager.start(options);
小测试 🧪
- 尝试在小程序中使用wx.getUserProfile获取用户信息,并显示在页面上。
- 尝试使用wx.getLocation获取用户的位置信息,并在控制台中打印。
今日学习总结 📚
| 概念 | 详细内容 | 
|---|---|
| 权限管理 | 学习了如何声明和请求小程序的权限 | 
| 常用API | 了解了获取用户信息、位置信息、拍摄照片和录音等常用API的使用 | 
结语
通过今天的学习,你应该掌握了如何在微信小程序中使用各种API,并了解了如何管理和请求小程序的权限。这些知识将帮助你更好地利用微信小程序的丰富功能。明天我们将探讨小程序的发布与审核流程。如果你有任何疑问,欢迎关注并留言在我的公众号猫头虎技术团队。📩



















