doum
2026-06-16 77094dd01f0c6ff59b4fb4fa1105addf34b2398c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { devWechatMock, wxAppId, wxRedirectUri } from './config.js'
 
/** 从当前 URL 解析微信 OAuth code */
export function extractOAuthCodeFromUrl () {
  if (typeof window === 'undefined') return ''
  const href = window.location.href
  if (href.indexOf('code=') === -1) return ''
  const parts = href.split('?')
  for (const q of parts) {
    if (q.indexOf('code=') !== -1) {
      const stateIdx = q.indexOf('&state')
      return q.substring(q.indexOf('code=') + 5, stateIdx > -1 ? stateIdx : q.length)
    }
  }
  return ''
}
 
/** 跳转微信 OAuth(仅非模拟环境) */
export function redirectToWechatOAuth () {
  const uri = encodeURIComponent(wxRedirectUri)
  window.location.href =
    `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxAppId}&redirect_uri=${uri}&response_type=code&scope=snsapi_base#wechat_redirect`
}
 
/**
 * 微信 OAuth:开发环境用模拟 openid,生产环境走微信授权
 * @param {Object} options
 * @param {Function} options.authorizeApi (data) => Promise
 * @param {Function} options.onSuccess (res) => void
 * @param {string} [options.fallbackCode] 页面内缓存的 code
 */
export function runWechatOAuthFlow ({ authorizeApi, onSuccess, fallbackCode = '' }) {
  if (typeof window === 'undefined') return
 
  const handleAuthorize = (code) => {
    if (!code) return
    authorizeApi({ code }).then(res => {
      if (res.code === 200) onSuccess(res)
    })
  }
 
  if (devWechatMock.enabled) {
    const mockOpenId = uni.getStorageSync('openId') || devWechatMock.openId
    uni.setStorageSync('openId', mockOpenId)
    handleAuthorize(devWechatMock.mockCode)
    return
  }
 
  const code = extractOAuthCodeFromUrl() || fallbackCode
  if (code) {
    handleAuthorize(code)
    return
  }
  redirectToWechatOAuth()
}