WxApp/page/component/index.js

100 lines
2.8 KiB
JavaScript
Raw Normal View History

2024-08-30 15:23:27 +08:00
const app = getApp()
2024-08-29 14:36:16 +08:00
Page({
data: {
2024-08-30 15:23:27 +08:00
imgUrls: ["/image/b1.jpg", "/image/b2.jpg", "/image/b3.jpg"],
2024-08-29 14:36:16 +08:00
indicatorDots: false,
autoplay: false,
interval: 3000,
duration: 800,
2024-08-31 17:33:35 +08:00
goods: {},
2024-08-29 14:36:16 +08:00
},
onLoad() {
2024-08-30 15:23:27 +08:00
var self = this
2024-09-03 23:14:06 +08:00
self.checkUserProfile()
self.getUserProfile()// //获取openId
2024-08-29 14:36:16 +08:00
/**
* 发起请求获取商品列表信息
*/
wx.request({
// get请求
2024-08-30 15:23:27 +08:00
url: app.globalData.baseUrl + "/goods/loadData",
2024-08-29 14:36:16 +08:00
success(res) {
self.setData({
2024-08-30 15:23:27 +08:00
goods: res.data.data,
2024-08-29 14:36:16 +08:00
})
2024-08-30 15:23:27 +08:00
},
2024-08-29 14:36:16 +08:00
})
},
2024-09-03 23:14:06 +08:00
/**
* 检查本地缓存中是否有用户信息
*/
checkUserProfile() {
const userInfo = wx.getStorageSync('userInfo');
if (userInfo) {
// 如果有用户信息,直接设置数据
this.setData({
thumb: userInfo.avatarUrl,
nickname: userInfo.nickName,
});
} else {
//如果本地没有存储用户信息则通过openId查数据库中是否已经注册
wx.request({
url: app.globalData.baseUrl + "/user/getById",
method: "GET",
data: {
openId: wx.getStorageSync('openid'),
},
success(res) {
2024-09-04 23:56:21 +08:00
console.log("查到的用户信息" + res.data.data)
if (res.data.data != null) {
// 将用户信息存到 StorageSync
const userInfo = {
avatarUrl: res.data.data.avatarUrl,
nickName: res.data.data.username
};
wx.setStorageSync('userInfo', userInfo); // 存储到本地
} else {
wx.showModal({
title: '温馨提示',
content: '请先登录!',
showCancel: false,
success: (res) => {
if (res.confirm) {
console.log(res)
wx.navigateTo({
url: '/page/component/login/login',
});
}
2024-09-03 23:14:06 +08:00
}
2024-09-04 23:56:21 +08:00
})
}
2024-09-03 23:14:06 +08:00
}
})
}
},
//获取openId
getUserProfile() {
//通过wx.login()获取登录凭证code
wx.login({
success: (res) => {
const wxConfig = {
appid: "wx865aefa5a7115ae0",
2024-09-04 23:56:21 +08:00
secret: "df0817d59696a6160de2770222d8ec53",
2024-09-03 23:14:06 +08:00
code: res.code
}
2024-09-04 23:56:21 +08:00
console.log("code: " + res.code)
2024-09-03 23:14:06 +08:00
wx.request({
url: "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig.appid + "&secret=" + wxConfig.secret + "&code=" + wxConfig.code + "&js_code=" + wxConfig.code + '&grant_type=authorization_code',
success: (res) => {
2024-09-04 23:56:21 +08:00
console.log("openid:" + res.data.openId)
2024-09-03 23:14:06 +08:00
wx.setStorageSync('openid', res.data.openid);
},
fail: (err) => {
console.error('wx.login 失败', err);
}
})
},
})
},
2024-08-30 15:23:27 +08:00
})