收藏
回答

iphone13 系统ios26.3 基于微信公众号开发的h5 回调后老是报错code被使用

import { wxCallback } from '@/api/login.js'

import config from '@/config'


// 全局锁:整个应用只允许一次授权流程

let processing = false


export function wxAuthorize(callback) {

  // 强互斥锁,进不来就是进不来

  if (processing) return

  processing = true


  const redirect_uri = config.redirect_uri1 || window.location.href.split('?')[0]

  const appid = config.appid


  // 一进来立刻解析并清空 URL!!!这是关键

  const urlParams = getUrlCode()

  const code = urlParams.code


  // ==============================================

  // 【核心】一拿到 code 立刻清空 URL

  // 不管后面成功失败,绝对不给第二次机会

  // ==============================================

  if (code) {

    window.history.replaceState({}, '', window.location.pathname)

  }


  const lastValidCode = uni.getStorageSync('last_valid_code') || ''


  // 无 code → 去授权

  if (!code) {

    console.log('无 code,前往微信授权')

    const redirectUriEncode = encodeURIComponent(redirect_uri)

    const newState = Date.now() + Math.random().toString(36).slice(2)


    const authUrl =

      `https://open.weixin.qq.com/connect/oauth2/authorize` +

      `?appid=${appid}` +

      `&redirect_uri=${redirectUriEncode}` +

      `&response_type=code` +

      `&scope=snsapi_userinfo` +

      `&state=${newState}` +

      `#wechat_redirect`


    processing = false

    window.location.href = authUrl

    return

  }


  console.log('当前 code:', code)


  // code 已经用过

  if (code === lastValidCode) {

    console.log('code 已使用过,丢弃')

    uni.removeStorageSync('last_valid_code')

    processing = false

    callback({ success: false, msg: 'code已使用' })

    return

  }


  // 正常去换 token

  wxCallback(`?code=${code}&state=123`).then(res => {

    uni.setStorageSync('last_valid_code', code)

    processing = false

    callback({ success: true, data: res })

  }).catch(err => {

    console.error('wxCallback 失败:', err)

    uni.removeStorageSync('last_valid_code')

    processing = false

    callback({ success: false, ...err })

  })

}


// 解析 URL 参数

export function getUrlCode() {

  const theRequest = {}

  if (location.search.includes('?')) {

    const str = location.search.substr(1)

    const strs = str.split('&')

    for (let i = 0; i < strs.length; i++) {

      const [k, v] = strs[i].split('=')

      if (k) theRequest[k] = v

    }

  }

  return theRequest

}


export function getParams(url) {

  const searchParams = new URLSearchParams(url.split('?')[1])

  const params = {}

  for (const [key, value] of searchParams.entries()) {

    params[key] = value

  }

  return params

}


回答关注问题邀请回答
收藏

2 个回答

  • 社区技术运营专员--许涛
    社区技术运营专员--许涛
    02-27

    你好,打印下fail

    02-27
    有用
    回复
  • 文仔
    文仔
    03-03

    me.chanjar.weixin.common.exception.WxErrorException: {"errcode":40163,"errmsg":"code been used, rid: 699fe731-6f96e89c-398595ba"} 只有iphone13 系统ios26.3

    这个版本的会报错。其他的版本都正常

    03-03
    有用
    回复
登录 后发表内容