index.vue 2.67 KB
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2024-05-26 10:17:04
 * @FilePath: /xyxBooking-weapp/src/pages/auth/index.vue
 * @Description: 文件描述
-->
<template>
  <view class="auth-page">
    <view class="loading">
        <view>正在授权登录...</view>
    </view>
  </view>
</template>

<script setup>
import Taro, { useDidShow } from '@tarojs/taro'
import request from '@/utils/request';

useDidShow(() => {
    // 授权登陆
    Taro.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          Taro.showLoading({
            title: '授权中',
          })
          request.post('/srv/?a=openid', {
            code: res.code
          })
          .then(res => {
            if (res.data.code === 1) { // 成功
              var cookie = res.cookies ? res.cookies[0] : (res.header['Set-Cookie'] || res.header['set-cookie']);
              // 有些时候 cookie 可能是一个数组,或者分号分隔的字符串
              // axios-miniprogram 返回的 cookies 应该是一个数组
              
              if (cookie) {
                 // 处理 cookie 格式,如果包含分号,取第一个
                 if (Array.isArray(cookie)) cookie = cookie[0];
                 // 简单处理,通常服务器返回 PHPSESSID=xxx; path=/
                 // 我们存入 storage
                Taro.setStorageSync("sessionid", cookie);
                
                // 返回上一页
                Taro.hideLoading();
                Taro.navigateBack({
                    fail: () => {
                        Taro.reLaunch({ url: '/pages/index/index' })
                    }
                });
              } else {
                  console.warn('No cookie received');
                  Taro.hideLoading();
                  Taro.showToast({ title: '授权失败: 无Cookie', icon: 'none' });
              }
            } else {
              console.warn(res.data.msg);
              Taro.hideLoading();
              Taro.showToast({ title: res.data.msg || '授权失败', icon: 'none' });
            }
          })
          .catch(err => {
            console.error(err);
            Taro.hideLoading();
            Taro.showToast({ title: '网络错误', icon: 'none' });
          });
        } else {
          console.log('登录失败!' + res.errMsg)
          Taro.showToast({ title: '微信登录失败', icon: 'none' });
        }
      }
    })
})
</script>

<style lang="less">
.auth-page {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    .loading {
        text-align: center;
        color: #999;
    }
}
</style>