微信小程序开发

开发视频参考:

https://www.bilibili.com/video/BV1nE41117BQ?t=18&p=15

登录需要获取登录code 然后调用接口 去向后端获取openid 

 

登录取的code和openid需要放在app.js中
但是在login.js中页面加载函数取不到,需要在方法调用中取的

 

https://blog.csdn.net/weixin_41700702/article/details/109555589
https://cloud.tencent.com/developer/article/1605348
引入vant

 


上传图片需要为 本地预览地址为本地url url为单个不是数组

上线时候不校验合法域名 后台配置合法域名 然后开发工具进行查看并且刷新

 

// miniprogram/pages/login/login.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

const app = getApp()
var api = require('../../config/api.js');
var base64 = require('../../utils/base64.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    username: '',
    password: '',
    grant_type: 'password',
    clientType: '3',
    scope: 'all',
    refresh_token: '',
    Authorization: 'Basic ' + base64.encode('wechat-weApp:wechat-weApp'),
    avatarUrl: '../../images/user-unlogin.png',
    userInfo: {},
  },

  /**
   * WX_ACCOUNT_REGISTER_FAIL            (3001, "微信小程序申请授权失败!"),
   * WX_ACCOUNT_LOGIN_FAIL                (3002, "微信小程序登录失败!"),
   * WX_ACCOUNT_VERIFICATION_FAIL        (3003, "微信小程序核验授权失败!"),
   * WX_ACCOUNT_UPDATE_FAIL                (3004, "微信小程序账号更新失败!"),
   * WX_ACCOUNT_DISABLED                    (3005, "微信小程序账号被禁用,请联系管理员!"),
   * WX_ACCOUNT_BLACKLISTED                (3006, "微信小程序账号被列入黑名单,请联系管理员!"),
   * WX_ACCOUNT_EXISTED                    (3007, "微信小程序账号已存在,请登录!"),
   * WX_ACCOUNT_VERIFYING                (3008, "微信小程序账号在审核中,请耐心等待!"),
   * WX_ACCOUNT_REGISTRATION_REQUIRED    (3009, "微信小程序账号尚未注册,请注册!")
   */

  //获取用户信息 判断用户账号状态
  getOpenId: function () {
    // console.log("code: " + app.globalData.code);
    // console.log("openId: " + app.globalData.openId);
    var that = this
    wx.request({
      url: api.WE_APP_STATE,
      data: {
        jsCode: app.globalData.code,
        openId: app.globalData.openId,
      },
      method: "GET",
      header: {
        // "Content-Type": "application/x-www-form-urlencoded",
        "Content-Type": 'application/json'
      },
      success: function (result) {
        // console.log(result,'getOpenId')
        if (result.statusCode == 200) {
          // app.globalData.accountInfo = result.data
          // app.globalData.openId = result.data.result
          // app.globalData.code = null
          wx.hideLoading()

          if (3009 == result.data.code) {
            //微信小程序账号尚未注册
            wx.redirectTo({
              url: '/pages/register/register',
            })
          } else if (3008 == result.data.code) {
            //微信小程序账号在审核中
            wx.redirectTo({
              url: '/pages/verifying/verifying',
            })
          } else if (3007 == result.data.code) {
            //微信小程序账号已存在
            // console.log("登录走一波");
            that.login();
            // wx.redirectTo({
            //   url: '/pages/workOrder/create/create',
            // })
          } else {
            //异常情况
            Dialog.alert({
              title: '异常',
              message: result.data.message,
              theme: 'round-button',
            }).then(() => {
              // on close
            });
          }
        } else {
          console.log(`error1: ` + result)
          wx.hideLoading()
        }

      },
      fail: function (result) {
        console.log(`error2: $result`)
        wx.hideLoading()
      }
    })
  },

  //点击头像进行授权
  getUserInfo:function(e){
    let that = this;
    // 获取用户信息
    wx.getSetting({
      success(res) {
        // console.log("res", res)
        if (res.authSetting['scope.userInfo']) {
          console.log("已授权=====")
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              // console.log("获取用户信息成功", res)
              wx.showLoading({
                title: '正在加载',
              })
              that.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo 
              });
              that.getOpenId();
            },
            fail(res) {
              console.log("获取用户信息失败", res)
            }
          })
        } else {
          console.log("未授权=====")
          wx.showToast({title: '请授权', icon: 'none' })
        }
      }
    })
  },

  //小程序注册完成后进行登录 设置token
  login:function() {
    wx.showLoading({
      title: '登录中',
    })
    var that = this
    wx.request({
      url: api.TOKEN,
      data: {
        grant_type: this.data.grant_type,
        username: app.globalData.openId,
        password: app.globalData.openId,
        clientType: this.data.clientType,
        scope: this.data.scope,
        refresh_token: this.data.refresh_token
      },
      method: "POST",
      header: {
        // 'content-type': 'application/json', // 默认值
        "Content-Type": "application/x-www-form-urlencoded",
        'Authorization': this.data.Authorization,
      },
      success: function (result) {
        // console.log(result.statusCode)
        console.log(result,'login')
        app.globalData.vId = result.data.vIds[0]
        wx.hideLoading({
          success: (res) => {},
        })
        if (result.statusCode == 200) {
          app.globalData.accountInfo = result.data
          wx.reLaunch({
            url: '/pages/workOrder/create/create',
          })
        } else {
          Dialog.alert({
            title: '异常',
            message: result.data.message,
            theme: 'round-button',
          }).then(() => {
            // on close
          });
        }
      },
      fail: function (result) {
        console.log("fail")
        console.log(result)
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
登录js参考
//app.js

var api = require('./config/api.js');

App({
  onLaunch: function () {

    let that = this;
    //页面登录获取code
    wx.login({
      success (res) {
        // console.log("code=>>",res)
        that.globalData.code = res.code
        //利用code向后端换取openId 设为全局
        if (res.code) {
          wx.request({
            url: api.WE_APP_STATE,
            data: {
              jsCode: res.code
            },
            success: function (result) {
              // console.log(result)
              that.globalData.openId = result.data.result
            }
          })
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })


    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明:
        //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境(第一个创建的环境)
        // env: 'my-env-id',
        traceUser: true,
      })
    }
  },
  globalData: {
    code: null,
    userInfo: null,
    accountInfo: null,
    openId: null,
    tmpData: null,
    tmpEndData: null,
    vId:null
  }
})
app.js参考

 

posted @ 2021-07-29 09:58  阿蒙不萌  阅读(10)  评论(0编辑  收藏  举报