一、引入微信jssdk(需要先配置安全域名)
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script>
附:微信官方文档
二、通过config注入权限验证配置
$.ajax({
type: "post",
url: $http + "url", //后台接口
xhrFields: {
withCredentials: true
},
success: function (res) {
wx.config({
appId: res.data.app_id, // 必填,企业号的唯一标识,此处填写企业号corpid
timestamp: res.data.timestamp, // 必填,生成签名的时间戳
nonceStr: res.data.noncestr, // 必填,生成签名的随机串
signature: res.data.sign, // 必填,签名,见附录1
jsApiList: [
] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function () {
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
//例如,进入首页需要获取地理位置,需要在这里写wx.getLocation
});
wx.error(function (res) {
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});
}
});
三、写需要用到的权限
例如:获得地理位置
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function(res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
var dingwei = res.latitude + "," + res.longitude
sessionStorage.setItem("dingwei", dingwei)
}
});
例如:扫描二维码
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function(res) {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
window.location.href = result
}
});
四、登录(网页授权)
微信登陆需要单独说一下,这个地方是个比较麻烦的点。
通过看文档得知,登录需要四步
第一步:用户同意授权,获取code
前端直接跳转页面,用户同意授权后,微信会返回一个code。
* 需要注意的是,如果前端使用vue进行开发,页面中的#会被微信忽略,所以建议路由使用history模式,后台配合一下。
跳转路径:
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
redirect_uri需要用encodeURIComponent("返回网址")进行编码
授权成功后,微信会返回你的redirect_uri并带着code,如下图
第二步:通过code换取网页授权access_token
这一步需要后台来做,前端只需要把code传到后台即可,
截取code传到后台
let data={
code:code
}
axios.post('/api/auth/code',data).then((res) => {
if (res.code == 200) {
}
}).catch(function (error) {
});
第三步和第四步只需要后台做
这里贴一下自己的代码,用vue做的,登陆在路由的beforeEach做的
import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from "@/axios/axios.js"
import utils from "@/utils/utils.js"
let newUtils=new utils()
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: () => import('../views/home/home.vue')
},
{
path: '/order',
name: 'order',
component: () => import('../views/order/order.vue')
},
{
path: '*',
redirect: '/'
}
]
const router = new VueRouter({
mode:"history",
routes
})
router.beforeEach((to, from, next) => {
//非白名单页面判断登陆状态
let redirect_uri=encodeURIComponent(newUtils.getPath().url+to.fullPath),appid=newUtils.getPath().appid
let code=to.query.code,state=to.query.state
let noLoginArr=["/"],isCur=false,token=sessionStorage.getItem("token")
for(let i of noLoginArr){
if(to.path==i){
isCur=true
}
}
if(isCur){ //白名单内不做登录判断
next()
}else{
if(code && state && !token){ //登陆之后获取到code,传到后台登录
let data={
code:code
}
axios.post('/api/auth/code',data).then((res) => {
if (res.code == 200) {
sessionStorage.setItem("token",res.data.token)
axios.defaults.headers.common['token'] = res.data.token
next()
}
}).catch(function (error) {
});
}else if(token){ //已登录,有token,判断是否过期
let data={
token:token
}
axios.post('/api/auth/checkToken',data).then((res) => { //判断token是否过期接口
if (res.code == 200) {
next()
}else if(res.code == 401){
//去登录
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
}
}).catch(function (error) {
});
}else{ //未登录,没有token,去登录
//去登录
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
}
}
})
export default router