文章目录
全局入口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": []
}
}
}