Jelajahi Sumber

登录优化

wkw 3 minggu lalu
induk
melakukan
31064eee11

+ 1 - 9
app.js

@@ -1,15 +1,7 @@
 import {login} from './api/user';
 import { FETCH_AND_FORMAT_USER_INFO } from './utils/util.js'
 App({
-  onLaunch() {
-    // 登录
-    wx.login({
-      success: async ret => {
-        const res = await login({code:ret.code});
-        wx.setStorageSync('token', res.data.token_type + ' ' + res.data.access_token);
-        this.globalData.userInfo = await FETCH_AND_FORMAT_USER_INFO();
-      }
-    })
+  async onLaunch() {
   },
   globalData: {
     userInfo: null,

+ 3 - 3
components/Countdown/Countdown.js

@@ -22,9 +22,9 @@ Component({
   },
   lifetimes: {
     attached() {
-      if (this.properties.endTime && this.properties.startTime) {
+      if (this.properties.endTime) {
         const target = new Date(this.properties.endTime.replace(/-/g, '/')).getTime();
-        const start = new Date(this.properties.startTime.replace(/-/g, '/')).getTime();
+        const start = this.properties.startTime?new Date(this.properties.startTime.replace(/-/g, '/')).getTime():0;
         this.startCountdown(target,start);
       }
     },
@@ -47,7 +47,7 @@ Component({
           this.triggerEvent("finish"); // 通知父组件倒计时结束
           return;
         }
-        if(startTime > now && this.data.isStart){
+        if(startTime > 0 && startTime > now && this.data.isStart){
           return;
         }
         const days = Math.floor(diff / (60 * 60 * 24));

+ 0 - 1
components/Countdown/Countdown.wxss

@@ -1,7 +1,6 @@
 .calendar-item{
   display: flex;
   gap: 28rpx;
-  margin-top: 40rpx;
 }
 .item-lf{
   background: #FFC200;

+ 24 - 12
custom-tab-bar/index.js

@@ -26,6 +26,7 @@ Component({
     ],
     showShare: false,
     showAgreementModal:false,
+    showPoster:false,
     programConfig: {}
   },
   lifetimes: {
@@ -50,19 +51,30 @@ Component({
     openShowAgreementModal(){
       this.setData({ showAgreementModal: true })
     },
+    onClosePoster(){
+      this.setData({ showPoster: true })
+    },
+    openPoster() {
+      this.setData({
+        showShare:false,
+        showPoster: true
+      });
+    },
     // 分享逻辑
-    onShareAppMessage() {
-      return {
-        path: '/pages/index/index',
-        imageUrl: app.globalData.programConfig.share_img
+    onShareAppMessage(res) {
+      const shareType = res.target.dataset.type;
+      if (shareType === 'poster') {
+        // return {
+        //   title: '分享我的专属海报',
+        //   path: '/pages/index/index',
+        //   imageUrl: app.globalData.programConfig.share_img
+        // }
+      } else if (shareType === 'friend') {
+        return {
+          path: '/pages/index/index',
+          imageUrl: app.globalData.programConfig.share_img
+        }
       }
-    },
-    // onShareTimeline() {
-    //   return {
-    //     title: '分享到朋友圈标题',
-    //     query: 'id=123',
-    //     imageUrl: '/static/tabbar/tp.png'
-    //   }
-    // },
+    }
   }
 })

+ 17 - 5
custom-tab-bar/index.wxml

@@ -15,14 +15,15 @@
 >
   <view class="share-container">
     <view class="share-options">
-      <button class="share-item" open-type="share">
+      <button class="share-item" open-type="share" data-type="friend">
         <image class="share-icon" src="/static/tabbar/weixin.png" mode="aspectFit" />
         <text class="share-text">微信好友</text>
       </button>
-      <!-- <button class="share-item" open-type="share" data-type="timeline">
+
+      <button class="share-item" bindtap="openPoster">
         <image class="share-icon" src="/static/tabbar/tp.png" mode="aspectFit" />
-        <text class="share-text">朋友圈</text>
-      </button> -->
+        <text class="share-text">海报转发</text>
+      </button>
     </view>
     <!-- 取消按钮 -->
     <view class="share-cancel" bindtap="onCloseShare" hover-class="btn-hover" hover-start-time="50">
@@ -44,4 +45,15 @@
     <view class="box-text" bindtap="onPhone" wx:if="{{programConfig.customer_phone}}">客服电话:{{programConfig.customer_phone}}</view>
     <view class="box-text" wx:if="{{programConfig.customer_email}}">客服邮箱:{{programConfig.customer_email}}</view>
   </view>
-</van-dialog>
+</van-dialog>
+
+<!-- 弹框展示海报 -->
+<van-popup show="{{showPoster}}" position="center" bind:close="onClosePoster" close-on-click-overlay="{{true}}">
+  <view class="poster-container">
+    <image src="/static/image/address.png" mode="widthFix" class="poster-img" />
+    <view class="poster-actions">
+      <button bindtap="savePoster">保存到相册</button>
+      <button open-type="share" data-type="poster">发送朋友</button>
+    </view>
+  </view>
+</van-popup>

+ 47 - 15
pages/index/index.js

@@ -1,5 +1,6 @@
 import {miniProgramConfig} from '../../api/other';
 import {BASE_URL} from '../../utils/request';
+import {isLoggedIn,doLogin} from '../../utils/auth';
 const app = getApp();
 Page({
   data: {
@@ -8,7 +9,9 @@ Page({
     introduction:'',
     start_time:'',
     end_time:'',
-    ad_img:''
+    ad_img:'',
+    pendingAction:null,//按钮类型
+    loggedIn:false
   },
   async onLoad(){
     const res = await miniProgramConfig();
@@ -26,6 +29,9 @@ Page({
       this.getTabBar().setData({
         selected: 0
       })
+      this.setData({
+        loggedIn: isLoggedIn()
+      })
     }
   },
   goPage(e){
@@ -40,24 +46,50 @@ Page({
       })
     }
   },
-  goRegister() {
-    wx.navigateTo({
-      url: '/pages/register/register'
-    })
-  },
-  // 打开分享弹框
-  onShowShare() {
-    const tabbar = this.getTabBar && this.getTabBar()
-    if (tabbar && tabbar.openShare) {
-      tabbar.openShare()
-    } else {
-      console.log("没找到 tabbar 组件")
-    }
-  },
   onShareAppMessage() {
     return {
       path: '/pages/index/index',
       imageUrl: app.globalData.programConfig.share_img
     }
   },
+  goRegister(e) {
+    const action = e.currentTarget.dataset.action;
+    if (isLoggedIn()) {
+      this.doAction(action)
+    }
+  },
+  async onGetPhoneNumber(e) {
+    const action = e.currentTarget.dataset.action;
+    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
+      wx.showToast({ title: '授权失败', icon: 'none' })
+      return
+    }
+    const { encryptedData, iv } = e.detail;
+    try {
+      wx.login({
+        success: async loginRes => {
+          await doLogin({
+            code: loginRes.code,
+            // phone: { encryptedData, iv }
+          });
+          this.setData({ loggedIn: isLoggedIn() })
+          this.doAction(action);
+        }
+      })
+    } catch (err) {
+      wx.showToast({ title: '登录失败,请重试', icon: 'none' });
+      console.error(err);
+    }
+  },
+  doAction(action) {
+    if (action === 'register') wx.navigateTo({ url: '/pages/register/register' });
+    if (action === 'invite'){
+      const tabbar = this.getTabBar && this.getTabBar()
+      if (tabbar && tabbar.openShare) {
+        tabbar.openShare()
+      } else {
+        console.log("没找到 tabbar 组件")
+      }
+    };
+  }
 })

+ 7 - 3
pages/index/index.wxml

@@ -7,6 +7,7 @@
       interval="{{3000}}"
       duration="{{500}}"
       circular="{{true}}"
+      autoplay="{{true}}"
     >
       <block wx:for="{{banners}}" wx:key="index">
         <swiper-item>
@@ -36,18 +37,21 @@
           </view>
           <!-- 日历 -->
           <block wx:if="{{start_time && end_time}}">
-            <countdown start-time="{{start_time}}" end-time="{{end_time}}" />
+            <view class="countdown">倒计时开跑时间</view>
+            <countdown end-time="{{start_time}}" />
           </block>
         </view>
         <!-- 报名 -->
         <view class="registration">
-          <view class="registration-lf" bindtap="goRegister">
+          <view class="registration-lf" bindtap="goRegister" data-action="register">
             <image class="lf-bg-img" src="{{baseUrl + '/static/image/registration.png'}}" mode="aspectFit" />
             <image class="registration-img" src="/static/image/lkbm.png" mode="aspectFit" />
+            <button wx:if="{{!loggedIn}}" class="cover-btn" open-type="getPhoneNumber"      bindgetphonenumber="onGetPhoneNumber" data-action="register"></button>
           </view>
-          <view class="registration-ri" bindtap="onShowShare">
+          <view class="registration-ri" bindtap="goRegister" data-action="invite">
             <image class="ri-bg-img" src="{{baseUrl + '/static/image/invitation.png'}}" mode="aspectFit" />
             <image class="registration-img" src="/static/image/yqhy.png" mode="aspectFit"/>
+            <button wx:if="{{!loggedIn}}" class="cover-btn" open-type="getPhoneNumber" bindgetphonenumber="onGetPhoneNumber" data-action="invite"></button>
           </view>
         </view>
         <image class="ad-img" wx:if="{{ad_img}}" src="{{ad_img}}" mode="widthFix"/>

+ 14 - 0
pages/index/index.wxss

@@ -84,4 +84,18 @@
 }
 .ad-img{
   width: 100%;
+}
+.countdown{
+  margin: 20rpx 0 30rpx;
+  text-align: center;
+  font-size: 26rpx;
+}
+.cover-btn {
+  position: absolute;
+  width: 100%;
+  height: 100%;
+  top: 0;
+  left: 0;
+  opacity: 0; /* 完全透明 */
+  z-index: 10;
 }

+ 60 - 64
pages/mine/mine.js

@@ -1,7 +1,8 @@
 import {BASE_URL} from '../../utils/request';
 import { uploadImage } from '../../utils/upload.js';
 import { MAKE_PHONE_CALL } from '../../utils/util.js';
-import {userModify} from '../../api/user';
+import { userModify } from '../../api/user';
+import { isLoggedIn, doLogin } from '../../utils/auth';
 const app = getApp();
 Page({
   data: {
@@ -15,8 +16,25 @@ Page({
     ],
     userInfo: {},
     programConfig:{},
-    baseUrl:BASE_URL
+    baseUrl:BASE_URL,
+    loggedIn: isLoggedIn()
   },
+  onLoad(options) {
+    this.setData({
+      userInfo: app.globalData.userInfo,
+      programConfig: app.globalData.programConfig
+    });
+  },
+  onShow() {
+    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
+      this.getTabBar().setData({ selected: 2 })
+    }
+    this.setData({
+      userInfo: app.globalData.userInfo,
+      loggedIn: isLoggedIn()
+    });
+  },
+
   goPage(e){
     const index = e.currentTarget.dataset.index;
     const pageMap = {
@@ -32,45 +50,23 @@ Page({
       const tabbar = this.getTabBar && this.getTabBar();
       if (tabbar && tabbar.openShowAgreementModal) {
         tabbar.openShowAgreementModal()
-      } else {
-        console.log("没找到 tabbar 组件")
       }
     }
   },
-  onLoad(options) {
-    this.setData({
-      userInfo: app.globalData.userInfo,
-      programConfig:app.globalData.programConfig
-    });
-  },
-  onShow() {
-    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
-      this.getTabBar().setData({ selected: 2 })
-    }
-    this.setData({
-      userInfo: app.globalData.userInfo
-    });
-  },
-   // 头像
-   async onChooseAvatar(e) {
+
+  // 头像选择
+  async onChooseAvatar(e) {
     const { avatarUrl } = e.detail;
-    // 上传到服务器
     const res = await uploadImage(avatarUrl);
-    this.setData({
-      "userInfo.avatar":avatarUrl
-    });
+    this.setData({ "userInfo.avatar": avatarUrl });
     this.onSave(res.path);
   },
-  async onSave(pathUrl){
-    const res = await userModify({avatar:pathUrl});
+
+  async onSave(pathUrl) {
+    const res = await userModify({ avatar: pathUrl });
     if(res.code == 200){
-      // wx.showToast({
-      //   title: '更新成功',
-      //   icon: 'none',
-      //   duration: 2000
-      // });
       app.globalData.userInfo = res.data;
-    }else{
+    } else {
       wx.showToast({
         title: res.message || '更新失败',
         icon: 'none',
@@ -78,42 +74,42 @@ Page({
       });
     }
   },
-  onPhone(){
+  onPhone() {
     MAKE_PHONE_CALL(this.data.programConfig.customer_phone);
   },
 
-  /**
-   * 生命周期函数--监听页面隐藏
-   */
-  onHide() {
-
-  },
-
-  /**
-   * 生命周期函数--监听页面卸载
-   */
-  onUnload() {
-
+  handleActionWithLogin(e) {
+    const index = e.currentTarget.dataset.index;
+    if (index >= 2 && index <= 4 && !isLoggedIn()) {
+      return;
+    }
+    this.doAction(index);
   },
-
-  /**
-   * 页面相关事件处理函数--监听用户下拉动作
-   */
-  onPullDownRefresh() {
-
+  async onGetPhoneNumber(e) {
+    const index = e.currentTarget.dataset.index;
+    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
+      wx.showToast({ title: '授权失败', icon: 'none' });
+      return;
+    }
+    const { encryptedData, iv } = e.detail;
+    try {
+      wx.login({
+        success: async loginRes => {
+          await doLogin({
+            code: loginRes.code,
+            // phone: { encryptedData, iv } 可按接口需要传
+          });
+          this.setData({ loggedIn: true });
+          this.doAction(index);
+        }
+      });
+    } catch (err) {
+      wx.showToast({ title: '登录失败,请重试', icon: 'none' });
+      console.error(err);
+    }
   },
 
-  /**
-   * 页面上拉触底事件的处理函数
-   */
-  onReachBottom() {
-
+  doAction(index) {
+    this.goPage({ currentTarget: { dataset: { index } } });
   },
-
-  /**
-   * 用户点击右上角分享
-   */
-  onShareAppMessage() {
-
-  }
-})
+})

+ 17 - 4
pages/mine/mine.wxml

@@ -3,21 +3,34 @@
   <view class="mine">
     <view class="user-box">
       <button class="avatar-wrapper" open-type="chooseAvatar"   bind:chooseavatar="onChooseAvatar">
-        <van-image lazy-load round width="144rpx" height="144rpx" fit="cover" src="{{userInfo.avatar}}" />
+        <van-image lazy-load round width="144rpx" height="144rpx" fit="cover" src="{{userInfo.avatar || '/static/image/cat.jpeg'}}" />
       </button>
-      <view class="user-text mt28">{{userInfo.nickname}}</view>
-      <view class="user-text user-number" wx:if="{{userInfo.competitionNo}}">参赛号:{{userInfo.competitionNo}}</view>
+      <view class="user-text mt28">{{userInfo.nickname || '游客'}}</view>
+      <view class="user-text user-number" wx:if="{{userInfo.competitionNo}}">报名号:{{userInfo.competitionNo}}</view>
     </view>
     <view class="bg-color">
       <view class="content">
         <view class="card-box">
-          <van-cell is-link wx:for="{{menuList}}" wx:key="index" class="{{index === menuList.length - 1 ? 'last-cell' : ''}}" bind:click="goPage" data-index="{{index}}">
+          <van-cell 
+            is-link 
+            wx:for="{{menuList}}" 
+            wx:key="index" 
+            bind:click="handleActionWithLogin" 
+            data-index="{{index}}"
+            class="{{index === menuList.length - 1 ? 'last-cell' : ''}}">
             <view slot="icon">
               <image class="card-img" src="{{item.icon}}" mode="aspectFit"/>
             </view>
             <view slot="title">
               <view class="van-cell-text">{{item.title}}</view>
             </view>
+
+            <!-- 未登录覆盖授权按钮 -->
+            <button 
+              wx:if="{{!loggedIn && index >= 2 && index <= 4}}" 
+              class="cover-btn" 
+              open-type="getPhoneNumber" bindgetphonenumber="onGetPhoneNumber"
+              data-index="{{index}}"></button>
           </van-cell>
         </view>
       </view>

+ 11 - 0
pages/mine/mine.wxss

@@ -110,3 +110,14 @@ button::after {
 .van-dialog__header{
   font-weight: bold !important;
 }
+.cover-btn {
+  position: absolute;
+  width: 100% !important;
+  height: 100%;
+  top: 0;
+  left: 0;
+  right: 0;
+  opacity: 0;
+  z-index: 10;
+}
+

+ 11 - 1
pages/register/register.js

@@ -14,7 +14,8 @@ Page({
       // competition_no: '', // 比赛ID
       competition_image: '' // 上传的图片路径
     },
-    phoneError: '', 
+    phoneError: '',
+    raceNumberError:'',
     genders: ['女', '男'],
     showPicker: false,
     fileList: [],
@@ -119,6 +120,7 @@ Page({
   },
   // 输入框数据绑定
   onInput(e) {
+    console.log(e)
     const field = e.currentTarget.dataset.field;
     const value = e.detail;
     // 手机号单独做校验
@@ -130,6 +132,14 @@ Page({
         this.setData({ phoneError: '' });
       }
     }
+    if (field === 'race_number') {
+      const regIdCard = /^\d{18}$/;
+      if (value && !regIdCard.test(value)) {
+        this.setData({ raceNumberError: '身份证号格式不正确' });
+      }else{
+        this.setData({ raceNumberError: '' });
+      }
+    }
     this.setData({
       formData: { ...this.data.formData, [field]: value }
     }, () => this.checkFormValid());

+ 5 - 3
pages/register/register.wxml

@@ -72,7 +72,9 @@
             data-field="race_number"
             placeholder="请输入身份证号"
             border="{{ false }}"
-          />
+          >
+            <view class="error-text">{{raceNumberError}}</view>
+          </van-field>
         </view>
 
         <!-- 参赛号码 -->
@@ -95,7 +97,7 @@
             <block wx:if="{{filePath}}">
               <block wx:if="{{fileType === 'image'}}">
                 <view class="preview-wrap">
-                  <image src="{{filePath}}" class="preview-img" mode="aspectFit" data-src="{{filePath}}" bindtap="previewImage"/>
+                  <image src="{{filePath}}" class="preview-img" mode="aspectFill" data-src="{{filePath}}" bindtap="previewImage"/>
                   <view class="delete-btn" bindtap="removeFile">
                     <van-icon name="cross" color="#fff" size="16" class="delete-btn-icon"/>
                   </view>
@@ -113,7 +115,7 @@
             <block wx:if="{{!filePath}}">
               <view class="uploader-text" bindtap="chooseFile">
                 <image class="uploader-img" src="/static/image/xj.png" mode="aspectFit"/>
-                <view>上传图片</view>
+                <view>历史完赛证明上传</view>
               </view>
             </block>
           </view>

+ 1 - 1
pages/registrationRecords/registrationRecords.wxml

@@ -24,7 +24,7 @@
           <van-cell title="手机号" value="{{item.phone}}" border="{{ false }}" />
           <van-cell title="性别" value="{{item.genderText}}" border="{{ false }}" />
           <van-cell title="身份证号" value="{{item.race_number}}" border="{{ false }}" />
-          <van-cell custom-class="cell-list" title="参赛号码" value="{{item.competition_no}}" border="{{ false }}" />
+          <van-cell custom-class="cell-list" title="报名号码" value="{{item.competition_no}}" border="{{ false }}" />
         </view>
       </view>
     </block>

TEMPAT SAMPAH
static/image/cat.jpeg


+ 0 - 31
utils/amap-wx.130.js

@@ -1,31 +0,0 @@
-function AMapWX(a){this.key=a.key;this.requestConfig={key:a.key,s:"rsx",platform:"WXJS",appname:a.key,sdkversion:"1.2.0",logversion:"2.0"};this.MeRequestConfig={key:a.key,serviceName:"https://restapi.amap.com/rest/me"}}
-AMapWX.prototype.getWxLocation=function(a,b){wx.getLocation({type:"gcj02",success:function(c){c=c.longitude+","+c.latitude;wx.setStorage({key:"userLocation",data:c});b(c)},fail:function(c){wx.getStorage({key:"userLocation",success:function(d){d.data&&b(d.data)}});a.fail({errCode:"0",errMsg:c.errMsg||""})}})};
-AMapWX.prototype.getMEKeywordsSearch=function(a){if(!a.options)return a.fail({errCode:"0",errMsg:"\u7f3a\u5c11\u5fc5\u8981\u53c2\u6570"});var b=a.options,c=this.MeRequestConfig,d={key:c.key,s:"rsx",platform:"WXJS",appname:a.key,sdkversion:"1.2.0",logversion:"2.0"};b.layerId&&(d.layerId=b.layerId);b.keywords&&(d.keywords=b.keywords);b.city&&(d.city=b.city);b.filter&&(d.filter=b.filter);b.sortrule&&(d.sortrule=b.sortrule);b.pageNum&&(d.pageNum=b.pageNum);b.pageSize&&(d.pageSize=b.pageSize);b.sig&&(d.sig=
-b.sig);wx.request({url:c.serviceName+"/cpoint/datasearch/local",data:d,method:"GET",header:{"content-type":"application/json"},success:function(e){(e=e.data)&&e.status&&"1"===e.status&&0===e.code?a.success(e.data):a.fail({errCode:"0",errMsg:e})},fail:function(e){a.fail({errCode:"0",errMsg:e.errMsg||""})}})};
-AMapWX.prototype.getMEIdSearch=function(a){if(!a.options)return a.fail({errCode:"0",errMsg:"\u7f3a\u5c11\u5fc5\u8981\u53c2\u6570"});var b=a.options,c=this.MeRequestConfig,d={key:c.key,s:"rsx",platform:"WXJS",appname:a.key,sdkversion:"1.2.0",logversion:"2.0"};b.layerId&&(d.layerId=b.layerId);b.id&&(d.id=b.id);b.sig&&(d.sig=b.sig);wx.request({url:c.serviceName+"/cpoint/datasearch/id",data:d,method:"GET",header:{"content-type":"application/json"},success:function(e){(e=e.data)&&e.status&&"1"===e.status&&
-0===e.code?a.success(e.data):a.fail({errCode:"0",errMsg:e})},fail:function(e){a.fail({errCode:"0",errMsg:e.errMsg||""})}})};
-AMapWX.prototype.getMEPolygonSearch=function(a){if(!a.options)return a.fail({errCode:"0",errMsg:"\u7f3a\u5c11\u5fc5\u8981\u53c2\u6570"});var b=a.options,c=this.MeRequestConfig,d={key:c.key,s:"rsx",platform:"WXJS",appname:a.key,sdkversion:"1.2.0",logversion:"2.0"};b.layerId&&(d.layerId=b.layerId);b.keywords&&(d.keywords=b.keywords);b.polygon&&(d.polygon=b.polygon);b.filter&&(d.filter=b.filter);b.sortrule&&(d.sortrule=b.sortrule);b.pageNum&&(d.pageNum=b.pageNum);b.pageSize&&(d.pageSize=b.pageSize);
-b.sig&&(d.sig=b.sig);wx.request({url:c.serviceName+"/cpoint/datasearch/polygon",data:d,method:"GET",header:{"content-type":"application/json"},success:function(e){(e=e.data)&&e.status&&"1"===e.status&&0===e.code?a.success(e.data):a.fail({errCode:"0",errMsg:e})},fail:function(e){a.fail({errCode:"0",errMsg:e.errMsg||""})}})};
-AMapWX.prototype.getMEaroundSearch=function(a){if(!a.options)return a.fail({errCode:"0",errMsg:"\u7f3a\u5c11\u5fc5\u8981\u53c2\u6570"});var b=a.options,c=this.MeRequestConfig,d={key:c.key,s:"rsx",platform:"WXJS",appname:a.key,sdkversion:"1.2.0",logversion:"2.0"};b.layerId&&(d.layerId=b.layerId);b.keywords&&(d.keywords=b.keywords);b.center&&(d.center=b.center);b.radius&&(d.radius=b.radius);b.filter&&(d.filter=b.filter);b.sortrule&&(d.sortrule=b.sortrule);b.pageNum&&(d.pageNum=b.pageNum);b.pageSize&&
-(d.pageSize=b.pageSize);b.sig&&(d.sig=b.sig);wx.request({url:c.serviceName+"/cpoint/datasearch/around",data:d,method:"GET",header:{"content-type":"application/json"},success:function(e){(e=e.data)&&e.status&&"1"===e.status&&0===e.code?a.success(e.data):a.fail({errCode:"0",errMsg:e})},fail:function(e){a.fail({errCode:"0",errMsg:e.errMsg||""})}})};
-AMapWX.prototype.getGeo=function(a){var b=this.requestConfig,c=a.options;b={key:this.key,extensions:"all",s:b.s,platform:b.platform,appname:this.key,sdkversion:b.sdkversion,logversion:b.logversion};c.address&&(b.address=c.address);c.city&&(b.city=c.city);c.batch&&(b.batch=c.batch);c.sig&&(b.sig=c.sig);wx.request({url:"https://restapi.amap.com/v3/geocode/geo",data:b,method:"GET",header:{"content-type":"application/json"},success:function(d){(d=d.data)&&d.status&&"1"===d.status?a.success(d):a.fail({errCode:"0",
-errMsg:d})},fail:function(d){a.fail({errCode:"0",errMsg:d.errMsg||""})}})};
-AMapWX.prototype.getRegeo=function(a){function b(d){var e=c.requestConfig;wx.request({url:"https://restapi.amap.com/v3/geocode/regeo",data:{key:c.key,location:d,extensions:"all",s:e.s,platform:e.platform,appname:c.key,sdkversion:e.sdkversion,logversion:e.logversion},method:"GET",header:{"content-type":"application/json"},success:function(g){if(g.data.status&&"1"==g.data.status){g=g.data.regeocode;var h=g.addressComponent,f=[],k=g.roads[0].name+"\u9644\u8fd1",m=d.split(",")[0],n=d.split(",")[1];if(g.pois&&
-g.pois[0]){k=g.pois[0].name+"\u9644\u8fd1";var l=g.pois[0].location;l&&(m=parseFloat(l.split(",")[0]),n=parseFloat(l.split(",")[1]))}h.provice&&f.push(h.provice);h.city&&f.push(h.city);h.district&&f.push(h.district);h.streetNumber&&h.streetNumber.street&&h.streetNumber.number?(f.push(h.streetNumber.street),f.push(h.streetNumber.number)):f.push(g.roads[0].name);f=f.join("");a.success([{iconPath:a.iconPath,width:a.iconWidth,height:a.iconHeight,name:f,desc:k,longitude:m,latitude:n,id:0,regeocodeData:g}])}else a.fail({errCode:g.data.infocode,
-errMsg:g.data.info})},fail:function(g){a.fail({errCode:"0",errMsg:g.errMsg||""})}})}var c=this;a.location?b(a.location):c.getWxLocation(a,function(d){b(d)})};
-AMapWX.prototype.getWeather=function(a){function b(g){var h="base";a.type&&"forecast"==a.type&&(h="all");wx.request({url:"https://restapi.amap.com/v3/weather/weatherInfo",data:{key:d.key,city:g,extensions:h,s:e.s,platform:e.platform,appname:d.key,sdkversion:e.sdkversion,logversion:e.logversion},method:"GET",header:{"content-type":"application/json"},success:function(f){if(f.data.status&&"1"==f.data.status)if(f.data.lives){if((f=f.data.lives)&&0<f.length){f=f[0];var k={city:{text:"\u57ce\u5e02",data:f.city},
-weather:{text:"\u5929\u6c14",data:f.weather},temperature:{text:"\u6e29\u5ea6",data:f.temperature},winddirection:{text:"\u98ce\u5411",data:f.winddirection+"\u98ce"},windpower:{text:"\u98ce\u529b",data:f.windpower+"\u7ea7"},humidity:{text:"\u6e7f\u5ea6",data:f.humidity+"%"}};k.liveData=f;a.success(k)}}else f.data.forecasts&&f.data.forecasts[0]&&a.success({forecast:f.data.forecasts[0]});else a.fail({errCode:f.data.infocode,errMsg:f.data.info})},fail:function(f){a.fail({errCode:"0",errMsg:f.errMsg||""})}})}
-function c(g){wx.request({url:"https://restapi.amap.com/v3/geocode/regeo",data:{key:d.key,location:g,extensions:"all",s:e.s,platform:e.platform,appname:d.key,sdkversion:e.sdkversion,logversion:e.logversion},method:"GET",header:{"content-type":"application/json"},success:function(h){if(h.data.status&&"1"==h.data.status){h=h.data.regeocode;if(h.addressComponent)var f=h.addressComponent.adcode;else h.aois&&0<h.aois.length&&(f=h.aois[0].adcode);b(f)}else a.fail({errCode:h.data.infocode,errMsg:h.data.info})},
-fail:function(h){a.fail({errCode:"0",errMsg:h.errMsg||""})}})}var d=this,e=d.requestConfig;a.city?b(a.city):d.getWxLocation(a,function(g){c(g)})};
-AMapWX.prototype.getPoiAround=function(a){function b(e){e={key:c.key,location:e,s:d.s,platform:d.platform,appname:c.key,sdkversion:d.sdkversion,logversion:d.logversion};a.querytypes&&(e.types=a.querytypes);a.querykeywords&&(e.keywords=a.querykeywords);wx.request({url:"https://restapi.amap.com/v3/place/around",data:e,method:"GET",header:{"content-type":"application/json"},success:function(g){if(g.data.status&&"1"==g.data.status){if((g=g.data)&&g.pois){for(var h=[],f=0;f<g.pois.length;f++){var k=0==
-f?a.iconPathSelected:a.iconPath;h.push({latitude:parseFloat(g.pois[f].location.split(",")[1]),longitude:parseFloat(g.pois[f].location.split(",")[0]),iconPath:k,width:22,height:32,id:f,name:g.pois[f].name,address:g.pois[f].address})}a.success({markers:h,poisData:g.pois})}}else a.fail({errCode:g.data.infocode,errMsg:g.data.info})},fail:function(g){a.fail({errCode:"0",errMsg:g.errMsg||""})}})}var c=this,d=c.requestConfig;a.location?b(a.location):c.getWxLocation(a,function(e){b(e)})};
-AMapWX.prototype.getStaticmap=function(a){function b(e){c.push("location="+e);a.zoom&&c.push("zoom="+a.zoom);a.size&&c.push("size="+a.size);a.scale&&c.push("scale="+a.scale);a.markers&&c.push("markers="+a.markers);a.labels&&c.push("labels="+a.labels);a.paths&&c.push("paths="+a.paths);a.traffic&&c.push("traffic="+a.traffic);e="https://restapi.amap.com/v3/staticmap?"+c.join("&");a.success({url:e})}var c=[];c.push("key="+this.key);var d=this.requestConfig;c.push("s="+d.s);c.push("platform="+d.platform);
-c.push("appname="+d.appname);c.push("sdkversion="+d.sdkversion);c.push("logversion="+d.logversion);a.location?b(a.location):this.getWxLocation(a,function(e){b(e)})};
-AMapWX.prototype.getInputtips=function(a){var b=Object.assign({},this.requestConfig);a.location&&(b.location=a.location);a.keywords&&(b.keywords=a.keywords);a.type&&(b.type=a.type);a.city&&(b.city=a.city);a.citylimit&&(b.citylimit=a.citylimit);wx.request({url:"https://restapi.amap.com/v3/assistant/inputtips",data:b,method:"GET",header:{"content-type":"application/json"},success:function(c){c&&c.data&&c.data.tips&&a.success({tips:c.data.tips})},fail:function(c){a.fail({errCode:"0",errMsg:c.errMsg||
-""})}})};
-AMapWX.prototype.getDrivingRoute=function(a){var b=Object.assign({},this.requestConfig);a.origin&&(b.origin=a.origin);a.destination&&(b.destination=a.destination);a.strategy&&(b.strategy=a.strategy);a.waypoints&&(b.waypoints=a.waypoints);a.avoidpolygons&&(b.avoidpolygons=a.avoidpolygons);a.avoidroad&&(b.avoidroad=a.avoidroad);wx.request({url:"https://restapi.amap.com/v3/direction/driving",data:b,method:"GET",header:{"content-type":"application/json"},success:function(c){c&&c.data&&c.data.route&&a.success({paths:c.data.route.paths,
-taxi_cost:c.data.route.taxi_cost||""})},fail:function(c){a.fail({errCode:"0",errMsg:c.errMsg||""})}})};
-AMapWX.prototype.getWalkingRoute=function(a){var b=Object.assign({},this.requestConfig);a.origin&&(b.origin=a.origin);a.destination&&(b.destination=a.destination);wx.request({url:"https://restapi.amap.com/v3/direction/walking",data:b,method:"GET",header:{"content-type":"application/json"},success:function(c){c&&c.data&&c.data.route&&a.success({paths:c.data.route.paths})},fail:function(c){a.fail({errCode:"0",errMsg:c.errMsg||""})}})};
-AMapWX.prototype.getTransitRoute=function(a){var b=Object.assign({},this.requestConfig);a.origin&&(b.origin=a.origin);a.destination&&(b.destination=a.destination);a.strategy&&(b.strategy=a.strategy);a.city&&(b.city=a.city);a.cityd&&(b.cityd=a.cityd);wx.request({url:"https://restapi.amap.com/v3/direction/transit/integrated",data:b,method:"GET",header:{"content-type":"application/json"},success:function(c){c&&c.data&&c.data.route&&(c=c.data.route,a.success({distance:c.distance||"",taxi_cost:c.taxi_cost||
-"",transits:c.transits}))},fail:function(c){a.fail({errCode:"0",errMsg:c.errMsg||""})}})};
-AMapWX.prototype.getRidingRoute=function(a){var b=Object.assign({},this.requestConfig);a.origin&&(b.origin=a.origin);a.destination&&(b.destination=a.destination);wx.request({url:"https://restapi.amap.com/v3/direction/riding",data:b,method:"GET",header:{"content-type":"application/json"},success:function(c){c&&c.data&&c.data.route&&a.success({paths:c.data.route.paths})},fail:function(c){a.fail({errCode:"0",errMsg:c.errMsg||""})}})};module.exports.AMapWX=AMapWX;

+ 35 - 0
utils/auth.js

@@ -0,0 +1,35 @@
+import { login } from '../api/user'
+import { FETCH_AND_FORMAT_USER_INFO } from './util'
+// 检查是否登录
+export function isLoggedIn() {
+  const token = wx.getStorageSync('token')
+  const expires = wx.getStorageSync('expires_in')
+  return token && expires && expires > Date.now()
+}
+
+// 调用登录
+export async function doLogin({ code, phone, nickname, avatar }) {
+  wx.showLoading({
+    title: '登录中...',
+    mask: true
+  });
+  try {
+    const res = await login({
+      code,
+      phone,
+      nickname,
+      avatar
+    })
+    wx.setStorageSync('token', res.data.token_type + ' ' + res.data.access_token)
+    wx.setStorageSync('expires_in', Date.now() + ((res.data.expires_in - 10) * 1000))
+    FETCH_AND_FORMAT_USER_INFO()
+  } catch (error) {
+    wx.showToast({
+      title: '登录失败',
+      icon: 'none',
+      duration: 2000
+    });
+  } finally{
+    wx.hideLoading();
+  }
+}

+ 1 - 0
utils/request.js

@@ -29,6 +29,7 @@ function request({ loading = true, url, method = 'GET', data = {}, header = {} }
             duration: 2000
           });
           wx.removeStorageSync('token');
+          wx.removeStorageSync('expires_in');
           setTimeout(() => {
             wx.reLaunch({
               url: '/pages/index/index'

+ 7 - 2
utils/util.js

@@ -17,10 +17,15 @@ export const MAKE_PHONE_CALL = (phoneNumber) => {
 // 获取用户信息
 export async function FETCH_AND_FORMAT_USER_INFO() {
   const userRes = await getUserInfo()
-  const data = userRes.data || {}
+  const data = userRes.data || {};
+  getApp().globalData.userInfo = {
+    ...data,
+    avatar: data.avatar || '/static/image/cat.jpeg',
+    nickname: data.nickname || data.username.substring(0,6)
+  }
   return {
     ...data,
-    avatar: data.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg',
+    avatar: data.avatar || '/static/image/cat.jpeg',
     nickname: data.nickname || data.username.substring(0,6)
   }
 }