index.vue 5.42 KB
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-09-12 10:20:03
 * @FilePath: /lls_program/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 { ref } from "vue";
import request from '@/utils/request';

</script>

<script>
import "./index.less";
import { getCurrentPageParam } from "@/utils/weapp";
import { returnToOriginalPage, silentAuth } from '@/utils/authRedirect'

export default {
  name: "authPage",
  mounted() {
    // 页面加载时优先尝试静默授权
    this.performAuth();
  },
  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: {
    performAuth() {
      // 优先尝试静默授权
      silentAuth().then(() => {
        // 静默授权成功,检查当前页面是否需要跳转
        const pages = Taro.getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const currentRoute = currentPage?.route;

        // 只有在auth页面时才需要跳转回原页面
        if (currentRoute === 'pages/auth/index') {
          returnToOriginalPage();
        }
      }).catch(() => {
        // 静默授权失败,执行手动授权
        this.manualAuth();
      });
    },
    manualAuth() {
      // 手动授权登陆
      Taro.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            Taro.showLoading({
              title: '授权中',
            })
            // 根据环境判断是否传递openid参数
            const requestData = {
              code: res.code,
            };

            // 测试环境下传递openid,正式环境不传递
            if (process.env.NODE_ENV === 'development') {
              // requestData.openid = 'h-008';
              // requestData.openid = 'h-009';
              // requestData.openid = 'h-010';
              // requestData.openid = 'h-011';
              // requestData.openid = 'h-012';
              // requestData.openid = 'h-013';
              // requestData.openid = 'oWbdFvkD5VtloC50wSNR9IWiU2q8';
              requestData.openid = 'oex8h5QZnZJto3ttvO6swSvylAQo';
            }

            request.post('/srv/?a=openid', requestData)
            .then(res => {
              if (res.data.code) {
                var cookie = res.cookies[0];
                if (cookie != null) {
                  wx.setStorageSync("sessionid", res.cookies[0]);//服务器返回的 Set-Cookie,保存到本地
                  //TAG 小程序绑定cookie
                  // 修改请求头
                  request.defaults.headers.cookie = res.cookies[0];
                  // TAG:处理分享跳转问题 - 使用新的重定向逻辑
                  returnToOriginalPage();
                  Taro.hideLoading();
                }
              } else {
                console.warn(res.data.msg);
                Taro.hideLoading();
              }
            })
            .catch(err => {
              console.error(err);
              Taro.hideLoading();
            });
          } else {
            console.log('登录失败!' + res.errMsg)
          }
        }
      })
    },
    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>