@xiao-ying/miniapp-wechat-h5
v1.1.0
Published
Headless React helpers for opening XiaoYing App from WeChat H5
Readme
@xiao-ying/miniapp-wechat-h5
微信 H5 中“在 App 内打开”的 headless React 能力包。
- 不依赖
@xiao-ying/miniapp-ui-browser - 不提供 CSS、Tailwind 插件或 Vite 插件
- 通过
weixin-js-sdk+wx-open-launch-app实现微信内唤起 App
安装
pnpm add @xiao-ying/miniapp-sdk @xiao-ying/miniapp-sdk-browser @xiao-ying/miniapp-wechat-h5 react快速使用
在入口最顶部记录微信落地页 URL:
import '@xiao-ying/miniapp-sdk'
import '@xiao-ying/miniapp-sdk-browser'
import { captureWechatEntryUrl } from '@xiao-ying/miniapp-wechat-h5'
captureWechatEntryUrl()然后在页面里使用包装组件:
import { WechatOpenInAppButton } from '@xiao-ying/miniapp-wechat-h5'
export const OpenButton = () => {
return (
<WechatOpenInAppButton appId="wx_your_mobile_appid">
<button type="button">在 App 中打开</button>
</WechatOpenInAppButton>
)
}默认行为
- 默认签名接口:
POST https://api.xiaoying.life/v1/user/wechat-h5/sign - 默认
extInfo:https://m.xiaoying.life - 非微信环境、初始化失败、或尚未 ready 时,仅渲染
children children只负责展示;真实点击入口是覆盖在上层的wx-open-launch-app- 若传入
openTagReadyTimeoutMs,则会在 Android 微信里检测开放标签ready超时;超时后卸载wx-open-launch-app并触发onOpenTagReadyTimeout
Hook
import { useWechatOpenInApp } from '@xiao-ying/miniapp-wechat-h5'
const Example = () => {
const { isWechat, isLoading, isReady, error } = useWechatOpenInApp()
return <pre>{JSON.stringify({ isWechat, isLoading, isReady, error: error?.message })}</pre>
}自定义签名请求
默认会通过 xy.request 发起:
POST https://api.xiaoying.life/v1/user/wechat-h5/sign
Content-Type: application/json
{"url":"<signUrl>"}若你想自行处理请求逻辑,可传入 signatureRequest:
<WechatOpenInAppButton
appId="wx_your_mobile_appid"
signatureRequest={async (signUrl) => {
const response = await fetch('/v1/user/wechat-h5/sign', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: signUrl
})
})
return await response.json()
}}
>
<button type="button">在 App 中打开</button>
</WechatOpenInAppButton>签名接口返回值约定:
{
"appId": "wx_service_account_appid",
"timestamp": 1234567890,
"nonceStr": "nonce",
"signature": "sha1"
}API
captureWechatEntryUrl()
- 建议在
main.tsx最顶部调用 - 首次调用时记录
window.location.href去掉#后的值 - 写入
window.__XY_MINIAPP_WECHAT_H5__.entryUrl - 幂等,不会覆盖已记录值
useWechatOpenInApp(options?)
signatureEndpoint?: stringsignatureRequest?: (signUrl: string) => Promise<{ appId: string; timestamp: number; nonceStr: string; signature: string }>
返回:
isWechatisLoadingisReadyerror
WechatOpenInAppButton
appId: stringextInfo?: stringsignatureEndpoint?: stringsignatureRequest?: (signUrl: string) => Promise<WechatSignature>children: React.ReactNodedisabled?: booleanopenTagReadyTimeoutMs?: numberclassName?: stringstyle?: React.CSSPropertiesonReady?: () => voidonLaunch?: (detail) => voidonError?: (detail) => voidonOpenTagReadyTimeout?: () => void
注意事项
- 本包仅适用于浏览器端,不支持 SSR
- iOS 微信签名强依赖首个落地页 URL,因此推荐始终在入口尽早调用
captureWechatEntryUrl() - Android / 鸿蒙通过开放标签拉起 App 时,App 侧仍需正确接入微信 OpenSDK
- 本包保持 headless;即使检测到开放标签超时,也不会内置任何“请在浏览器中打开”的提示文案
