微信小程序商城开发记录三之项目全局模块代码清单

全局入口app.js

App全局入口文件为app.js,主要用于注册一个小程序以及微信登录等。

//app.js
App({
  d: {
    //填写自己主机URL
    hostUrl: '',
    appID: "",
    appKey: "",
    //填写自己的测试URL
    ceshiUrl: '',
  },

  //小程序初始化完成时触发,全局只触发一次
  onLaunch: function () {
    // 展示本地存储能力,从本地缓存获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    //login
    this.getUserInfo();
  },
  //获取用户信息
  getUserInfo: function (cb) {
    var that = this;
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      // 登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          // console.log(res)
          var code = res.code;

          //get wx user simple info
          wx.getUserInfo({
            //是否带上登录状态,这时可以获得encryptedData,iv等敏感信息,这些敏感信息需要session_key来解密
            withCredentials: true,
            //如果已经授权过那么会执行这里的代码,console.log("已授权标记");
            success: res => {
              that.globalData.userInfo = res.userInfo;
              typeof cb == "function" && cb(that.globalData.userInfo);
              that.getUserSessionKey(code);
            },

            fail: function () {
              //获取用户信息失败后,请跳转授权页面
              wx.showModal({
                title: '警告',
                content: '尚未进行授权,请点击确定跳转到授权页面进行授权',
                success: res => {
                  if (res.confirm) {
                    console.log('用户点击确定'),
                      wx.navigateTo({
                        url: '../tologin/tologin',
                      })
                  }
                }

              })
            }
          });
        }
      });
    }
  },
  //开发者服务器使用登录校验凭证appID、appKey、code获取微信接口服务返回的sessionkey和openid
  getUserSessionKey: code => {
    var that = this;
    wx.request({
      url: '',
      method: 'POST',
      data: {
        code: code
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        var data = res.data;
        if (data.status == 0) {
          wx.showToast({
            title: data.err,
            duration: 2000
          });
          return false;
        }
        that.globalData.userInfo['sessionId'] = data.session_key;
        that.globalData.userInfo['openid'] = data.openid;
        that.onLoginUser();
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常!err:getsessionkeys',
          duration: 2000
        });
      },

    });
  },

  //授权登录,与session_key、openID相关联
  onLoginUser: function () {
    var that = this;
    var user = that.globalData.userInfo;
    wx.request({
      url: '',
      method: 'POST',
      data: {
        SessionId: user.sessionId,
        gender: user.gender, //性别
        NickName: user.nickName,
        HeadUrl: user.avatarUrl,
        openid: user.openid
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        //初始化数据
        var data = res.data.arr;
        var status = res.data.status;
        if (status != 1) {
          wx.showToast({
            title: 'res.data.err',
            duration: 3000
          });
          return false;
        }
        that.globalData.userInfo['id'] = data.ID;
        that.globalData.userInfo['NickName'] = data.NickName;
        that.globalData.userInfo['HeadUrl'] = data.HeadUrl;
        var userId = data.ID;
        if (!userId) {
          wx.showToast({
            title: '登录失败!',
            duration: 3000
          });
          return false;
        }
        that.d.userId = userId;
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常!err:authlogin',
          duration: 2000
        });
      },
    });
  },

  globalData: {
    userInfo: null
  },

  onPullDownRefresh: function () {
    wx.stopPullDownRefresh({
      success: (res) => {},
    })
  }
})

微信登录过程

每个用户相对于每个微信应用(公众号或者小程序)的openId 是唯一的,也就是说一个用户相对于不同的微信应用会存在不同的openId
在这里插入图片描述

wx.getUserInfo

在这里插入图片描述
在这里插入图片描述
session_key 的作用之一是将小程序前端从微信服务器获取到的encryptedData 解密出来,获取到openId 和unionId 等信息。但是在1.2 登录过程中我们可以看到开发者服务器是能够直接拿到用户的openId 信息的,而且unionId 也是有其他获取途径的
在这里插入图片描述

在应用中如何保存用户登录态

保存用户登录态,一直以来都有两种解决方案:前端保存和后端保存

  • 后端保存:写session 的时候可以直接设定过期时间,定期通知小程序前端重新进行登录(wx.login)
  • 前端保存:因为session_key 存在时效性问题(毕竟是用来查看敏感信息),而小程序前端可以通过wx.checkSession() 来检查session_key 是否过期。所以可以通过这个来作为保存用户登录态的机制,这也是小程序文档中推荐的方法:

在这里插入图片描述

全局配置app.json

主要用于小程序页面路由配置和窗体参数设置

{
  "pages": [
    "pages/index/index",
    "pages/tologin/tologin",
    "pages/product/detail",
    "pages/search/search",
    "pages/user/user",
    "pages/user/dingdan",
    "pages/user/daifahuo",
    "pages/user/daishouhuo",
    "pages/user/success",
    "pages/user/shouhuo",
    "pages/user/tuihuo",
    "pages/user/feedback",
    "pages/order/pay",
    "pages/order/detail",
    "pages/cart/cart",
    "pages/listdetail/listdetail",
    "pages/address/address",
    "pages/address/user-address/user-address",
    "pages/category/index",
    "pages/ritual/ritual",
    "pages/synopsis/synopsis",
    "pages/myritual/myritual"
  ],
  "window": {
    "backgroundTextStyle": "dark",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "知识贩卖机",
    "navigationBarTextStyle": "black",
    "enablePullDownRefresh": true
  },
  "tabBar": {
    "backgroundColor": "#fafafa",
    "borderStyle": "white",
    "selectedColor": "#b4282d",
    "color": "#666",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "static/images/ic_menu_choice_nor.png",
        "selectedIconPath": "static/images/ic_menu_choice_pressed.png"
      },
      {
        "pagePath": "pages/category/index",
        "text": "分类",
        "iconPath": "static/images/ic_menu_sort_nor.png",
        "selectedIconPath": "static/images/ic_menu_sort_pressed.png"
      },
      {
        "pagePath": "pages/cart/cart",
        "text": "购物车",
        "iconPath": "static/images/ic_menu_shopping_nor.png",
        "selectedIconPath": "static/images/ic_menu_shopping_pressed.png"
      },
      {
        "pagePath": "pages/user/user",
        "text": "我的",
        "iconPath": "static/images/ic_menu_me_nor.png",
        "selectedIconPath": "static/images/ic_menu_me_pressed.png"
      }
    ]
  },
  "networkTimeout": {
    "request": 10000,
    "downloadFile": 10000
  },
  "debug": true,
  "sitemapLocation": "sitemap43.json"
}

全局样式app.wxss

主要用于设置全局样式

/**app.wxss**/
.container {
  box-sizing: border-box;
  background-color: #f4f4f4;
  font-family: PingFangSC-Light, helvetica, 'Heiti SC';
}

view,image,text,navigator {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

view,text {
  font-family: PingFangSC-Light, helvetica, 'Heiti SC';
  font-size: 29rpx;
  color: #333;
}

.df {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}

.df_1 {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  -webkit-tap-highlight-color: transparent;
}

.df_2 {
  -webkit-box-flex: 2;
  -webkit-flex: 2;
  -ms-flex: 2;
  flex: 2;
  -webkit-tap-highlight-color: transparent;
}

浏览器前缀

  • -moz代表firefox浏览器私有属性;

  • -ms代表IE浏览器私有属性;

  • webkit代表chrome、safari私有属性;

  • -o代表Opera私有属性。

项目配置project.config.json

主要用于对小程序开发者进行个性化配置

{
  "description": "项目配置文件",
  "packOptions": {
    "ignore": []
  },
  "setting": {
    "urlCheck": true,
    "es6": true,
    "enhance": false,
    "postcss": true,
    "preloadBackgroundData": false,
    "minified": true,
    "newFeature": true,
    "coverView": true,
    "nodeModules": false,
    "autoAudits": false,
    "showShadowRootInWxmlPanel": true,
    "scopeDataCheck": false,
    "uglifyFileName": false,
    "checkInvalidKey": true,
    "checkSiteMap": true,
    "uploadWithSourceMap": true,
    "compileHotReLoad": false,
    "useMultiFrameRuntime": false,
    "useApiHook": true,
    "babelSetting": {
      "ignore": [],
      "disablePlugins": [],
      "outputPath": ""
    },
    "useIsolateContext": true,
    "useCompilerModule": false,
    "userConfirmedUseCompilerModuleSwitch": false,
    "packNpmManually": false,
    "packNpmRelationList": [],
    "minifyWXSS": true
  },
  "compileType": "miniprogram",
  "libVersion": "2.13.2",
  "appid": "wx16b0543676196080",
  "projectname": "mall",
  "debugOptions": {
    "hidedInDevtools": []
  },
  "scripts": {},
  "isGameTourist": false,
  "simulatorType": "wechat",
  "simulatorPluginLibVersion": {},
  "condition": {
    "search": {
      "list": []
    },
    "conversation": {
      "list": []
    },
    "game": {
      "list": []
    },
    "plugin": {
      "list": []
    },
    "gamePlugin": {
      "list": []
    },
    "miniprogram": {
      "list": []
    }
  }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
微信商城小程序开发代码可以使用小程序源码来构建。小程序源码通常使用PHP和Java编程语言编写,并可以包含在HTML页面中。您可以在IDE中创建或导入小程序源文件来开始开发。如果您已经有一个小程序,可以将其导入IDE进行进一步的开发。另外,您还可以使用Vant组件库来增强小程序的功能和用户体验。Vant是一个轻量、可靠的移动端组件库,提供了Vue 2版本、Vue 3版本和微信小程序版本。您可以安装Vant并在小程序中使用它的组件。在开发过程中,需要注意的是,如果使用开发者工具创建的项目,需要手动配置project.config.json文件,以便正确索引到npm依赖的位置。具体的配置可以参考开发者工具的文档。 #### 引用[.reference_title] - *1* [最全微信小程序源码项目开发代码合集](https://blog.csdn.net/apltccode/article/details/127548630)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [微信小程序开发(超详细保姆式教程)](https://blog.csdn.net/m0_64875238/article/details/127796691)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值