cometang前端技术博客 cometang前端技术博客
首页
  • html5
  • JavaScript
  • ES6
  • Vue
  • 微信小程序
  • react
  • react上手教程
  • 前端框架
  • 大神之路
  • 面试汇总
  • Node
  • PHP
  • Go语言
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

cometang

永远相信技术的力量
首页
  • html5
  • JavaScript
  • ES6
  • Vue
  • 微信小程序
  • react
  • react上手教程
  • 前端框架
  • 大神之路
  • 面试汇总
  • Node
  • PHP
  • Go语言
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • ES6

  • vue

  • h5

  • JavaScript

  • 前端框架

  • react

  • 大神之路

  • 微信小程序

    • 微信小程序语法基础
    • 微信小程序进阶
    • 微信小程序高阶
      • 前言:
      • 1.网络请求 wx.request()
      • 2.网络请求的企业级三层封装
        • 2.1 前置,提取公共服务器url utils/common.js
        • 2.1 第一层 utils/request.js
        • 2.2 第二层 接口对应层 /api/users.js
        • 2.3 第三层 接口调用层
      • 3.本地存储
      • 4.小程序定位+腾讯地图 逆地址解析api 获取城市
        • 注意1: 获取用户授权 配置 app.json
        • 注意2:在请求腾讯位置服务时需要配置 后端接口服务器的白名单
      • 5.获取用户信息 getUserProfile
      • 6.用户 登录
        • 6.1 登录流程图
        • 6.2 准备工作:
        • 6.3 前端拿到 code 发送给后端,后端返回openid 和seesionkey
      • 8.相机扫码
      • 9.选择联系人
      • 10.拨打电话
      • 4. 小程序分享
      • 5.微信支付
      • 6.分包上线
  • 面试题汇总

  • react轻松上手教程

  • 前端
  • 微信小程序
cometang
2023-02-11
目录

微信小程序高阶

# 前言:

微信小程序中最为强大的 是 微信的内置API,内置API 可以支持在 小程序中 快速调用微信软件的部分功能,能够快速对接一些业务需求,比如: 网络请求,支付,数据缓存,数据分析,文件操作,位置获取,手机硬件调用等等。

文档链接: https://developers.weixin.qq.com/miniprogram/dev/api/base/wx.env.html

# 1.网络请求 wx.request()

类似于axios 用来发送网络请求,获取后端的数据,

wx.request 方法没有通过 Promise 进行封装,使用起来比较麻烦。

如果需要在微信小程序 请求 https:// 的后端接口,需要配置服务器白名单才能够正确请求,不会会被微信拦截,配置方法:服务器域名请在 「小程序后台 - 开发 - 开发设置 - 服务器域名」 中进行配置 https://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html

wx.request({
  url: 'example.php', //仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
  • 使用案例

// index.js
Page({
  data:{
  },
  getData(){
    wx.request({
      url: 'http://129.211.169.131:6368/getFractionShop', //仅为示例,并非真实的接口地址
      success (res) {
        console.log(res.data)
      }
    })
  },
  onLoad(){
    this.getData()
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 2.网络请求的企业级三层封装

在调用接口时,很多时候都需要进行封装,为了更方便的使用

# 2.1 前置,提取公共服务器url utils/common.js

export const  BaseUrl = 'http://129.211.169.131:6368'
1

# 2.1 第一层 utils/request.js

import {BaseUrl} from './common'

//利用 Promise 封装 request 请求
export const request = (url,method,data={})=>{
  return new Promise((resolve,reject)=>{
      wx.request({
        url:BaseUrl+url,
        method,
        data,
        success(res){
          console.log(res);
           resolve(res)
        },
        fail(err){
          reject(err)
        }
      })
  })
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 2.2 第二层 接口对应层 /api/users.js

import {request} from '../utils/request'

// get 
export  const getList = ()=>request('/getFractionShop','get');

// post 
export  const xxx = (data)=>request('/xxxx','post',data);
1
2
3
4
5
6
7

# 2.3 第三层 接口调用层

页面的js文件中

// index.js
import {getList} from '../../api/data'
Page({
  data:{

  },
  getData(){
   getList().then(res=>{
      console.log(res.data);   //获取到返回数据
    })
  },
  onLoad(){
    this.getData()
  }
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 3.本地存储

# 4.小程序定位+腾讯地图 逆地址解析api 获取城市

  • 注册腾讯位置服务-开发者账号 https://lbs.qq.com/

  • 应用管理--我的应---创建新应用--【注意:创建应用时,需要传入 小程序的 appId(微信公众平台申请且绑定到当前小程序)】

  • 创建应用后,创建key: 【必选:webServiceAPI,填写自己小程序的 appId】

  • 微信小程序中 使用 wx.getLocation() 获取当前用户的 经纬度信息【需要获取用户权限】

  • 获取到 当前用户的 经纬度之后,调用腾讯位置服务中的 逆地址解析API【通过经纬度获取地址数据】 【需要配置域名白名单】

  async getCity(){
    let location =  await wx.getLocation();
    let optionStr = `location=${location.latitude},${location.longitude}&key=2U5BZ-3C66V-FFPP7-UEM3K-NOZNE-LBFUL`;
    wx.request({
      url:`https://apis.map.qq.com/ws/geocoder/v1/?${optionStr}`,
      method:'get',
      success(res){
        console.log(res.data.result);
      }
    })

1
2
3
4
5
6
7
8
9
10
11

img

# 注意1: 获取用户授权 配置 app.json

{
    ...,
   "requiredPrivateInfos":[
        "getLocation"
    ],
  "permission": {
      "scope.userLocation":{
          "desc": "使用地图需要获取您的位置?"
      }
  },
}
1
2
3
4
5
6
7
8
9
10
11

# 注意2:在请求腾讯位置服务时需要配置 后端接口服务器的白名单

微信公众平台----小程序---开发-----开发管理---开发设置---服务器域名--添加https的域名

# 5.获取用户信息 getUserProfile

微信小程序获取用户信息-登录规则调整公告:https://developers.weixin.qq.com/community/develop/doc/000cacfa20ce88df04cb468bc52801

<button bindtap="getUserProfile"> 点击获取信息</button>
1
getUserProfile(e) {
    // 推荐使用 wx.getUserProfile 获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
  			//res  返回的用户信息: 包含头像 用户名
      }
    })
  },
1
2
3
4
5
6
7
8
9
10

# 6.用户 登录

# 6.1 登录流程图

img

# 6.2 准备工作:

在小程序后台(开发管理---开发设置),拿到 AppID 与 AppSecret 秘钥 交给后端,【微信说:原则上,前端不能存储AppSecret 【为了安全,防止前端爬虫】 】

# 6.3 前端拿到 code 发送给后端,后端返回openid 和seesionkey

后端接口地址: http://115.159.153.85:5002/getOpenId

请求方式: post

请求数据:

AppID: 小程序appid AppSecret:小程序管理平台秘钥 code:login接口的返回值

utils/common.js

export const WXAPP = {
  AppID:'wx5484e4642189d850',
  AppSecret:'a75403a4491dc2cf67d81aecc010bb88'
}
1
2
3
4

页面.js

onload(){
    wx.login({
      success: (res) => {
        let data = {
          AppID:WXAPP.AppID,
          AppSecret:WXAPP.AppSecret,
          code:res.code
        }
       wx.request({
         url:'http://115.159.153.85:5002/getOpenId',
         method:'post',
         data,
         success(res){
           console.log(res);  // {session_key: "5mBqgkPgAkyLW623B3mfHg==", openid: "oxqa_5FE_ZAQKDeRV3-37CkUVVbg"}
         }
       })
      },
    })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 8.相机扫码

// 允许从相机和相册扫码
wx.scanCode({
  success (res) {
    console.log(res.result)  //扫码得到的数据
  }
})

// 只允许从相机扫码
wx.scanCode({
  onlyFromCamera: true,
  success (res) {
    console.log(res)
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 9.选择联系人


<button  bindtap="chooseContact">选择联系人</button>
1
2
 chooseContact() {
        wx.chooseContact({
          success: function (res) {
            console.log(res, '成功回调')
          },
          fail(res) {
            console.log(res, '错误回调')
          },
          complete(res) {
            console.log(res, '结束回调')
          }
        })
      }
1
2
3
4
5
6
7
8
9
10
11
12
13

# 10.拨打电话

<button bindlongpress="tell" data-phoneNum="13648242772">13648242772</button>
1
tell(e){
  // 提示呼叫号码还是将号码添加到手机通讯录
  wx.showActionSheet({
      itemList: ['呼叫','添加联系人'],
      success:function(res){
          if(res.tapIndex===0){
            console.log(e.target);
              // 呼叫号码
              wx.makePhoneCall({
              phoneNumber: e.target.dataset.phonenum
              })
          }else if(res.tapIndex==1){
              // 添加到手机通讯录
              wx.addPhoneContact({
              firstName: 'test',//联系人姓名
              mobilePhoneNumber: e.target.dataset.phonenum,//联系人手机号
              })
          }
      }
  })
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 4. 小程序分享

https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html#onShareAppMessage-Object-object
1
  • 发送给朋友

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '源码1'
        })
      }, 2000)
    })
    return {
      title: '源码',
      path: '/page/home',
      promise 
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 5.微信支付

# 6.分包上线

编辑 (opens new window)
微信小程序进阶
面试题汇总

← 微信小程序进阶 面试题汇总→

最近更新
01
go语言基础
07-13
02
《react上手教程》- 基础语法
07-13
03
redux-redux toolkit-状态管理
03-18
更多文章>
Theme by Vdoing | Copyright © 2019-2023

cometang | 唐世杰 渝ICP备18015657号-2

  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式