@norcy/react-native-toolkit 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/lib/commonjs/AppleLoginUtil.js +2 -4
  2. package/lib/commonjs/AppleLoginUtil.js.map +1 -1
  3. package/lib/commonjs/HuaweiLoginUtil.js +10 -22
  4. package/lib/commonjs/HuaweiLoginUtil.js.map +1 -1
  5. package/lib/commonjs/LoginManager.js +96 -95
  6. package/lib/commonjs/LoginManager.js.map +1 -1
  7. package/lib/commonjs/WeChatLoginUtil.js +32 -56
  8. package/lib/commonjs/WeChatLoginUtil.js.map +1 -1
  9. package/lib/commonjs/constant.js.map +1 -1
  10. package/lib/module/AppleLoginUtil.js +2 -4
  11. package/lib/module/AppleLoginUtil.js.map +1 -1
  12. package/lib/module/HuaweiLoginUtil.js +10 -22
  13. package/lib/module/HuaweiLoginUtil.js.map +1 -1
  14. package/lib/module/LoginManager.js +96 -95
  15. package/lib/module/LoginManager.js.map +1 -1
  16. package/lib/module/WeChatLoginUtil.js +32 -56
  17. package/lib/module/WeChatLoginUtil.js.map +1 -1
  18. package/lib/module/constant.js.map +1 -1
  19. package/lib/typescript/AppleLoginUtil.d.ts +5 -1
  20. package/lib/typescript/AppleLoginUtil.d.ts.map +1 -1
  21. package/lib/typescript/HuaweiLoginUtil.d.ts +2 -7
  22. package/lib/typescript/HuaweiLoginUtil.d.ts.map +1 -1
  23. package/lib/typescript/LoginManager.d.ts +6 -6
  24. package/lib/typescript/LoginManager.d.ts.map +1 -1
  25. package/lib/typescript/WeChatLoginUtil.d.ts +3 -2
  26. package/lib/typescript/WeChatLoginUtil.d.ts.map +1 -1
  27. package/lib/typescript/constant.d.ts +6 -0
  28. package/lib/typescript/constant.d.ts.map +1 -1
  29. package/package.json +1 -1
  30. package/src/AppleLoginUtil.ts +6 -6
  31. package/src/HuaweiLoginUtil.ts +11 -24
  32. package/src/LoginManager.ts +76 -116
  33. package/src/WeChatLoginUtil.ts +54 -71
  34. package/src/constant.ts +7 -0
@@ -12,11 +12,14 @@ export const AppleLoginUtil = {
12
12
  // });
13
13
  // });
14
14
 
15
- fetchAndUpdateCredentialState: async (user: string, callback: Function) => {
15
+ fetchAndUpdateCredentialState: async (
16
+ user: string,
17
+ callback: (params: { result: LoginState; error?: string }) => void
18
+ ) => {
16
19
  console.log('User 正在登录鉴权:', user);
17
20
 
18
21
  if (user === null) {
19
- callback({ result: LoginState.NOTLOGIN }, { error: 'USER EMPTY' });
22
+ callback({ result: LoginState.NOTLOGIN, error: 'USER EMPTY' });
20
23
  } else {
21
24
  const credentialState = await appleAuth.getCredentialStateForUser(user);
22
25
  if (credentialState === appleAuth.State.AUTHORIZED) {
@@ -24,10 +27,7 @@ export const AppleLoginUtil = {
24
27
  callback({ result: LoginState.AUTHORIZED });
25
28
  } else {
26
29
  console.warn('登录鉴权失败');
27
- callback(
28
- { result: LoginState.NOTLOGIN },
29
- { error: 'Authorized Failed' }
30
- );
30
+ callback({ result: LoginState.NOTLOGIN, error: 'Authorized Failed' });
31
31
  }
32
32
  }
33
33
  },
@@ -1,4 +1,5 @@
1
1
  import { NativeModules, TurboModuleRegistry } from 'react-native';
2
+ import { ThirdPartyUserInfo } from './constant';
2
3
  import { PlatformHelper } from './PlatformHelper';
3
4
 
4
5
  const HuaweiLoginModule =
@@ -6,33 +7,19 @@ const HuaweiLoginModule =
6
7
  TurboModuleRegistry.get<any>('HuaweiLoginModule');
7
8
 
8
9
  export const HuaweiLoginUtil = {
9
- doLogin: async (
10
- callback: (result: {
11
- nickname?: string;
12
- headimgurl?: string;
13
- openid?: string;
14
- unionid?: string;
15
- error?: any;
16
- }) => void
17
- ) => {
10
+ doLogin: async (): Promise<ThirdPartyUserInfo> => {
18
11
  if (PlatformHelper.isIOS()) {
19
- callback({ error: 'Huawei Login is not supported on iOS' });
20
- return;
12
+ throw new Error('Huawei Login is not supported on iOS');
21
13
  }
22
14
  if (!HuaweiLoginModule || typeof HuaweiLoginModule.signIn !== 'function') {
23
- callback({ error: 'HuaweiLoginModule not available' });
24
- return;
25
- }
26
- try {
27
- const result = await HuaweiLoginModule.signIn();
28
- callback({
29
- nickname: result.nickname,
30
- headimgurl: result.headimgurl,
31
- openid: result.openid,
32
- unionid: result.unionid,
33
- });
34
- } catch (e) {
35
- callback({ error: e });
15
+ throw new Error('HuaweiLoginModule not available');
36
16
  }
17
+ const result = await HuaweiLoginModule.signIn();
18
+ return {
19
+ nickname: result.nickname,
20
+ headimgurl: result.headimgurl,
21
+ openid: result.openid,
22
+ unionid: result.unionid,
23
+ };
37
24
  },
38
25
  };
@@ -25,25 +25,19 @@ export type LoginFailResultType = {
25
25
  code?: string;
26
26
  };
27
27
 
28
- type LoginFinishParams = {
29
- isAuto?: boolean;
30
- user?: UserType;
31
- error?: string | object;
32
- code?: string;
33
- };
28
+ type LoginFinishParams =
29
+ | { isAuto?: boolean; user: UserType }
30
+ | { isAuto?: boolean; error: unknown; code?: string };
34
31
 
35
- const onLoginFinish = ({
36
- isAuto = false,
37
- user,
38
- error,
39
- code,
40
- }: LoginFinishParams) => {
41
- if (user) {
32
+ const onLoginFinish = (params: LoginFinishParams) => {
33
+ if ('user' in params) {
34
+ const { isAuto = false, user } = params;
42
35
  PrefData.setValue(BuildInPrefs.LastLoginType, user.type);
43
36
  const data = { isAuto, user };
44
37
  console.log('onLoginSuccess', data);
45
38
  Notification.postNotification('onLoginSuccess', data);
46
39
  } else {
40
+ const { isAuto = false, error, code } = params;
47
41
  const data = { isAuto, error, code };
48
42
  console.log('onLoginFail', data);
49
43
  Notification.postNotification('onLoginFail', data);
@@ -78,7 +72,7 @@ export const LoginManager = {
78
72
  login: async (
79
73
  type: LoginType,
80
74
  devAuthData: LoginAuthDataType | null = null,
81
- loadingCallback: Function,
75
+ loadingCallback: () => void,
82
76
  qrcodeCallback?: (qrcode: string) => void
83
77
  ) => {
84
78
  // 如果之前已经鉴权过,则直接使用上次鉴权的 AuthData
@@ -116,85 +110,51 @@ export const LoginManager = {
116
110
 
117
111
  AppleLoginUtil.fetchAndUpdateCredentialState(
118
112
  userData.userId,
119
- ({ result, error: error2 }: { result: number; error: any }) => {
120
- if (error || result !== LoginState.AUTHORIZED) {
121
- onLoginFinish({ error: error2 });
113
+ ({ result, error: credentialError }) => {
114
+ if (credentialError || result !== LoginState.AUTHORIZED) {
115
+ onLoginFinish({ error: credentialError });
122
116
  } else {
123
- loadingCallback && loadingCallback();
117
+ loadingCallback?.();
124
118
  doLogin(userData.authData, userData);
125
119
  }
126
120
  }
127
121
  );
128
122
  }
129
123
  } else if (type === LoginType.LoginTypeWeChat) {
130
- WeChatLoginUtil.doLogin(
131
- ToolkitConfig.WeiXinId,
132
- ToolkitConfig.WeiXinSecret,
133
- ({
124
+ try {
125
+ const { nickname, headimgurl, openid, unionid } =
126
+ await WeChatLoginUtil.doLogin(
127
+ ToolkitConfig.WeiXinId,
128
+ ToolkitConfig.WeiXinSecret
129
+ );
130
+ let userData = {
134
131
  nickname,
135
132
  headimgurl,
136
- openid,
137
- unionid,
138
- error,
139
- }: {
140
- nickname: string;
141
- headimgurl: string;
142
- openid: string;
143
- unionid: string;
144
- error: any;
145
- }) => {
146
- if (error) {
147
- onLoginFinish({ error });
148
- } else {
149
- let userData = {
150
- nickname: nickname,
151
- headimgurl: headimgurl,
152
- authData: {
153
- openid: openid,
154
- unionid: unionid,
155
- loginType: 'wechat',
156
- },
157
- };
158
- loadingCallback && loadingCallback();
159
- doLogin(userData.authData, userData);
160
- }
161
- }
162
- );
133
+ authData: { openid, unionid, loginType: 'wechat' as const },
134
+ };
135
+ loadingCallback?.();
136
+ doLogin(userData.authData, userData);
137
+ } catch (error) {
138
+ onLoginFinish({ error });
139
+ }
163
140
  } else if (type === LoginType.LoginTypeWeChatScan) {
164
- WeChatLoginUtil.doLoginByScan(
165
- ToolkitConfig.WeiXinId,
166
- ToolkitConfig.WeiXinSecret,
167
- qrcodeCallback!,
168
- ({
141
+ try {
142
+ const { nickname, headimgurl, openid, unionid } =
143
+ await WeChatLoginUtil.doLoginByScan(
144
+ ToolkitConfig.WeiXinId,
145
+ ToolkitConfig.WeiXinSecret,
146
+ qrcodeCallback!
147
+ );
148
+ let userData = {
169
149
  nickname,
170
150
  headimgurl,
171
- openid,
172
- unionid,
173
- error,
174
- }: {
175
- nickname: string;
176
- headimgurl: string;
177
- openid: string;
178
- unionid: string;
179
- error: any;
180
- }) => {
181
- if (error) {
182
- onLoginFinish({ error });
183
- } else {
184
- let userData = {
185
- nickname: nickname,
186
- headimgurl: headimgurl,
187
- authData: {
188
- openid: openid,
189
- unionid: unionid,
190
- loginType: 'wechat',
191
- },
192
- };
193
- loadingCallback && loadingCallback();
194
- doLogin(userData.authData, userData);
195
- }
196
- }
197
- );
151
+ authData: { openid, unionid, loginType: 'wechat' as const },
152
+ };
153
+ loadingCallback?.();
154
+ doLogin(userData.authData, userData);
155
+ } catch (error) {
156
+ onLoginFinish({ error });
157
+ }
198
158
  } else if (type === LoginType.LoginTypeVisitor) {
199
159
  const uniqueId = getUniqueIdSync();
200
160
  console.log(uniqueId);
@@ -205,37 +165,31 @@ export const LoginManager = {
205
165
  loginType: 'visitor',
206
166
  },
207
167
  };
208
- loadingCallback && loadingCallback();
168
+ loadingCallback?.();
209
169
  doLogin(userData.authData, userData);
210
170
  } else if (type === LoginType.LoginTypeHuawei) {
211
- HuaweiLoginUtil.doLogin(
212
- ({ nickname, headimgurl, openid, unionid, error }) => {
213
- if (error) {
214
- onLoginFinish({ error });
215
- } else {
216
- let userData = {
217
- nickname: nickname,
218
- headimgurl: headimgurl,
219
- authData: {
220
- openid: openid!,
221
- unionid: unionid,
222
- loginType: 'huawei',
223
- },
224
- };
225
- loadingCallback && loadingCallback();
226
- doLogin(userData.authData, userData);
227
- }
228
- }
229
- );
171
+ try {
172
+ const { nickname, headimgurl, openid, unionid } =
173
+ await HuaweiLoginUtil.doLogin();
174
+ let userData = {
175
+ nickname,
176
+ headimgurl,
177
+ authData: { openid, unionid, loginType: 'huawei' as const },
178
+ };
179
+ loadingCallback?.();
180
+ doLogin(userData.authData, userData);
181
+ } catch (error) {
182
+ onLoginFinish({ error });
183
+ }
230
184
  } else {
231
185
  onLoginFinish({ error: 'Unknown Login Type' });
232
186
  }
233
187
  },
234
188
 
235
- logOut: (callback?: Function) => {
189
+ logOut: (callback?: () => void) => {
236
190
  console.log('onLogout');
237
191
  Auth.logOut();
238
- callback && callback();
192
+ callback?.();
239
193
  Notification.postNotification('onLogout');
240
194
  },
241
195
 
@@ -257,24 +211,28 @@ export const LoginManager = {
257
211
  batchUpdateUser: async (
258
212
  keys: string[],
259
213
  values: any[],
260
- callback?: Function
214
+ callback?: (error?: unknown) => void
261
215
  ) => {
262
216
  try {
263
217
  console.log('Batch Update User Begin: ' + keys + ' ' + values);
264
218
  const user = await Auth.batchUpdateUser(keys, values);
265
219
  console.log('Batch Update User End', user);
266
- callback && callback();
220
+ callback?.();
267
221
  } catch (e) {
268
222
  console.error(e);
269
- callback && callback(e);
223
+ callback?.(e);
270
224
  }
271
225
  },
272
226
 
273
- updateUser: (key: string, value: any, callback?: Function) => {
227
+ updateUser: (
228
+ key: string,
229
+ value: any,
230
+ callback?: (error?: unknown) => void
231
+ ) => {
274
232
  LoginManager.batchUpdateUser([key], [value], callback);
275
233
  },
276
234
 
277
- deleteUser: async (callback: Function) => {
235
+ deleteUser: async (callback: (error?: unknown) => void) => {
278
236
  try {
279
237
  const currentUser = Auth.currentUser();
280
238
  if (!currentUser) {
@@ -299,14 +257,16 @@ export const LoginManager = {
299
257
  return PrefData.getValue(BuildInPrefs.RegisterInThisDevice);
300
258
  },
301
259
 
302
- fetchWeChatAvatar: (callback: FetchImageFunctionType) => {
303
- WeChatLoginUtil.doLogin(
304
- ToolkitConfig.WeiXinId,
305
- ToolkitConfig.WeiXinSecret,
306
- ({ headimgurl }: { headimgurl: string }) => {
307
- callback({ headimgurl });
308
- }
309
- );
260
+ fetchWeChatAvatar: async (callback: FetchImageFunctionType) => {
261
+ try {
262
+ const { headimgurl } = await WeChatLoginUtil.doLogin(
263
+ ToolkitConfig.WeiXinId,
264
+ ToolkitConfig.WeiXinSecret
265
+ );
266
+ callback({ headimgurl });
267
+ } catch (_) {
268
+ // 获取头像失败,忽略
269
+ }
310
270
  },
311
271
 
312
272
  getRegisterDays: () => {
@@ -1,6 +1,7 @@
1
1
  import { sha1 } from 'js-sha1';
2
2
  import { NativeEventEmitter, NativeModules } from 'react-native';
3
3
  import * as WeChat from 'react-native-wechat-lib';
4
+ import { ThirdPartyUserInfo } from './constant';
4
5
  import { Tool } from './Tool';
5
6
 
6
7
  // https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
@@ -44,13 +45,12 @@ const createSignature = (
44
45
  return ret;
45
46
  };
46
47
 
47
- const getUserInfo = (
48
+ const getUserInfo = async (
48
49
  WeiXinId: string,
49
50
  WeiXinSecret: string,
50
- code: string,
51
- callback: Function
52
- ) => {
53
- let accessTokenUrl =
51
+ code: string
52
+ ): Promise<ThirdPartyUserInfo> => {
53
+ const accessTokenUrl =
54
54
  'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' +
55
55
  WeiXinId +
56
56
  '&secret=' +
@@ -58,64 +58,43 @@ const getUserInfo = (
58
58
  '&code=' +
59
59
  code +
60
60
  '&grant_type=authorization_code';
61
- fetch(accessTokenUrl)
62
- .then((res) => {
63
- return res.json();
64
- })
65
- .then((res) => {
66
- console.log('wechat get access code success: ', res.access_token);
67
- let userInfoUrl =
68
- 'https://api.weixin.qq.com/sns/userinfo?access_token=' +
69
- res.access_token +
70
- '&openid=' +
71
- res.openid;
72
- fetch(userInfoUrl)
73
- .then((res2) => {
74
- return res2.json();
75
- })
76
- .then((json) => {
77
- console.log('wechat get user info success: ', json);
78
- callback({
79
- nickname: json.nickname,
80
- headimgurl: json.headimgurl,
81
- openid: json.openid,
82
- unionid: json.unionid,
83
- });
84
- })
85
- .catch((e) => {
86
- console.warn('wechat get user info fail ', e);
87
- callback({ error: e });
88
- });
89
- })
90
- .catch((e) => {
91
- console.warn('wechat get access code fail ', e);
92
- callback({ error: e });
93
- });
61
+ const res = await (await fetch(accessTokenUrl)).json();
62
+ console.log('wechat get access code success: ', res.access_token);
63
+
64
+ const userInfoUrl =
65
+ 'https://api.weixin.qq.com/sns/userinfo?access_token=' +
66
+ res.access_token +
67
+ '&openid=' +
68
+ res.openid;
69
+ const json = await (await fetch(userInfoUrl)).json();
70
+ console.log('wechat get user info success: ', json);
71
+
72
+ return {
73
+ nickname: json.nickname,
74
+ headimgurl: json.headimgurl,
75
+ openid: json.openid,
76
+ unionid: json.unionid,
77
+ };
94
78
  };
95
79
 
96
80
  export const WeChatLoginUtil = {
97
- doLogin: (WeiXinId: string, WeiXinSecret: string, callback: Function) => {
98
- WeChat.sendAuthRequest('snsapi_userinfo')
99
- .then((ret) => {
100
- console.log('wechat auth success ', ret);
101
- if (!ret?.code) {
102
- callback({ error: 'Auth code 获取失败' });
103
- return;
104
- }
105
- getUserInfo(WeiXinId, WeiXinSecret, ret?.code, callback);
106
- })
107
- .catch((e: any) => {
108
- console.warn('wechat auth fail ', e);
109
- callback({ error: e });
110
- });
81
+ doLogin: async (
82
+ WeiXinId: string,
83
+ WeiXinSecret: string
84
+ ): Promise<ThirdPartyUserInfo> => {
85
+ const ret = await WeChat.sendAuthRequest('snsapi_userinfo');
86
+ console.log('wechat auth success ', ret);
87
+ if (!ret?.code) {
88
+ throw new Error('Auth code 获取失败');
89
+ }
90
+ return getUserInfo(WeiXinId, WeiXinSecret, ret.code);
111
91
  },
112
92
 
113
93
  doLoginByScan: async (
114
94
  WeiXinId: string,
115
95
  WeiXinSecret: string,
116
- onQRGet: (qrcode: string) => void,
117
- callback: Function
118
- ) => {
96
+ onQRGet: (qrcode: string) => void
97
+ ): Promise<ThirdPartyUserInfo> => {
119
98
  const accessToken = await getAccessToken(WeiXinId, WeiXinSecret);
120
99
  const ticket = await getSDKTicket(accessToken);
121
100
  const nonceStr = Tool.generateObjectId();
@@ -128,22 +107,26 @@ export const WeChatLoginUtil = {
128
107
  onQRGet(res.qrcode)
129
108
  );
130
109
 
131
- NativeModules.WeChat.authByScan(
132
- WeiXinId,
133
- nonceStr,
134
- timestamp,
135
- 'snsapi_userinfo',
136
- signature,
137
- '',
138
- (ret: any) => {
139
- console.log('scan result', ret);
140
- subscription.remove();
141
- if (!ret?.authCode) {
142
- callback({ error: 'Auth code 获取失败' });
143
- return;
110
+ const authCode = await new Promise<string>((resolve, reject) => {
111
+ NativeModules.WeChat.authByScan(
112
+ WeiXinId,
113
+ nonceStr,
114
+ timestamp,
115
+ 'snsapi_userinfo',
116
+ signature,
117
+ '',
118
+ (ret: any) => {
119
+ console.log('scan result', ret);
120
+ subscription.remove();
121
+ if (!ret?.authCode) {
122
+ reject(new Error('Auth code 获取失败'));
123
+ } else {
124
+ resolve(ret.authCode);
125
+ }
144
126
  }
145
- getUserInfo(WeiXinId, WeiXinSecret, ret?.authCode, callback);
146
- }
147
- );
127
+ );
128
+ });
129
+
130
+ return getUserInfo(WeiXinId, WeiXinSecret, authCode);
148
131
  },
149
132
  };
package/src/constant.ts CHANGED
@@ -26,6 +26,13 @@ export interface LoginUserDataType {
26
26
  authData: LoginAuthDataType;
27
27
  }
28
28
 
29
+ export interface ThirdPartyUserInfo {
30
+ nickname: string;
31
+ headimgurl: string;
32
+ openid: string;
33
+ unionid: string;
34
+ }
35
+
29
36
  export enum LoginState {
30
37
  NOTLOGIN,
31
38
  AUTHORIZED,