调用微信JS-SDK,实现定位打卡功能

3,220 阅读2分钟

微信公众平台API

一、绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”,接口安全域名必须配置正确,否则无法调用JS-SDK

二、下载域名校验文件放在根目录下,添加下列内容,确保打包后文件不丢失

// 在webpack.prod.conf.js文件下
new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetsSubDirectory,
    ignore: ['.*']
  },
  // 拷贝微信授权文件
  {
    from: path.join(__dirname, '../WW_verify_csnlcbNdYTh1Jr70.txt'),
    to: ''
  },
  // 拷贝微信授权文件
  {
    from: path.join(__dirname, '../WW_verify_eh9DBm9Q7RXevG73.txt'),
    to: ''
  },
  // 拷贝微信授权文件
  {
    from: path.join(__dirname, '../WW_verify_Y9t6r8NcjE375lec.txt'),
    to: ''
  }
])

三、vue 中引入文件

npm install weixin-js-sdk --save

// 在使用页面引用即可
import wx from 'weixin-js-sdk'

四、获取微信配置信息

// url必须不包含#以及后面部分(若url传参错误,数据也会返回,但签名是失败的)
// axiosApi()是封装好的axios请求方法
getWxConfig () {
  let curHref = window.location.href.split('#')[0]
  let params = {
    appId: this.appId,
    url: curHref
  }
  axiosApi({ url: 'wxSignpackage', 'type': 'post', params }).then((res) => {
    this.initWx(res)
  }).catch((e) => {
    console.log(e)
    this.clockTip = '定位失败'
    this.$toast({ message: '定位失败' })
  })
}

五、微信初始化

// 微信初始化
initWx (res) {
  let _this = this
  let wxConfig = {
    debug: false, // 开启调试模式
    appId: res.appId, // 必填,公众号的唯一标识
    timestamp: res.timestamp, // 必填,生成签名的时间戳
    nonceStr: res.nonceStr, // 必填,生成签名的随机串
    signature: res.signature, // 必填,签名
    jsApiList: [ 'getLocation' ] // 必填,需要使用的JS接口列表
  }
  wx.config(wxConfig)

  // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,
  // config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,
  // 则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,
  // 则可以直接调用,不需要放在ready函数中。

  wx.ready(function () {
    wx.getLocation({
      type: 'wgs84', //默认为wgs84的gps坐标
      success: (res) => {
        _this.getAddress(res.longitude, res.latitude)
        _this.getNearBy(res.longitude, res.latitude)
        _this.addMarker(res.longitude, res.latitude)
      },
      fail: function (res) {
        console.log(res)
        console.log('微信定位失败')
      }
    })
  })
  
  // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看
  // 也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
  wx.error(function (res) {
    console.log(res)
    console.log('微信权限配置失败')
  })
}