微信公众平台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('微信权限配置失败')
})
}
复制代码