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()
|
}
|