微信小程序之小试牛刀

目录

1、介绍

1.1、个人用户信息

1.2、小程序的界面控件使用

1.3、内部使用的功能

1.4、总结

2、app

2.1、app.json

 2.2、app.js

3、UserLogin

3.1、UserLogin.wxml

3.2、UserLogin.js

4、InstallAgreement

4.1、InstallAgreement.wxml

4.2、InstallAgreement.js

5、Signature

5.1、Signature.wxml

5.2、Signature.wxss

5.3、 Signature.js

6、主界面 index

6.1、index.wxml

6.2、index.js

7、getCurrentUserInfo

8、getPhoneNumber

9、GetOrderData

10、UploadData

下载链接:小程序测试


1、介绍

1.1、个人用户信息

如图所示,

  1. 获取当前用户信息,
  2. 手机号,
  3. 此用户提交到云数据库的内容的删除和查看,以openid为唯一标识索引
  4. 默认状态为未登录,授权登录以后保存登录信息
  5. 在登陆时获取的openid其实调用云函数就可以读取到,但是还是用传统方式尝试做了一下

1.2、小程序的界面控件使用

主要有

  1. 常见的label、button、
  2. 所在地区使用省市区的picker,
  3. 费用使用的是普通的picker
  4. 学生姓名的添加删除使用动态渲染wx:for
  5. 签字使用canvas,同时界面切换
  6. 阅读并同意使用navigator跳转到安全事项的页面

1.3、内部使用的功能

  1. 云开发自带的数据库添加/删除/更新/查看
  2. 云开发的存储功能
  3. 界面滑动条的使用
  4. 单次和周期定时器的使用
  5. 调用云函数时同步等待

1.4、总结

        自我感觉是把小程序普通的功能都使用了,剩下的就是特殊的需要的时候使用和熟能生巧,可是自己学了一轮感觉使用的机会都没有啊,可恶

  1. 框架中框架、wxml、wxss都有所熟悉
  2. 组件中的image、canvas、tabbar、view、scroll-view、button、checkbox、input、label、picker
  3. 界面之间的切换、交互、本地数据存储、本地文件存储、图片、云开发、服务端的api

2、app

        文件框架如图所示

2.1、app.json

        主要功能:添加了tabBar

{
    "pages": [
        "pages/index/index",
        "pages/UserLogin/UserLogin",
        "pages/InstallAgreement/InstallAgreement",
        "pages/Signature/Signature"
    ],
    "window": {
        "backgroundTextStyle": "light",
        "navigationBarBackgroundColor": "#fff",
        "navigationBarTitleText": "Weixin",
        "navigationBarTextStyle": "black"
    },
    "style": "v2",
    "sitemapLocation": "sitemap.json",
    //此处开始添加
    "tabBar": {
      "color": "#999",
          "selectedColor": "#3D98FF",
          "backgroundColor": "#fff",
          "borderStyle": "white",
      "list": [
        {
          "pagePath": "pages/index/index",
          "iconPath": "image/icon_component.png",
          "selectedIconPath": "image/icon_component_HL.png",
          "text": "注册"
        },
        {
          "pagePath": "pages/UserLogin/UserLogin",
          "iconPath": "image/icon_API.png",
          "selectedIconPath": "image/icon_API_HL.png",
          "text": "我的"
        }
      ]
    }
    
}

 2.2、app.js

        主要功能:添加了全局变量以及启动时读取

// app.js
App({
  globalData:{//全局变量
    phone: '',
    userInfo: {},
    userOpenid: '',
    hasUserInfo: false,
    hasPhoneNumber: false
  },
  onLaunch(){
    wx.cloud.init({
      env: '此处应当指定自己的云环境变量'
    })
    //全局变量的初始化
    const userinfo =  wx.getStorageSync('userinfo') || {}
    const phoneNumber =  wx.getStorageSync('phone') || ''
    const openid =  wx.getStorageSync('openid') || ''
    this.globalData.userInfo = userinfo;
    this.globalData.userOpenid = openid;
    this.globalData.phone = phoneNumber;
    this.globalData.hasUserInfo = Object.keys(userinfo).length == 0?false:true;
    this.globalData.hasPhoneNumber = phoneNumber==''?false:true;
  },
})

3、UserLogin

3.1、UserLogin.wxml

        主要功能:如果已登录显示用户信息和提交记录和删除记录,否则显示登录按钮

<view class="container">
  <view class="userinfo">
    <!-- 授权前 -->
    <block wx:if="{{!hasUserInfo}}">
      <button type="primary" bindtap="getUserProfile" > 快速登录 </button>
    </block>
    <!-- 授权后 -->
    <block wx:else>
     <view class="users">
      <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
      <block wx:if="{{!hasPhoneNumber}}">
        <button type="primary" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">绑定手机号</button>
      </block>
      <block wx:else>
        <text class="userinfo-phone">手机号: {{phone}}</text>
      </block>
      
      <view class="weui-btn-area">
          <button id="Buttom"  class="weui-btn" type="primary"bindtap='ClickSubmitHistory' >提交记录</button>
          <button id="Buttom"  class="weui-btn" type="primary"bindtap='ClickRemove' >删除记录</button>
      </view>
     </view>
    </block>
  </view>
</view>

3.2、UserLogin.js

var global = getApp().globalData;
Page({
  data: {
    phone: '',
    userInfo: {},
    userOpenid: '',
    hasUserInfo: false,
    hasPhoneNumber: false
  },
  onLoad(options) {
    this.setData({
      userInfo: global.userInfo,
      userOpenid: global.userOpenid,
      phone: global.phone,
      hasPhoneNumber: global.hasPhoneNumber,
      hasUserInfo: global.hasUserInfo
    })
  },
  ClickSubmitHistory(res){
    wx.cloud.callFunction({
      name: 'GetOrderData',
      data: {
        Type: 'Get',
        userOpenid: global.userOpenid,
      }
    }).then(res =>{
      console.log("获取成功: ",res)
    }).catch(res => {
      console.log("获取失败: ",res)
    })
  },
  ClickRemove(res){
    wx.cloud.callFunction({
      name: 'UploadData',
      data: {
        Type: 'Remove',
        userOpenid: global.userOpenid,
      }
    }).then(res =>{
      console.log("删除成功: ",res)
    }).catch(res => {
      console.log("删除失败: ",res)
    })
  },
  async getPhoneNumber(res) {
    const errMsg = res.detail.errMsg
    if (errMsg != "getPhoneNumber:ok"){
      wx.showToast({
        title: '授权失败',
        icon: 'error'
      })
      return
    }
    const cloudId = res.detail.cloudID
    const cloudIdList = [cloudId]
    wx.showLoading({
      title: '获取中',
      mask: true
    })
    const cloudFunRes = await wx.cloud.callFunction({
      name: "getPhoneNumber",
      data: {
        cloudIdList:cloudIdList,
        openid: this.data.userOpenid
      }
    })
    console.log("cloudIdList: ",cloudIdList)
    console.log("cloudFunRes: ",cloudFunRes)
    const jsonStr = cloudFunRes.result.dataList[0].json
    const jsonData = JSON.parse(jsonStr)
    const phoneNumber = jsonData.data.phoneNumber
    console.log(phoneNumber)
    this.setData({
      hasPhoneNumber: phoneNumber==''?false:true,
      phone: phoneNumber
    })
    this.globalData.phone = this.data.phone;
    this.globalData.hasPhoneNumber = this.data.hasPhoneNumber;
    wx.setStorageSync('phone', phoneNumber)
    wx.hideLoading({
      success: (res) => {},
    })
  },
  async getUserProfile(e) {
    var than = this
    wx.getUserProfile({
      desc: '用于获取用户个人信息',
      success: function (detail) {
        wx.login({
          success: res => {
            var code = res.code; //登录凭证
            wx.cloud.callFunction({
              name: "getCurrentUserInfo",
              data: {
                encryptedData: detail.encryptedData,
                iv: detail.iv,
                code: code,
                userInfo: detail.rawData
              }
            }).then(res => {
              console.log("res: ",res);
              var openid = res.result.openid;
              var status = res.result.status;
              var phoneNumber = res.result.phone;
              console.log("openid: ",openid);
              console.log("status: ",status);
              console.log("phone: ",phoneNumber);
              console.log("nickName: ",detail.userInfo.nickName);
              wx.setStorageSync('userinfo', detail.userInfo)
              wx.setStorageSync('openid', openid)
              if(phoneNumber==undefined){
                wx.setStorageSync('phone', "")
              }else{
                wx.setStorageSync('phone', phoneNumber)
              }
              than.setData({
                userOpenid: openid,
                userInfo: detail.userInfo,
                hasUserInfo: true,
                hasPhoneNumber: phoneNumber==undefined?false:true,
                phone: phoneNumber==undefined?'':phoneNumber
              })
              this.globalData.userOpenid = this.data.userOpenid;
              this.globalData.userInfo = this.data.userInfo;
              this.globalData.hasUserInfo = this.data.hasUserInfo;
              this.globalData.hasPhoneNumber = this.data.hasPhoneNumber;
              this.globalData.phone = this.data.phone;
            }).catch(res => {
              console.log("111res3: ",res);
            })
          }
        });
      },
      fail: function () {
       wx.showModal({
         content: '取消授权将会影响相关服务,您确定取消授权吗?',
         success (res) {
           if (res.confirm) {
             wx.showToast({
               title: '已取消授权',
               duration: 1500
             })
           } else if (res.cancel) {
             this.getUserProfile()
           }
         }
       })
      }
    })
  }
})

4、InstallAgreement

        主要功能:显示安全要求须知,没有任何行为,只有返回之前界面

4.1、InstallAgreement.wxml


<view catchtouchmove="catchtouchmove" class="tips" >
      <view class="tips_box">
          <view class="hint_view">
              <view class="text">
                  <view class="hint1">出游须知</view>
                  <view class="hint2"><text>注意安全</text></view>
                  <view class="hint2"><text>危险时电话: 110</text></view>
                  <view class="hint2"><text>火灾时电话: 119</text></view>
                  <view class="hint2"><text>受伤时电话: 120</text></view>
              </view>
          </view>
          <button bindtap='tipAgree' class="login" type='primary' formType="submit" >关闭</button>
      </view>
  </view>

4.2、InstallAgreement.js

Page({
  onLoad(options) {
  },
  tipAgree: function() { //重新画
    wx.navigateBack()
  },
})

5、Signature

        主要功能:签名,返回临时文件图片的src

5.1、Signature.wxml

<view class="sign">
  <view class="paper">
    <canvas class="handWriting" disable-scroll="true" bindtouchstart="touchstart1" bindtouchmove="touchmove1"  canvas-id="handWriting1">
    </canvas>
  </view>
  <view class="signBtn">
    <button size="" type="primary" bindtap="sign1ok">完成签字</button> 
    <button size="" type="warn" bindtap="reSign1">重新签字</button>
  </view>
</view>

5.2、Signature.wxss

.paper{border:1px solid #dedede; margin: 10px; height:200px }
.image{border:1px solid #dedede; margin: 10px; height:200px }
.signBtn{display: flex; margin-top:20px;}
.signTitle{ text-align: center; font-size:1.2em;margin:10px auto;}
.handWriting{width:100%; height:200px }
.image image{width:100%; height:200px }

5.3、 Signature.js

Page({
  data: {
    context1: null,
    hasDraw:false, //默认没有画
    src:null
  },
  onLoad: function() {
    console.log("Signature/onLoad")
    var context1 = wx.createCanvasContext('handWriting1');
    context1.setStrokeStyle("#000000")
    context1.setLineWidth(3);
    this.setData({
      src:null,
      context1: context1,
    })
  },
  touchstart1: function(e) {
    var context1 = this.data.context1;
    context1.moveTo(e.touches[0].x, e.touches[0].y);
    this.setData({
      context1: context1,
      hasDraw : true, //要签字了
    });
  },
  touchmove1: function(e) {
    var x = e.touches[0].x;
    var y = e.touches[0].y;
    var context1 = this.data.context1;
    context1.setLineWidth(3);
    context1.lineTo(x, y);
    context1.stroke();
    context1.setLineCap('round');
    context1.draw(true);
    context1.moveTo(x, y);
  },
  reSign1: function() { //重新画
    var that = this;
    var context1 = that.data.context1;
    context1.draw(); //清空画布
    that.setData({
      hasDraw: false, //没有画
      src: null
    });
  },
  sign1ok: function () {
    var that = this;
    if(!that.data.hasDraw){
      console.log("签字是空白的 没有签字")
    }else{
      var context1 = that.data.context1;
      context1.draw(true, wx.canvasToTempFilePath({
        canvasId: 'handWriting1',
        success(res) {
          console.log(res.tempFilePath) //得到了图片下面自己写上传吧
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2];
          prevPage.setData({
            imageSource: res.tempFilePath
          })
          wx.navigateBack()
        }
      }))
    }
  },
});

6、主界面 index

6.1、index.wxml

<!--index.wxml-->

<view id="Top" class="page-body">
  <view class="page-section">
    <view class="weui-cells__title">带队老师</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" bindinput='SlotInput' data-cmd="Teacher" value="{{Teacher}}" auto-focus />
      </view>
    </view>
    
    <view class="weui-cells__title">联系人电话</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" bindinput='SlotInput' data-cmd="Phone" value="{{Phone}}" />
      </view>
    </view>
    
    <view class="weui-cells__title">班级</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" bindinput='SlotInput' data-cmd="Class" value="{{Class}}" />
      </view>
    </view>
    
    <view class="weui-cells__title">所在地区</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="section">
        <picker mode="region" bindchange="bindRegionChange" value="{{region}}" custom-item="{{customItem}}">
          <view class="picker">
            {{region[0]}} {{region[1]}} {{region[2]}}
          </view>
        </picker>
      </view>
    </view>
    
    <view class="weui-cells__title">具体地址</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell weui-cell_input">
        <input class="weui-input" bindinput='SlotInput' data-cmd="Addr" value="{{Addr}}" />
      </view>
    </view>
    
    <view class="weui-cells__title">费用</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="section">
        <picker bindchange="bindPickerChange" value="{{ChargeModeIndex}}" range="{{ChargeModeList}}">
          <view class="picker">{{ChargeModeList[ChargeModeIndex]}} </view>
        </picker>
      </view>
    </view>

    <block   wx:for="{{StudentNameList}}" wx:key="key">
      <view class="weui-cells__title">学生姓名{{index+1}}</view>
      <view class="weui-cells weui-cells_after-title">
        <view class="weui-cell weui-cell_input">
          <input class="weui-input" bindinput='SlotInput' data-id="{{index}}" data-cmd="Student" value="{{StudentNameList[index]}}" />
        </view>
      </view>
    </block > 
    <button class='AddStudent' bindtap='AddStudent'>添加</button>
    <button class='DelStudent' bindtap='DelStudent'>删除</button>

      <view class="weui-cell weui-cell_input"  hidden="{{imageSource?true:false}}">
        <input  class="weui-input" style="width:100%;height:200px"   	bindfocus='ClickImage'  placeholder="请在此处点击签字"  />
      </view>
      <view class="image" hidden="{{imageSource?false:true}}">
        <image src="{{imageSource}}"  style="width:100%;height:200px"></image>
      </view>
  </view>
  <!--相关协议-->
 <checkbox-group bindchange="bindAgreeChange">
      <label class="weui-agree" for="weuiAgree">
           <view class="weui-agree__text">
              <checkbox class="weui-agree__checkbox" id="weuiAgree" value="agree" checked="{{}}" />
                <view  class="weui-agree__checkbox-icon">
                     <icon class="weui-agree__checkbox-icon-check" type="success_no_circle" size="9" wx:if="{{isAgree}}"></icon>
                    </view>
                    阅读并同意<navigator url="/pages/InstallAgreement/InstallAgreement" class="weui-agree__link">《安全事项》</navigator>
              </view>
          </label>
   </checkbox-group>
<!--提交按钮-->
<view class="weui-btn-area">
    <button id="Buttom"  class="weui-btn" type="primary"bindtap='ClickSubmit'disabled='{{btn_disabled}}'>确定提交</button>
</view>
</view>

6.2、index.js

var global = getApp().globalData;
Page({
  data: {
    SendTimeOutCount: 0,
    SendTimeOutTimerID: 0,
    scrollPos: 0,
    isAgree: 0,
    btn_disabled: true,
    cmd: '',
    Teacher: 'baidu',
    Phone: '12345678910',
    Class: '初三一班',
    region: ['北京市', '北京市', '海淀区'],
    Addr: '西北旺东路10号院百度科技园1号楼',
    ChargeModeIndex: 1,
    ChargeModeList: ['','自费', '免费'],
    StudentNameList:  ['小明','小红','小黄'],
    imageSource: null,
    UploadDataResult: false
  },
  CurrentPageScrollTo(in_data){
    var timer = setTimeout(()=>{ 
      wx.pageScrollTo({ 
          selector: in_data
      });
      clearTimeout(timer);
    },500)
  },
  onPageScroll:function(e){ // 获取滚动条当前位置
    this.data.scrollPos = e.scrollTop
  },
  onShow(){
    console.log("index/onShow ")
    if(this.data.scrollPos < 100){
      this.CurrentPageScrollTo('#Top')
    }else{
      this.CurrentPageScrollTo('#Buttom')
    }
  },
  onUnload(){
    if(this.data.SendTimeOutTimerID != 0){
      clearInterval(this.data.SendTimeOutTimerID)
    }
  },
  onLoad() {
    
  },
  bindPickerChange: function (e) {
    console.log('收费模式发送选择改变,携带值为', e.detail.value)
    this.setData({
      ChargeModeIndex: e.detail.value
    })
    this.data.Model = this.data.ChargeModeList[e.detail.value]
  },
  bindRegionChange: function (e) {
    console.log('所在地区发送选择改变,携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  SlotInput(res){
    console.log(res);
    var than = this;
    let InputCmd = res.currentTarget.dataset.cmd;
    let val = res.detail.value;
    switch(InputCmd){
      case 'Teacher':
        than.data.Teacher = val;
        break;
      case 'Phone':
        than.data.Phone = val;
        break;
      case 'Class':
        than.data.Class = val;
        break;
      case 'Addr':
        than.data.Addr = val;
        break;
      case 'Student':
        let ClickIndex = res.currentTarget.dataset.id;
        than.data.StudentNameList[ClickIndex] = val;
        break;
    }
  },
  AddStudent: function(){
    var  lists = this.data.StudentNameList;
    if(lists.length > 15){
      wx.showToast({
        title: '超出最大限制',//用户看到的提示信息
        icon: 'none',//提示图标,有error,success、none
        duration: 2000//停留时间
      })
      return
    }
    var newData = '';
    lists.push(newData);
    this.setData({
      StudentNameList: lists,
    })  
    console.log(this.data.StudentNameList)
  },
  DelStudent: function () {
    var lists = this.data.StudentNameList;
    lists.pop();
    this.setData({
      StudentNameList: lists,
    })
    console.log(this.data.StudentNameList)
  },
  ClickImage: function(){
    wx.navigateTo({
      url: '/pages/Signature/Signature',
    })
  },
  bindAgreeChange:function(e) {
     console.log(e.detail.value)
      this.setData({
        isAgree:e.detail.value.length,
      })
      if (e.detail.value.length==1){
       this.setData({
         btn_disabled:false,
       })
     }else{
        //onsole.log(e.detail.value.length)
       this.setData({
         btn_disabled:true
       })
     }
  },
  CheckData(){
    var ErrorString = ''
    if(this.data.Teacher.replace(/\s+/g, '')   == ''){
      ErrorString = '带队老师为空'
    }else if(this.data.Phone.replace(/\s+/g, '')   == ''){
      ErrorString = '联系人电话为空'
    }else if(this.data.Class.replace(/\s+/g, '')   == ''){
      ErrorString = '班级为空'
    }else if(this.data.region.join("") == ''){
      ErrorString = '所在地区为空'
    }else if(this.data.Addr.replace(/\s+/g, '')   == ''){
      ErrorString = '具体地址为空'
    }else if(this.data.ChargeModeList[this.data.ChargeModeIndex].replace(/\s+/g, '')   == ''){
      ErrorString = '费用模式为空'
    }else if(this.data.imageSource == null){
      ErrorString = '当前还未签字确认'
    }else{
      let StudentNameListLen = this.data.StudentNameList.length
      console.log("StudentNameListLen: " ,StudentNameListLen)
      if(StudentNameListLen == 0){
        ErrorString = '学生姓名存在为空'
        return ErrorString;
      }
      for(let i = 0;i < StudentNameListLen;i++){
        if(this.data.StudentNameList[i].replace(/\s+/g, '')   == ''){
          ErrorString = '学生姓名存在为空'
          return ErrorString;
        }
      }
      ErrorString = ''
    }
    return ErrorString
  },
  SendTimeOutTimerCheck(){
    // console.log("Time: " ,time.formatTime(new Date()));
    this.data.SendTimeOutCount++;
    if(this.data.SendTimeOutCount > 60){
      if(this.data.SendTimeOutTimerID != 0){
        clearInterval(this.data.SendTimeOutTimerID)
      }
      this.data.SendTimeOutCount = 0;
      wx.hideLoading({})
      wx.showToast({
        title: '获取超时',//用户看到的提示信息
        icon: 'none',//提示图标,有error,success、none
      })
    }else{
      if(this.data.UploadDataResult == true){
        if(this.data.SendTimeOutTimerID != 0){
          clearInterval(this.data.SendTimeOutTimerID)
        }
        this.data.SendTimeOutCount = 0;
        wx.hideLoading({})
        wx.showToast({
          title: '提交成功',//用户看到的提示信息
          icon: 'success',//提示图标,有error,success、none
        })
      }
    }
  },
  ClickSubmit:function(e){
    console.log(global.userOpenid)
    if(global.userOpenid == ''){
      wx.showToast({
        title: '当前还未登录',//用户看到的提示信息
        icon: 'error',//提示图标,有error,success、none
        duration: 2000//停留时间
      })
    }
    var ErrorString = this.CheckData()
    if(ErrorString != ''){
      wx.showToast({
        title: ErrorString,//用户看到的提示信息
        icon: 'none',//提示图标,有error,success、none
        duration: 2000//停留时间
      })
      return
    }
    this.UploadDataToCloudService()
    this.data.SendTimeOutTimerID = setInterval(this.SendTimeOutTimerCheck,1000)
    wx.showLoading({
      title: '请稍等',
    })
  },
  async UploadDataToCloudService(){
    let status = false;
    let result1 = await wx.cloud.callFunction({
      name: 'UploadData',
      data: {
        Type: 'Upload',
        Teacher: this.data.Teacher,
        Phone: this.data.Phone,
        Address: this.data.region.join("") + this.data.Addr,
        ChargeMode: this.data.ChargeModeList[this.data.ChargeModeIndex],
        StudentNameList: this.data.StudentNameList.join(","),
        userOpenid: global.userOpenid,
      }
    });
    var path = 'Signature/'
    path += this.data.StudentNameList.join("|")
    path += '.png'
    let result2 = await wx.cloud.uploadFile({
      cloudPath: path, // 上传至云端的路径
      filePath: this.data.imageSource, // 小程序临时文件路径
    })
    console.log('调用云函数结果,status:',status);
    console.log('调用云函数结果,result1:',result1);
    console.log('调用云函数结果,result2:',result2);
    if(result1.result.result == "Submit success!" && result2.statusCode == 204){
      this.data.UploadDataResult = true;
    }
  },
})

7、getCurrentUserInfo

        主要功能:获取openid,其实使用云开发没有必要、已经自带了

const request = require('request')
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
// 云函数入口函数
let user_id;
let user_uid;
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let code = event.code;//获取小程序传来的code
  let encryptedData = event.encryptedData;//获取小程序传来的encryptedData
  let iv = event.iv;//获取小程序传来的iv
  let userInfo = JSON.parse(event.userInfo) //获取个人信息
  let appid = "xxxxxxxxxxx";//自己小程序后台管理的appid,可登录小程序后台查看
  let secret = "xxxxxxxxxxx";//小程序后台管理的secret,可登录小程序后台查看
  let grant_type = "authorization_code";// 授权(必填)默认值
  let url = "https://api.weixin.qq.com/sns/jscode2session?grant_type="+grant_type+"&appid="+appid+"&secret="+secret+"&js_code="+code;
  const stat = await new Promise((resolve, reject) => {
    request(url, (err, response, body) => {
      if (!err && response.statusCode == 200) {
        let _data = JSON.parse(body)
        let UserCount = 0;
        user_id = _data.openid
        user_uid = _data.unionid
        db.collection('Account').where({
          user_id: _data.openid // 填入当前用户 openid
        }).count().then(res => {
          UserCount = res.total;
          if(UserCount == 0){/* 插入当前列表 */
            db.collection('Account').add({
              data: {
                user_id: _data.openid,
                nickName: userInfo.nickName,
                avatarUrl: userInfo.avatarUrl,
                gender: userInfo.gender,
                phone: ''
              }
            })
            .then(res => {
              resolve("Insert success!");
            })
            .catch(res => {
              reject("Insert fail!");
            })
          }else if(UserCount == 1){/* 更新当前列表 */
            db.collection('Account').where({
              user_id: _data.openid // 填入当前用户 openid
            }).update({
              data: {
                nickName: userInfo.nickName,
                avatarUrl: userInfo.avatarUrl,
                gender: userInfo.gender
              }
            })
            .then(res => {
              resolve("Update success!");
            }).catch(res => {
              reject("Update fail!");
            })
          }else if(UserCount > 1){/* 删除所有此id的并且重新添加 */
            db.collection('Account').where({
              user_id: _data.openid // 填入当前用户 openid
            }).remove()
            .then(res => {
              db.collection('Account').add({
                data: {
                  user_id: _data.openid,
                  nickName: userInfo.nickName,
                  avatarUrl: userInfo.avatarUrl,
                  gender: userInfo.gender,
                  phone: ''
                }
              })
              resolve("Remove and insert success!");
            }).catch(res => {
              reject("Remove fail!");
            })
          }
        })
      }
    })
  })
  const CurrentPhoneObject = await db.collection('Account').where({
    user_id: user_id // 填入当前用户 openid
  }).get()
  const CurrentPhone = CurrentPhoneObject.data[0].phone
  console.log("CurrentPhone: ",CurrentPhone);
  console.log("stat: ",stat);
  console.log("user_id: ",user_id);
  console.log("user_uid: ",user_uid);
  return {
    status: stat,
    CurrentPhone: CurrentPhone,
    openid: user_id,
    unionid: user_uid
  }
}

8、getPhoneNumber

        主要功能:获取手机号码

const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
// 云函数入口函数
exports.main = async (event) => {
  const wxContext = cloud.getWXContext()
  console.log("event: ",event)
  const openid = event.openid
  const cloudIdList = event.cloudIdList
  console.log("openid: ",openid)
  console.log("openid: ",wxContext.OPENID)
  console.log("cloudIdList: ",cloudIdList)
  try {
    const result = await cloud.openapi.cloudbase.getOpenData({
      openid: openid,
      cloudidList: cloudIdList
    })
    
    const jsonStr = result.dataList[0].json
    const jsonData = JSON.parse(jsonStr)
    const phoneNumber = jsonData.data.phoneNumber
    console.log("phoneNumber: ",phoneNumber)

    await db.collection('Account').where({
      user_id: openid // 填入当前用户 openid
    }).update({
      data: {
        phone: phoneNumber
      }
    })
    .then(res => {
      console.log("Update success!");
    }).catch(res => {
      console.log("Update fail!");
    })

    return result
  } catch (err) {
    return err
  }
}

9、GetOrderData

        主要功能:获取所有此用户的提交信息

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
const MAX_LIMIT = 100
const db = cloud.database()
exports.main = async (event, context) => {
  let OptionsType = event.Type;
  let userOpenid = event.userOpenid;
  const countResult = await db.collection('Orders').where({
    userOpenid: userOpenid // 填入当前用户 openid
  }).count()
  const total = countResult.total
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('Orders').where({
      userOpenid: userOpenid
    }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}

10、UploadData

        主要功能:删除和添加

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
exports.main = async (event, context) => {
  let OptionsType = event.Type;
  let userOpenid = event.userOpenid;
  let result;
  console.log('start...');
  
  if(OptionsType == 'Get'){
    const countResult = await db.collection('Orders').where({
      userOpenid: userOpenid // 填入当前用户 openid
    }).count()
    const total = countResult.total
  }
  console.log('break2...');
  result = await new Promise((resolve, reject) => {
    if(OptionsType == 'Upload'){
      db.collection('Orders').add({
        data:{
          Teacher: event.Teacher,
          Phone: event.Phone,
          Address: event.Address,
          ChargeMode: event.ChargeMode,
          StudentNameList: event.StudentNameList,
          userOpenid: event.userOpenid
        }
      })
      .then(res => {
        resolve("Submit success!");
      })
      .catch(res => {
        reject("Submit fail!");
      })
    }else if(OptionsType == 'Remove'){
      db.collection('Orders').where({
        userOpenid: userOpenid // 填入当前用户 openid
      }).remove()
      .then(res => {
        resolve("Remove success!");
      })
      .catch(res => {
        reject("Remove fail!");
      })
    }else if(OptionsType == 'Get'){
      // const countResult = db.collection('Orders').where({
      //   userOpenid: userOpenid // 填入当前用户 openid
      // }).count()
      // const total = countResult.total


      // console.log('total: ',total);
      // console.log('countResult: ',countResult);
      // const MAX_LIMIT = 100
      // const total = countResult.total
      // console.log('total: ',total);
      // // 计算需分几次取
      // const batchTimes = Math.ceil(total / 100)
      // // 承载所有读操作的 promise 的数组
      // const tasks = []
      // for (let i = 0; i < batchTimes; i++) {
      //   const promise = db.collection('todos').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
      //   tasks.push(promise)
      // }
      // // 等待所有
      // return (await Promise.all(tasks)).reduce((acc, cur) => {
      //   return {
      //     data: acc.data.concat(cur.data),
      //     errMsg: acc.errMsg,
      //   }
      // })
      resolve("Nothing");
    }
  })
  return {
    event,
    result: result
  } 
}

下载链接:小程序测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值