Vue 微信开发,微信内H5静默获取code、openid
在写代码之前要先确定公众号有网页授权的权限
其次需要设置好安全域名
安全域名设置好之后,你的vue界面需要打包好了在微信中测试
注意打包好的Vue URL 一定要是配置的安全域名之内的
<template>
<div class="icontent">
<template v-if="token">
<div>登录成功!</div>
</template>
<template>
<div>登录中...</div>
</template>
</div>
</template>
<script>
import Vue from 'vue';
import store from '@/store'
import $ from 'jquery'
import Cookies from 'js-cookie'
import { getOpenid } from '@/api/login'
import axios from 'axios'
import { setsession, getsession, removesession } from '@/utils/user'
export default {
name: "getcode",
data () {
return {
code: '',
token: ''
}
},
methods: {
// 请求openid的方法,需要后端写法
getopenid_data(data) {
getOpenid(data).then(response => {
const data = response.data
console.log(data)
// alert(JSON.stringify(response))
this.token = data.token
setsession(this.token)
store.state.token = this.token
if (this.$route.path == '/toship') {
this.$router.push({ name: 'myship' })
} else {
this.$router.push({ name: 'myorder' })
}
}).catch(error => {
alert(error)
})
},
getUrlParam (name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
let url = window.location.href.split('#')[0]
let search = url.split('?')[1]
if (search) {
var r = search.substr(0).match(reg)
if (r !== null) return unescape(r[2])
return null
} else {
return null
}
}
},
created: function() {
var code = this.getUrlParam('code')
var local = window.location.href
if (code == null || code == '') {
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4e20c26e94fe156a&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=state#wechat_redirect'
} else {
this.code = code
var data = {
code: this.code
}
this.getopenid_data(data)
}
}
}
</script>
<style scoped>
</style>