Просмотр исходного кода

feat: 微信授权登录相关逻辑

laiqi 1 год назад
Родитель
Сommit
fa82b9e873
4 измененных файлов с 80 добавлено и 37 удалено
  1. 3 2
      src/App.vue
  2. 60 29
      src/pages-sub/auth/index.vue
  3. 11 6
      src/pages/mine/index.vue
  4. 6 0
      src/utils/http.ts

+ 3 - 2
src/App.vue

@@ -5,8 +5,9 @@ import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
 onLaunch(() => {
   console.log('App Launch')
   // 检查是否已登录
-  const isLogin = uni.getStorageSync('token')
-  if (!isLogin) {
+  const loginInfo = uni.getStorageSync('loginInfo')
+
+  if (!(loginInfo && loginInfo.token)) {
     uni.navigateTo({ url: '/pages-sub/auth/index' })
   }
 })

+ 60 - 29
src/pages-sub/auth/index.vue

@@ -13,7 +13,9 @@
     <view class="text-2xl font-bold mb-8 mt-20">达州农机优惠劵</view>
     <view class="text-gray-500 text-sm mb-8">申请获取以下权限</view>
     <view class="text-gray-500 text-sm mb-8">获取您的公开信息(昵称、头像等)</view>
-    <wd-button type="success" round block @click="handleLogin">点击授权</wd-button>
+    <wd-button type="success" round block @click="handleLogin" :loading="loading">
+      点击授权
+    </wd-button>
   </view>
 </template>
 
@@ -22,46 +24,75 @@ import { getAuthCode } from '@/service/auth'
 import { onMounted } from 'vue'
 import { until } from '@vueuse/core'
 
+const loading = ref(false)
+
 // 微信登录
 const handleLogin = async () => {
-  uni.login({
-    provider: 'weixin',
-    onlyAuthorize: true,
-    success: async function (event) {
-      try {
-        const { loading, error, data } = useRequest(() => getAuthCode(event.code), {
-          immediate: true,
-        })
+  loading.value = true
+  wx.getUserProfile({
+    desc: '用于完善用户信息',
+    success: ({ userInfo }) => {
+      //   console.log('用户信息:', userInfo)
+      //   avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
+      //   city: ""
+      //   country: ""
+      //   gender: 0
+      //   is_demote: true
+      //   language: ""
+      //   nickName: "微信用户"
+      //   province: ""
+      uni.setStorageSync('userInfo', userInfo)
+
+      // 获取token
+      uni.login({
+        provider: 'weixin',
+        onlyAuthorize: true,
+        success: async function (event) {
+          try {
+            const { loading, error, data } = useRequest(() => getAuthCode(event.code), {
+              immediate: true,
+            })
 
-        // 等待数据加载完成
-        await until(loading).toBe(false)
+            // 等待数据加载完成
+            await until(loading).toBe(false)
 
-        if (!error.value && data.value) {
-          const { token, userid, openid } = data.value as any
+            if (!error.value && data.value) {
+              const { token, userid, openid } = data.value as any
 
-          uni.setStorageSync('token', token)
-          uni.setStorageSync('userid', userid)
-          uni.setStorageSync('openid', openid)
+              uni.setStorageSync('loginInfo', { token, userid, openid })
 
-          uni.switchTab({ url: '/pages/index/index' })
-        } else {
+              uni.switchTab({ url: '/pages/index/index' })
+            } else {
+              uni.showToast({
+                title: '授权失败,请重试',
+                icon: 'none',
+              })
+            }
+          } catch (err) {
+            console.error('授权失败:', err)
+            uni.showToast({
+              title: '授权失败,请重试',
+              icon: 'none',
+            })
+          }
+        },
+        fail: function (err) {
+          console.error('登录失败:', err)
           uni.showToast({
-            title: '授权失败,请重试',
+            title: '登录失败,请重试',
             icon: 'none',
           })
-        }
-      } catch (err) {
-        console.error('授权失败:', err)
-        uni.showToast({
-          title: '授权失败,请重试',
-          icon: 'none',
-        })
-      }
+        },
+        complete: () => {
+          loading.value = false
+        },
+      })
     },
     fail: function (err) {
-      console.error('登录失败:', err)
+      console.error('获取用户信息失败:', err)
+      loading.value = false
       uni.showToast({
-        title: '登录失败,请重试',
+        title: '获取用户信息失败,请重试',
         icon: 'none',
       })
     },

+ 11 - 6
src/pages/mine/index.vue

@@ -11,9 +11,9 @@
     <!-- 顶部用户信息区域 -->
     <view class="bg-blue-400 pt-12 pb-8 px-4 relative">
       <view class="flex items-center">
-        <view v-if="userInfo.avatar" class="w-16 h-16">
+        <view v-if="userInfo.avatarUrl" class="w-16 h-16">
           <image
-            :src="userInfo.avatar"
+            :src="userInfo.avatarUrl"
             class="w-full h-full rounded-full bg-white"
             mode="aspectFill"
           />
@@ -23,9 +23,9 @@
         </view>
         <view class="ml-4 text-white">
           <view class="text-xl font-bold">
-            {{ userInfo.isLogin ? userInfo.nickname : '未登录' }}
+            {{ userInfo.isLogin ? userInfo.nickName : '未登录' }}
           </view>
-          <view class="text-sm mt-1 opacity-90">当前游客身份</view>
+          <view class="text-sm mt-1 opacity-90" v-if="!userInfo.isLogin">当前游客身份</view>
         </view>
       </view>
     </view>
@@ -95,8 +95,13 @@ import { ref } from 'vue'
 // 用户信息
 const userInfo = ref({
   isLogin: false,
-  avatar: '',
-  nickname: '',
+  avatarUrl: '',
+  nickName: '',
+})
+
+onMounted(() => {
+  userInfo.value = uni.getStorageSync('userInfo')
+  userInfo.value.isLogin = uni.getStorageSync('loginInfo')?.token
 })
 
 // 页面跳转

+ 6 - 0
src/utils/http.ts

@@ -5,6 +5,12 @@ export const http = <T>(options: CustomRequestOptions) => {
   return new Promise<IResData<T>>((resolve, reject) => {
     uni.request({
       ...options,
+      header: Object.assign(
+        {
+          token: `${uni.getStorageSync('loginInfo')?.token}`,
+        },
+        options.header,
+      ),
       dataType: 'json',
       // #ifndef MP-WEIXIN
       responseType: 'json',