获取企业微信授权code

在企业微信的Vue应用中,由于授权回调路径http://xxx/?code=...&state=#/question的特性,code值位于#之前,需要使用正则表达式来正确获取授权code。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于企业微信vue hash模式下网页授权返回的路径:http://xxx/?code=otRG0-v6GX6L87pCkJOZW_XwAH2e9xcuclVlL5-eobk&state=#/question,拼接code在#之前需要用正则方法(getUrlKey('code'))拿到对应code

created() {
  // 由于企业微信vue hash模式下网页授权返回的路径:http://xxx/?code=otRG0-v6GX6L87pCkJOZW_XwAH2e9xcuclVlL5-eobk&state=#/question
  const code = this.getUrlKey('code')
  if (code) {
    this.code = code
    this.getFastReplyCntent(code)
  } else {
    this.getCodeApi()
  }
},
getCodeApi() {
    // 获取code
    const urlNow = encodeURIComponent(window.location.href) // 这个地址可以写项目的地址
    const id = this.$route.query.id
    sessionStorage.setItem('dydstate', id)
    sessionStorage.setItem('infoId', this.$route.query.infoId)
    sessionStorage.setItem('userType', this.$route.query.userType)
    const url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + this.appid + '&redirect_uri=' + urlNow + '&response_type=code&scope=snsapi_base&state=' + id + '#wechat_redirect'
    window.location.href = url
},
// 获取路径中的参数(code等)
getUrlKey(name) {
    return (decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || ['', ''])[1].replace(/\+/g, '%20')) || null)
},

// 这是网上找的第二种获取参数的方法
getQueryString(name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  const result = window.location.search.substring(1).match(reg);
  if (result != null) {
    return decodeURIComponent(result[2]);
  }
  return null;
}

// 通过原生 JS 去获取 code
getQueryString('code')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值