wechat.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import {getUrlParams} from "@/utils/urlUtils";
  2. import {getOAuthUrl, getWxOpenId} from "@/api/wechat";
  3. import {useUserStore} from "@/store/modules/user";
  4. import {alertController, loadingController} from '@ionic/vue';
  5. export function isWechat() {
  6. return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
  7. /*return true;*/
  8. }
  9. export async function wxAuth() {
  10. const userStore = useUserStore();
  11. if (isWechat() && !userStore.getOpenId) {
  12. const urlParams = getUrlParams() as any;
  13. const code = urlParams["code"];
  14. if (!code) {
  15. const loading = await loadingController.create({
  16. cssClass: 'my-custom-class',
  17. message: '微信授权中,请稍后...',
  18. duration: 2000,
  19. });
  20. await loading.present();
  21. getOAuthUrl().then((res: any) => {
  22. if (res) {
  23. window.location.href = res;
  24. } else {
  25. presentAlert("微信授权失败!");
  26. }
  27. });
  28. } else {
  29. getWxOpenId(code).then((res: any) => {
  30. userStore.setOpenId(res);
  31. });
  32. }
  33. }
  34. }
  35. const presentAlert = async (msg: any) => {
  36. const alert = await alertController.create({
  37. header: '错误!',
  38. message: msg,
  39. buttons: [
  40. '确定'
  41. ],
  42. });
  43. await alert.present();
  44. }