-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
116 lines (110 loc) · 2.68 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//app.js
import store from './store/index.js'
const {
request
} = require('./utils/request.js');
App({
/**
* 生命周期回调——监听小程序初始化。
*/
onLaunch: function () {
// 获取系统信息
wx.getSystemInfo({
success: (res) => {
const theme = res.theme;
store.setState({
theme
});
}
})
// 调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户的唯一标识(openid)及本次登录的会话密钥(session_key)等。
wx.login({
success: res => {
// 发送 res.code 到后台换取 openid, sessionKey, unionId
if (res.code) {
request(`/mini/api/v1/login?code=${res.code}`)
.then(response => {
const {
token,
openid
} = response.data;
// 存储用户 openid
store.setState({
openid,
});
try {
wx.setStorageSync('miniToken', token)
} catch (error) {
console.log('同步保存token失败,原因:', error);
}
})
.then(() => {
return request('/mini/api/v1/users')
})
.then(response => {
const {
nickname: nickName,
avatar: avatarUrl,
sex: gender,
country,
province,
city,
language
} = response.data;
store.setState({
user: {
nickName,
avatarUrl,
gender,
country,
province,
city,
language,
}
});
}).catch(err => {
console.log('登录失败,原因:' + err);
})
}
}
})
},
/**
* 监听系统主题变化
* @param {*} theme
*/
onThemeChange: function (theme) {
store.setState({
theme
});
},
/**
* 授权之后更新用户
*/
onUserUpdate: function (userInfo) {
const {
avatarUrl: avatar,
city,
country,
gender: sex,
language,
nickName: nickname,
province
} = userInfo;
request('/mini/api/v1/users', 'put', {
avatar,
city,
country,
sex,
language,
nickname,
province,
})
.then(() => {
console.log('用户登录更新成功。')
}).catch(err => {
console.log('用户登录更新失败:' + err);
})
},
store: store,
})