調用微信JS-SDK,實現定位打卡功能

微信公衆平臺APIvue

1、綁定域名webpack

先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」,接口安全域名必須配置正確,不然沒法調用JS-SDKios

2、下載域名校驗文件放在根目錄下,添加下列內容,確保打包後文件不丟失git

// 在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: ''
  }
])
複製代碼

3、vue 中引入文件web

npm install weixin-js-sdk --save

// 在使用頁面引用便可
import wx from 'weixin-js-sdk'
複製代碼

4、獲取微信配置信息npm

// 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: '定位失敗' })
  })
}
複製代碼

5、微信初始化axios

// 微信初始化
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('微信權限配置失敗')
  })
}
複製代碼
相關文章
相關標籤/搜索