Live2D

初始化微信JSAPI

复制代码
/**
 * 初始化微信 JS-SDK
 * @see https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
 */
import { getWxSignature } from '@/services/index'; //获取签名的接口,服务端提供

export const APPID = 'xxxx'; 微信小程序的appid

/**
 * 获取随机字符串
 * @param length - 随机字符串长度,默认为 32
 */
export function getRandomStr (length = 32): string {
  const tmp = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  let str = '';
  for (let i = 0; i < length; i += 1) {
    str += tmp.charAt(Math.floor(Math.random() * tmp.length));
  }
  return str;
}

async function getWxConfig (jsApiList: string[] = ['openLocation']) {
  const nonceStr = getRandomStr(6);
  const timestamp = Math.floor(new Date().getTime() / 1000);

  const res = await getWxSignature({
    appId: APPID,
    type: 'jsapi',
    paramMap: JSON.stringify({
      noncestr: nonceStr,
      timestamp: Math.floor(new Date().getTime() / 1000),
      url: location.href,
    }),
  });

  const { model = '' } = res || {}; //获取到的签名

  return {
    appId: APPID,
    debug: false,
    jsApiList,
    timestamp,
    nonceStr,
    signature: model,
  };
}

/** @see https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html */
export async function initWxJsSdk () {
 const isWeixin =
/MicroMessenger/i.test(navigator.userAgent);
if (!isWeixin) return;

  const configData = await getWxConfig();

  return new Promise((resolve, reject) => {
    const handleWxReady = () => {
      window.wx?.config(configData);
      window.wx?.ready(resolve);
      window.wx?.error(reject);
    };

    if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {
      document.addEventListener('WeixinJSBridgeReady', handleWxReady, false);
    } else {
      handleWxReady();
    }
  });
}
复制代码

 

posted @   喻佳文  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示