Browse Source

feat(login): 微信一键登录

Tim_Walker 2 years ago
parent
commit
c93c796397
7 changed files with 132 additions and 59 deletions
  1. 63 0
      src/api/login.js
  2. 0 13
      src/api/system.js
  3. 23 26
      src/pages/login/index.vue
  4. 3 2
      src/pages/mine/index.vue
  5. 9 7
      src/service/index.js
  6. 2 8
      src/store/getters.js
  7. 32 3
      src/store/modules/user.js

+ 63 - 0
src/api/login.js

@@ -0,0 +1,63 @@
+import { request } from '@/service';
+
+/**
+ * 通过wx.login()获取登录code令牌
+ * @returns
+ */
+export const getWxLoginCode = () => {
+  return new Promise((resolve, reject) => {
+    wx.login({
+      success(res) {
+        if (res.code) {
+          //发起网络请求log
+          resolve(res.code);
+        }
+      },
+    });
+  });
+};
+
+/**
+ * 微信一键注册/登录
+ * @param {*} data
+ * @returns
+ */
+export function loginByWxLoginCode(data) {
+  return request({
+    url: '/uc/oauth/token',
+    method: 'post',
+    header: {
+      'Content-Type': 'application/x-www-form-urlencoded',
+    },
+    data: data,
+    loadingText: '登录中...',
+  });
+}
+
+/**
+ *  通过手机号获取验证码
+ * @param {string} phoneNumber 电话号码
+ * @returns R
+ */
+export function getSmsCodeByPhone(phoneNumber) {
+  return request({
+    url: '/uc/login/captcha',
+    method: 'post',
+    data: {
+      mobile: phoneNumber,
+    },
+  });
+}
+
+/**
+ *  通过手机号验证码登录
+ * @param {*} data
+ * @returns
+ */
+export function loginByPhoneAndSmsCode(data) {
+  return request({
+    url: '/uc/login/captcha',
+    method: 'post',
+    data: data,
+  });
+}

+ 0 - 13
src/api/system.js

@@ -17,16 +17,3 @@ export const getOpenId = (appid, secret, code) => {
     });
   });
 };
-
-export const getWxLoginCode = () => {
-  return new Promise((resolve, reject) => {
-    wx.login({
-      success(res) {
-        if (res.code) {
-          //发起网络请求log
-          resolve(res.code);
-        }
-      },
-    });
-  });
-};

+ 23 - 26
src/pages/login/index.vue

@@ -1,8 +1,8 @@
 <template>
   <view class="container">
-    <u-image src="@/static/logo.png"></u-image>
+    <u-image src="@/static/logo.png" mode="widthFix"></u-image>
     <view class="login-btn-wrap">
-      <u-button shape="circle" type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">微信用户一键登录</u-button>
+      <u-button shape="circle" type="primary" :loading="loading" @tap="login">微信用户一键登录</u-button>
       <u-button shape="circle" :customStyle="{ 'margin-top': '20rpx' }" @tap="$Router.push('/pages/login/phoneLogin')">手机号登录/注册</u-button>
     </view>
     <view>
@@ -14,43 +14,37 @@
 </template>
 
 <script>
-import { getWxLoginCode, getOpenId } from '@/api/system.js';
-import { request } from '@/service';
+import { getWxLoginCode } from '@/api/login.js';
+
 export default {
   data() {
     return {
-      appid: 'wx962bee9cb47b1696',
-      secret: '366ebb364f2180d59de5c42e25a453ea',
+      loading: false,
       form: {
         client_id: 'chelvc_client',
         client_secret: 'qWBe6jD%GCuPPTkP',
         grant_type: 'wechat',
         token: '',
-        mobile: '',
       },
     };
   },
   methods: {
-    async getPhoneNumber(e) {
-      console.log(e);
-      // TODO: update appid and secret
-      if (e.detail.errMsg != 'getPhoneNumber:ok') return uni.$u.toast('请授权使用您的手机号');
-      this.form.mobile = e.detail.encryptedData;
+    async login() {
+      this.loading = true;
       this.form.token = await getWxLoginCode();
-      uni.getSystemInfoAsync({
-        success: res => {
-          console.log(res);
-        },
-      });
-      request({
-        url: '/uc/login',
-        method: 'post',
-        data: this.form,
-        header: {
-          'Content-type': 'application/form-data',
-        },
-        loadingText: '登录中...',
-      });
+      this.$store
+        .dispatch('LoginByWxCode', this.form)
+        .then(() => {
+          this.loading = false;
+          uni.$u.toast('登录成功');
+          setTimeout(() => {
+            this.$Router.pushTab('/pages/home/index');
+          }, 1500);
+        })
+        .catch(() => {
+          this.loading = false;
+          uni.$u.toast('登录失败');
+        });
     },
   },
 };
@@ -58,7 +52,10 @@ export default {
 
 <style scoped>
 .container {
+  padding: 0 20rpx;
+  box-sizing: border-box;
 }
 .login-btn-wrap {
+  margin-top: 40rpx;
 }
 </style>

+ 3 - 2
src/pages/mine/index.vue

@@ -6,7 +6,7 @@
           <u-avatar src="https://avatars.githubusercontent.com/u/6481596?v=4" size="80"></u-avatar>
         </view>
         <view class="user-base">
-          <view class="user-nickname">用户昵称</view>
+          <view class="user-nickname" @tap="$Router.push('/pages/login/index')">用户昵称</view>
           <view class="btn-wrap">
             <view class="btn-content" @tap="$Router.push('/client/settings/index')">设置</view>
             <view class="btn-content">认证</view>
@@ -15,7 +15,7 @@
       </view>
       <view>
         <u-grid :border="false" col="4">
-          <u-grid-item v-for="(listItem, listIndex) in list1" :key="listIndex">
+          <u-grid-item v-for="(listItem, listIndex) in list1" :key="listIndex" @tap="$Router.push(listItem.url)">
             <u-icon :customStyle="{ paddingTop: 20 + 'rpx' }" :name="listItem.name" :size="22"></u-icon>
             <text class="grid-text">{{ listItem.title }}</text>
           </u-grid-item>
@@ -82,6 +82,7 @@ export default {
         {
           name: 'hourglass',
           title: '优惠券',
+          url: '/client/coupon/index',
         },
       ],
       list2: [

+ 9 - 7
src/service/index.js

@@ -1,6 +1,7 @@
 import { getSystemInfoAsync } from '@/utils/system';
+import store from '@/store';
 
-const BASE_URL = 'http://test.chelvc.com/api';
+const BASE_URL = 'https://test.chelvc.com';
 const TIME_OUT = 60000;
 const errStatus = {
   200: '成功',
@@ -42,14 +43,15 @@ export function request(options) {
         options.header,
       ),
       success: res => {
-        if (res.statusCode === 200) {
-          resolve(res.data);
-        } else {
+        if (res.statusCode !== 200) {
           uni.showToast({
             icon: 'none',
-            title: errStatus[res.statusCode],
+            title: res.data.message || errStatus[res.statusCode],
             duration: 2000,
           });
+          reject(res);
+        } else {
+          resolve(res.data);
         }
       },
       fail: err => {
@@ -71,7 +73,7 @@ export function request(options) {
 }
 
 export function send(options) {
-  // TODO: add token in this method when login successfully
-  // const access_token = store.getters.access_token;
+  const access_token = store.getters.access_token;
+  options.header['Authorization'] = `Bearer ${access_token}`;
   return request(options);
 }

+ 2 - 8
src/store/getters.js

@@ -1,12 +1,6 @@
-/*
- * @Author: yizhiyang
- * @LastEditors: yizhiyang
- * @Date: 2023-03-30 23:20:41
- * @LastEditTime: 2023-03-30 23:43:21
- * @FilePath: \chelvc-custom\src\store\getters.js
- */
 const getters = {
-  test: state => state.user.test,
+  access_token: state => state.user.access_token,
+  refresh_token: state => state.user.refresh_token,
 };
 
 export default getters;

+ 32 - 3
src/store/modules/user.js

@@ -1,7 +1,36 @@
+import { setCache, getCache } from '@/utils/cache';
+import { loginByWxLoginCode } from '@/api/login';
+
 export default {
   state: () => ({
-    test: 'test',
+    access_token: getCache('access_token') || '',
+    refresh_token: getCache('refresh_token') || '',
   }),
-  mutations: {},
-  actions: {},
+  mutations: {
+    SET_ACCESS_TOKEN(state, data) {
+      state.access_token = data;
+      setCache('access_token', state.access_token);
+    },
+    SET_REFRESH_TOKEN(state, data) {
+      state.refresh_token = data;
+      setCache('refresh_token', state.refresh_token);
+    },
+  },
+  actions: {
+    LoginByWxCode({ commit }, data) {
+      return new Promise((resolve, reject) => {
+        loginByWxLoginCode(data)
+          .then(res => {
+            if (res.access_token) {
+              commit('SET_ACCESS_TOKEN', res.access_token);
+              commit('SET_REFRESH_TOKEN', res.refresh_token);
+              resolve();
+            }
+          })
+          .catch(err => {
+            reject(err);
+          });
+      });
+    },
+  },
 };