@norcy/react-native-toolkit 0.3.21 → 0.3.23

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 (36) hide show
  1. package/lib/commonjs/AppleLoginUtil.js +33 -85
  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 +104 -114
  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 +1 -6
  10. package/lib/commonjs/constant.js.map +1 -1
  11. package/lib/module/AppleLoginUtil.js +33 -85
  12. package/lib/module/AppleLoginUtil.js.map +1 -1
  13. package/lib/module/HuaweiLoginUtil.js +10 -22
  14. package/lib/module/HuaweiLoginUtil.js.map +1 -1
  15. package/lib/module/LoginManager.js +105 -115
  16. package/lib/module/LoginManager.js.map +1 -1
  17. package/lib/module/WeChatLoginUtil.js +32 -56
  18. package/lib/module/WeChatLoginUtil.js.map +1 -1
  19. package/lib/module/constant.js +0 -5
  20. package/lib/module/constant.js.map +1 -1
  21. package/lib/typescript/AppleLoginUtil.d.ts +1 -15
  22. package/lib/typescript/AppleLoginUtil.d.ts.map +1 -1
  23. package/lib/typescript/HuaweiLoginUtil.d.ts +2 -7
  24. package/lib/typescript/HuaweiLoginUtil.d.ts.map +1 -1
  25. package/lib/typescript/LoginManager.d.ts +1 -1
  26. package/lib/typescript/LoginManager.d.ts.map +1 -1
  27. package/lib/typescript/WeChatLoginUtil.d.ts +3 -2
  28. package/lib/typescript/WeChatLoginUtil.d.ts.map +1 -1
  29. package/lib/typescript/constant.d.ts +5 -3
  30. package/lib/typescript/constant.d.ts.map +1 -1
  31. package/package.json +1 -1
  32. package/src/AppleLoginUtil.ts +29 -50
  33. package/src/HuaweiLoginUtil.ts +11 -24
  34. package/src/LoginManager.ts +82 -125
  35. package/src/WeChatLoginUtil.ts +54 -71
  36. package/src/constant.ts +5 -3
@@ -8,20 +8,11 @@ import { ToolkitConfig } from './Tool';
8
8
  import { WeChatLoginUtil } from './WeChatLoginUtil';
9
9
  import {
10
10
  LoginAuthDataType,
11
- LoginState,
12
11
  LoginType,
13
12
  LoginUserDataType,
14
13
  UserType,
15
14
  } from './constant';
16
15
 
17
- type WeChatCallbackResult = {
18
- nickname: string;
19
- headimgurl: string;
20
- openid: string;
21
- unionid: string;
22
- error: any;
23
- };
24
-
25
16
  type FetchImageFunctionType = ({ headimgurl }: { headimgurl: string }) => void;
26
17
  export type LoginSuccessResultType = {
27
18
  isAuto?: boolean;
@@ -33,25 +24,26 @@ export type LoginFailResultType = {
33
24
  code?: string;
34
25
  };
35
26
 
36
- type LoginFinishParams = {
37
- isAuto?: boolean;
38
- user?: UserType;
39
- error?: string | object;
40
- code?: string;
41
- };
27
+ type LoginFinishParams =
28
+ | { isAuto?: boolean; user: UserType }
29
+ | { isAuto?: boolean; error: unknown };
42
30
 
43
- const onLoginFinish = ({
44
- isAuto = false,
45
- user,
46
- error,
47
- code,
48
- }: LoginFinishParams) => {
49
- if (user) {
31
+ const onLoginFinish = (params: LoginFinishParams) => {
32
+ if ('user' in params) {
33
+ const { isAuto = false, user } = params;
50
34
  PrefData.setValue(BuildInPrefs.LastLoginType, user.type);
51
35
  const data = { isAuto, user };
52
36
  console.log('onLoginSuccess', data);
53
37
  Notification.postNotification('onLoginSuccess', data);
54
38
  } else {
39
+ const { isAuto = false, error } = params;
40
+ if (__DEV__ && !(error instanceof Error)) {
41
+ console.error('onLoginFinish: error should be an Error instance, got:', error);
42
+ }
43
+ const code =
44
+ error instanceof Error && 'code' in error
45
+ ? String((error as Error & { code: unknown }).code)
46
+ : undefined;
55
47
  const data = { isAuto, error, code };
56
48
  console.log('onLoginFail', data);
57
49
  Notification.postNotification('onLoginFail', data);
@@ -107,90 +99,55 @@ export const LoginManager = {
107
99
  }
108
100
 
109
101
  if (type === LoginType.LoginTypeApple) {
110
- const { user, email, error, code } =
111
- await AppleLoginUtil.requestAppleUserForLogin();
112
- if (!user || error) {
113
- onLoginFinish({ error, code });
114
- return;
115
- } else {
102
+ try {
103
+ const { user, email } =
104
+ await AppleLoginUtil.requestAppleUserForLogin();
105
+ await AppleLoginUtil.fetchAndUpdateCredentialState(user);
116
106
  let userData = {
117
107
  userId: user,
118
- email: email,
119
- authData: {
120
- openid: user,
121
- loginType: 'apple',
122
- },
108
+ email,
109
+ authData: { openid: user, loginType: 'apple' as const },
123
110
  };
124
-
125
- AppleLoginUtil.fetchAndUpdateCredentialState(
126
- userData.userId,
127
- ({ result, error: error2 }: { result: number; error: any }) => {
128
- if (error || result !== LoginState.AUTHORIZED) {
129
- onLoginFinish({ error: error2 });
130
- } else {
131
- loadingCallback?.();
132
- doLogin(userData.authData, userData);
133
- }
134
- }
135
- );
111
+ loadingCallback?.();
112
+ doLogin(userData.authData, userData);
113
+ } catch (error) {
114
+ onLoginFinish({ error });
136
115
  }
137
116
  } else if (type === LoginType.LoginTypeWeChat) {
138
- WeChatLoginUtil.doLogin(
139
- ToolkitConfig.WeiXinId,
140
- ToolkitConfig.WeiXinSecret,
141
- ({
117
+ try {
118
+ const { nickname, headimgurl, openid, unionid } =
119
+ await WeChatLoginUtil.doLogin(
120
+ ToolkitConfig.WeiXinId,
121
+ ToolkitConfig.WeiXinSecret
122
+ );
123
+ let userData = {
142
124
  nickname,
143
125
  headimgurl,
144
- openid,
145
- unionid,
146
- error,
147
- }: WeChatCallbackResult) => {
148
- if (error) {
149
- onLoginFinish({ error });
150
- } else {
151
- let userData = {
152
- nickname: nickname,
153
- headimgurl: headimgurl,
154
- authData: {
155
- openid: openid,
156
- unionid: unionid,
157
- loginType: 'wechat',
158
- },
159
- };
160
- loadingCallback?.();
161
- doLogin(userData.authData, userData);
162
- }
163
- }
164
- );
126
+ authData: { openid, unionid, loginType: 'wechat' as const },
127
+ };
128
+ loadingCallback?.();
129
+ doLogin(userData.authData, userData);
130
+ } catch (error) {
131
+ onLoginFinish({ error });
132
+ }
165
133
  } else if (type === LoginType.LoginTypeWeChatScan) {
166
- WeChatLoginUtil.doLoginByScan(
167
- ToolkitConfig.WeiXinId,
168
- ToolkitConfig.WeiXinSecret,
169
- qrcodeCallback!,
170
- ({
134
+ try {
135
+ const { nickname, headimgurl, openid, unionid } =
136
+ await WeChatLoginUtil.doLoginByScan(
137
+ ToolkitConfig.WeiXinId,
138
+ ToolkitConfig.WeiXinSecret,
139
+ qrcodeCallback!
140
+ );
141
+ let userData = {
171
142
  nickname,
172
143
  headimgurl,
173
- openid,
174
- unionid,
175
- error,
176
- }: WeChatCallbackResult) => {
177
- if (error) {
178
- onLoginFinish({ error });
179
- } else {
180
- let userData = {
181
- nickname: nickname,
182
- headimgurl: headimgurl,
183
- authData: {
184
- openid: openid,
185
- unionid: unionid,
186
- loginType: 'wechat',
187
- },
188
- };
189
- loadingCallback?.();
190
- doLogin(userData.authData, userData);
191
- }
192
- }
193
- );
144
+ authData: { openid, unionid, loginType: 'wechat' as const },
145
+ };
146
+ loadingCallback?.();
147
+ doLogin(userData.authData, userData);
148
+ } catch (error) {
149
+ onLoginFinish({ error });
150
+ }
194
151
  } else if (type === LoginType.LoginTypeVisitor) {
195
152
  const uniqueId = getUniqueIdSync();
196
153
  console.log(uniqueId);
@@ -204,27 +161,21 @@ export const LoginManager = {
204
161
  loadingCallback?.();
205
162
  doLogin(userData.authData, userData);
206
163
  } else if (type === LoginType.LoginTypeHuawei) {
207
- HuaweiLoginUtil.doLogin(
208
- ({ nickname, headimgurl, openid, unionid, error }) => {
209
- if (error) {
210
- onLoginFinish({ error });
211
- } else {
212
- let userData = {
213
- nickname: nickname,
214
- headimgurl: headimgurl,
215
- authData: {
216
- openid: openid!,
217
- unionid: unionid,
218
- loginType: 'huawei',
219
- },
220
- };
221
- loadingCallback?.();
222
- doLogin(userData.authData, userData);
223
- }
224
- }
225
- );
164
+ try {
165
+ const { nickname, headimgurl, openid, unionid } =
166
+ await HuaweiLoginUtil.doLogin();
167
+ let userData = {
168
+ nickname,
169
+ headimgurl,
170
+ authData: { openid, unionid, loginType: 'huawei' as const },
171
+ };
172
+ loadingCallback?.();
173
+ doLogin(userData.authData, userData);
174
+ } catch (error) {
175
+ onLoginFinish({ error });
176
+ }
226
177
  } else {
227
- onLoginFinish({ error: 'Unknown Login Type' });
178
+ onLoginFinish({ error: new Error('Unknown Login Type') });
228
179
  }
229
180
  },
230
181
 
@@ -266,7 +217,11 @@ export const LoginManager = {
266
217
  }
267
218
  },
268
219
 
269
- updateUser: (key: string, value: any, callback?: (error?: unknown) => void) => {
220
+ updateUser: (
221
+ key: string,
222
+ value: any,
223
+ callback?: (error?: unknown) => void
224
+ ) => {
270
225
  LoginManager.batchUpdateUser([key], [value], callback);
271
226
  },
272
227
 
@@ -295,14 +250,16 @@ export const LoginManager = {
295
250
  return PrefData.getValue(BuildInPrefs.RegisterInThisDevice);
296
251
  },
297
252
 
298
- fetchWeChatAvatar: (callback: FetchImageFunctionType) => {
299
- WeChatLoginUtil.doLogin(
300
- ToolkitConfig.WeiXinId,
301
- ToolkitConfig.WeiXinSecret,
302
- ({ headimgurl }: { headimgurl: string }) => {
303
- callback({ headimgurl });
304
- }
305
- );
253
+ fetchWeChatAvatar: async (callback: FetchImageFunctionType) => {
254
+ try {
255
+ const { headimgurl } = await WeChatLoginUtil.doLogin(
256
+ ToolkitConfig.WeiXinId,
257
+ ToolkitConfig.WeiXinSecret
258
+ );
259
+ callback({ headimgurl });
260
+ } catch (_) {
261
+ // 获取头像失败,忽略
262
+ }
306
263
  },
307
264
 
308
265
  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,9 +26,11 @@ export interface LoginUserDataType {
26
26
  authData: LoginAuthDataType;
27
27
  }
28
28
 
29
- export enum LoginState {
30
- NOTLOGIN,
31
- AUTHORIZED,
29
+ export interface ThirdPartyUserInfo {
30
+ nickname: string;
31
+ headimgurl: string;
32
+ openid: string;
33
+ unionid: string;
32
34
  }
33
35
 
34
36
  export enum LoginType {