在vue项目中使用微信js-sdk ,解析返回url,获取微信code,
直接上干货,如有不懂欢迎留言,如有错误,欢迎指出vue组件<script>import {authPageBaseUri, homePage, wechatAppId} from 'config'import {extractQueryParams} from 'utils'export default {name: 'home',data (...
·
直接上干货,如有不懂欢迎留言,如有错误,欢迎指出
vue组件
<script>
import {authPageBaseUri, homePage, wechatAppId} from 'config'
import {extractQueryParams} from 'utils'
export default {
name: 'home',
data () {
return {
config: {
appid: wechatAppId,
responseType: 'code',
scope: 'snsapi_base',
state: ''
}
}
},
created(){
this.getAuthCode()
},
methods: {
async getAuthCode(){
await this.redirectToAuthPageUrl()
let queryParams = extractQueryParams(window.location.href)
let code = queryParams.code
let callbackUrl = queryParams.callbackUrl
if (code) {
window.location.href = homePage + 'service_list?code=' + code
}
},
redirectToAuthPageUrl(){
let authParams = `?appid=${this.config.appid}&redirect_uri=${homePage}&response_type=${this.config.responseType}&state=${this.config.state}&scope=${this.config.scope}#wechat_redirect`
window.location.href = authPageBaseUri + authParams
},
}
}
</script>
<style scoped>
</style>
config文件
export const homePage = `http://tst.service.com/#/`
export const authPageBaseUri = 'https://open.weixin.qq.com/connect/oauth2/authorize'
export const wechatAppId = 'ww17cf217249330864'
utils文件
export function extractQueryParams (url) {
let queryParams = {}
if (url.includes('?')) {
let queryString = url.substr(url.indexOf('?') + 1)
let pairs = queryString.split('&')
for(let pair of pairs) {
let splitArray = pair.split('=')
let key = splitArray[0]
let value = splitArray[1]
if (value.indexOf('#') > -1) {
value = value.substring(0, value.indexOf('#'))
}
queryParams[key] = value
}
}
return queryParams
}
更多推荐
已为社区贡献4条内容
所有评论(0)