小程序
授权
微信公众号网页授权采用 OAuth 2.0 授权码模式:用户进入页面时先跳转微信授权,微信回调时在 URL 中携带 code,应用拿到 code 后渲染页面,由业务逻辑将 code 提交给后端换取登录凭证。
参考公众号网页授权
授权流程
入口初始化
以 React 项目为例。init() 在应用启动时执行:已有 Token 直接渲染应用;否则进入微信授权流程——URL 含 code 时渲染应用(应用内部负责将 code 换取 Token),不含 code 时跳转微信授权页。
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import { getTokenCookie } from './utils/cookie.ts'
import { wxAuth } from './utils/wx'
/**
* init app
*/
function renderApp() {
ReactDOM.createRoot(document.getElementById('root')!).render(
/**
* do not remove StrictMode it will cause error
* @see https://react.dev/reference/react/StrictMode
*/
<React.StrictMode>
<App />
</React.StrictMode>,
)
}
/**
* init wx auth
*/
function handleWxAuthorization() {
const url = new URL(window.location.href)
const code = url.searchParams.get('code')
if (code) {
try {
renderApp()
} catch (error) {
console.error('微信登录失败:', error)
wxAuth() // 失败时重新引导授权
}
} else {
wxAuth()
}
}
/**
* init
*/
async function init() {
if (getTokenCookie()) {
renderApp()
} else {
handleWxAuthorization()
}
}
init()构造微信授权链接
wxAuth() 将当前页面 URL 作为 redirect_uri,拼接授权参数后跳转微信,微信完成授权后会带着 code 回调到同一页面。
/**
* @description 微信授权
*/
export function wxAuth() {
// 当前地址
const currentUrl = new URL(window.location.href)
// 参数
const state = currentUrl.searchParams.get('state') ?? 'state'
const appid = import.meta.env.VITE_APP_WX_APP_ID
const redirect_uri = currentUrl.href
const wxAuthUrl = new URL(
'https://open.weixin.qq.com/connect/oauth2/authorize',
)
wxAuthUrl.searchParams.set('appid', appid)
wxAuthUrl.searchParams.set('redirect_uri', redirect_uri)
wxAuthUrl.searchParams.set('response_type', 'code')
wxAuthUrl.searchParams.set('scope', 'snsapi_userinfo')
wxAuthUrl.searchParams.set('state', state)
wxAuthUrl.hash = 'wechat_redirect'
window.location.href = wxAuthUrl.href
}环境变量
| 变量 | 说明 |
|---|---|
VITE_APP_WX_APP_ID | 公众号的 AppID,在微信公众平台后台获取 |