index.vue 7.39 KB
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-07-14 16:51:45
 * @FilePath: /jgdl/src/pages/auth/index.vue
 * @Description: 文件描述
-->
<template>
  <div>
    <!-- <button wx:if="{{canIUse}}" open-type="getUserInfo" @getuserinfo="bindGetUserInfo">授权登录</button>
    <view @tap="auth">授权登陆</view> -->
  </div>
</template>

<script setup>
import Taro from '@tarojs/taro'
import request from '@/utils/request';

</script>

<script>
import "./index.less";
import { getCurrentPageParam } from "@/utils/weapp";

export default {
  name: "authPage",
  /**
   * 页面准备完成后执行登录
   */
  onReady() {
    // 添加短暂延迟确保页面完全准备好
    setTimeout(() => {
      this.performLogin();
    }, 100);
  },
  data () {
    return {
      canIUse: wx.canIUse('button.open-type.getUserInfo')
    }
  },
  onLoad: function() {
    // 查看是否授权
    // wx.getSetting({
    //   success (res){
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权,可以直接调用 getUserInfo 获取头像昵称
    //       wx.getUserInfo({
    //         success: function(res) {
    //           console.warn(res.userInfo)
    //         }
    //       })
    //     }
    //   }
    // })
  },
  methods: {
    /**
     * 执行登录授权流程
     */
    performLogin() {
      Taro.login({
        success: (res) => {
          if (res.code) {
            this.handleLoginSuccess(res.code);
          } else {
            console.error('登录失败!' + res.errMsg);
            this.handleLoginError('登录失败,请重试');
          }
        },
        fail: (err) => {
          console.error('登录调用失败:', err);
          this.handleLoginError('登录失败,请重试');
        }
      });
    },

    /**
     * 处理登录成功后的网络请求
     * @param {string} code - 微信登录code
     */
    handleLoginSuccess(code) {
      Taro.showLoading({
        title: '授权中',
      });

      // 根据环境判断是否传递openid参数
      const requestData = {
        code: code
      };
      
      // 测试环境下传递openid,正式环境不传递
      if (process.env.NODE_ENV === 'development') {
        requestData.openid = 'h-008';
      }
      
      request.post('/srv/?a=openid', requestData)
      .then(res => {
        if (res.data.code) {
          const cookie = res.cookies[0];
          if (cookie != null) {
            // 保存sessionid到本地存储
            wx.setStorageSync("sessionid", res.cookies[0]);
            // 修改请求头
            request.defaults.headers.cookie = res.cookies[0];

            // 添加延迟确保存储操作完成
            setTimeout(() => {
              this.handleNavigateAfterAuth();
            }, 200);
          } else {
            // cookie为空时跳转到首页
            this.navigateToHome();
          }
        } else {
          console.warn(res.data.msg);
          this.handleLoginError(res.data.msg || '授权失败');
        }
      })
      .catch(err => {
        console.error('网络请求失败:', err);
        this.handleLoginError('网络请求失败,请重试');
      })
      .finally(() => {
        Taro.hideLoading();
      });
    },

    /**
     * 处理授权成功后的页面跳转
     */
    handleNavigateAfterAuth() {
      try {
        const params = getCurrentPageParam();

        if (params.url === 'pages/productDetail/index') {
          // 详情页的分享跳转处理 - 使用绝对路径
          this.navigateToPage(`/pages/productDetail/index?id=${params.id}`);
        } else if (params.url && params.url !== 'pages/auth/index') {
          // 如果有指定的目标页面且不是auth页面本身,跳转到该页面
          this.navigateToPage(`/${params.url}`);
        } else {
          // 其他情况跳转到首页
          this.navigateToHome();
        }
      } catch (error) {
        console.error('页面跳转参数解析失败:', error);
        // 降级处理:跳转到首页
        this.navigateToHome();
      }
    },

    /**
     * 跳转到指定页面
     * @param {string} url - 目标页面路径
     */
    navigateToPage(url) {
      setTimeout(() => {
        // 使用navigateTo而不是reLaunch,避免重新触发app.js的onLaunch
        Taro.navigateTo({
          url
        }).catch(err => {
          console.error('navigateTo跳转失败,尝试reLaunch:', err);
          // 降级处理:使用reLaunch
          Taro.reLaunch({
            url
          }).catch(err2 => {
            console.error('reLaunch跳转也失败:', err2);
            // 最终降级处理:跳转到首页
            this.navigateToHome();
          });
        });
      }, 300);
    },

    /**
     * 跳转到首页
     */
    navigateToHome() {
      // 使用switchTab跳转到首页,避免重新触发app.js的onLaunch
      Taro.switchTab({
        url: `/pages/index/index`
      }).catch(err => {
        console.error('switchTab跳转首页失败,尝试reLaunch:', err);
        // 降级处理:使用reLaunch
        Taro.reLaunch({
          url: `/pages/index/index`
        }).catch(err2 => {
          console.error('reLaunch跳转首页也失败:', err2);
          // 最后的降级处理
          Taro.showToast({
            title: '页面跳转失败',
            icon: 'error'
          });
        });
      });
    },

    /**
     * 处理登录错误
     * @param {string} message - 错误信息
     */
    handleLoginError(message) {
      Taro.hideLoading();
      Taro.showToast({
        title: message,
        icon: 'error',
        duration: 2000
      });

      // 错误情况下延迟跳转到首页
      setTimeout(() => {
        this.navigateToHome();
      }, 2000);
    },

    bindGetUserInfo (e) {
      console.warn(e.detail.userInfo)
    },
    // auth () {
    //   Taro.getSetting({
    //     success: function (res) {
    //       if (!res.authSetting['scope.userInfo']) {
    //         console.warn(0);
    //         Taro.authorize({
    //           scope: 'scope.userInfo',
    //           success: function () {
    //             Taro.getUserInfo({
    //               success: function(res) {
    //                 var userInfo = res.userInfo
    //                 console.warn(userInfo);
    //               }
    //             })
    //           },
    //           fail: function (error) {
    //             console.error(error)
    //           }
    //         })
    //       }
    //     }
    //   })
    // }
    auth () {
      // wx.getSetting({
      //   success (res){
      //     if (res.authSetting['scope.userInfo']) {
      //       // 已经授权,可以直接调用 getUserInfo 获取头像昵称
      //       wx.getUserInfo({
      //         success: function(res) {
      //           console.warn(res.userInfo)
      //         }
      //       })
      //     }
      //   }
      // })
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userInfo']) {
            wx.authorize({
              scope: 'scope.userInfo',
              success () {
                // 已经授权,可以直接调用 getUserInfo 获取头像昵称
                wx.getUserInfo({
                  success: function(res) {
                    console.warn(res.userInfo)
                  }
                })
              }
            })
          }
        }
      })
    }
  }
};
</script>