开发微信公众号H5页面,经常用到微信的openAPI之类的方法,比如获取用户位置、分享朋友圈或好友以及上传图片、预览图片等,这里对需要用到的api授权方法简单封装一下。
官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
1. 安装 weixin-js-sdk
npm install weixin-js-sdk -S
2. sdk授权方法封装
import request from '@/utils/request' //封装好的请求方法
import wx from 'weixin-js-sdk'
function wxSDKAuth(jsApiList = ['openLocation','getLocation']) {
let url = encodeURIComponent(window.location.href)
console.log('注册的url', url)
request({
method: 'GET',
url: '/wx/jsSignature?pageUrl=' + url, //签名信息从后端获取,在接口中按照官方文档签名加密算法返回签名信息
dataType: 'json',
contentType: 'application/json;charset=utf-8'
}).then(result => {
console.log(result)
if (result.code == 0) {
var config = result.data
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: config.appId, // 必填,公众号的唯一标识
timestamp: config.timeStamp, // 必填,生成签名的时间戳
nonceStr: config.noncestr, // 必填,生成签名的随机串
signature: config.signature, // 必填,签名
jsApiList, // 必填,需要使用的JS接口列表,图片预览接口
openTagList: ['wx-open-launch-weapp', 'wx-open-subscribe'], // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
})
wx.ready(function () {
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
console.log('微信调用ready表示成功')
})
wx.error(function (res) {
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
console.log('wxOpen微信调用错误' + res)
})
}
})
}
export default wxSDKAuth
3.使用举例
import wxSDKAuth from '@/common/wxsdk'
created() {
wxSDKAuth('openLocation','getLocation')
wx.ready(() => {
wx.getLocation({
type:'gcj02',
success: res => {
console.log(res.longitude)
console.log(res.latitude)
}
})
})
}