wechat.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * 判断是否在微信环境
  3. */
  4. export function isWechat() {
  5. const ua = window.navigator.userAgent.toLowerCase();
  6. // @ts-ignore
  7. return ua.match(/MicroMessenger/i) == 'micromessenger';
  8. }
  9. /**
  10. * 判断是否在企业微信环境
  11. */
  12. export function isEnterpriseWechat() {
  13. const ua = window.navigator.userAgent.toLowerCase();
  14. // @ts-ignore
  15. return isWechat() && ua.match(/wxwork/i) == 'wxwork';
  16. }
  17. /**
  18. * 重定向到企业微信授权页面
  19. * @param redirectUri 回调地址
  20. */
  21. export function redirectToWechatAuth(redirectUri: string) {
  22. const corpId = import.meta.env.VITE_WECHAT_CORPID;
  23. // const agentId = import.meta.env.VITE_WECHAT_AGENTID; // 非扫码登录场景通常不需要 agentid,由后端配置决定
  24. const state = 'STATE';
  25. const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${corpId}&redirect_uri=${encodeURIComponent(
  26. redirectUri
  27. )}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
  28. window.location.href = url;
  29. }
  30. /**
  31. * 从 URL 中获取 code
  32. */
  33. export function getUrlCode(): string | null {
  34. const url = window.location.href;
  35. const match = url.match(/[?&]code=([^&#]*)/);
  36. return match ? match[1] : null;
  37. }