http.uts
16.2 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
import { storage } from "../../utils/storage.uts";
import { djDomain, djSecretKey, domain, merchantDomain, pathEnum, secretKey, shukeDomain } from "../env.uts";
import { sign } from "./sign.uts";
type HostType = "dj" | "ip" | "merchant" | "scrm";
// 响应日志开关:需要更安静时可改为 false
const ENABLE_HTTP_RESPONSE_LOG: boolean = true;
const HOST = {
"scrm": domain,
"dj": djDomain,
"merchant": merchantDomain,
"ip": "http://192.168.1.125:8080"
} as UTSJSONObject;
/**
* HTTP 请求封装(从 gl_tape/api/request/http.js 迁移)
* - 统一处理 GET / POST
* - 自动注入 appKey / secret / sessionId 等并完成参数签名
* - 处理业务 code 及登录态失效跳转
*/
class Request {
private safeJsonStringify(v: any | null): string {
if (v == null) {
return "null";
}
try {
return JSON.stringify(v);
} catch (e) {
return `${v}`;
}
}
private logResponse(
channel: "rop" | "shuke" | "raw",
requestMethod: string,
url: string,
startAtMs: number,
statusCode: number | null,
resData: any | null,
errMsg: string | null
): void {
if (!ENABLE_HTTP_RESPONSE_LOG) {
return;
}
const costMs = Date.now() - startAtMs;
let bizCodeStr = "";
let bizMsgStr = "";
if (resData != null) {
const obj = resData as UTSJSONObject;
const bizCode = obj["code"];
const bizMsg = obj["message"];
if (bizCode != null) {
bizCodeStr = `${bizCode}`;
}
if (bizMsg != null) {
bizMsgStr = `${bizMsg}`;
}
}
const statusStr = statusCode != null ? `${statusCode}` : "";
const errStr = errMsg != null ? errMsg : "";
// console.log(
// `[http][${channel}] ${requestMethod} ${url} cost=${costMs}ms status=${statusStr} bizCode=${bizCodeStr} bizMsg=${bizMsgStr} err=${errStr} res=${this.safeJsonStringify(resData)}`
// );
}
/**
* 网关部分接口除 Header.Authorization 外,仍校验 JSON 内的 sessionId(与 signHttp 注入 ROP sessionId 一致)。
* 缺省、空串或与 Header 不一致时写入当前存储的会话 id。
*/
private ensureShukeJsonBodySessionId(body: UTSJSONObject, sessionHeader: string | null): UTSJSONObject {
if (sessionHeader == null || sessionHeader === "") {
return body;
}
const raw = body["sessionId"];
const rawStr = raw != null ? `${raw}` : "";
const bad = rawStr === "" || rawStr === "null" || rawStr !== sessionHeader;
if (!bad) {
return body;
}
const copy = JSON.parse(JSON.stringify(body)) as UTSJSONObject;
copy["sessionId"] = sessionHeader;
return copy;
}
/**
* 会话 id 归一化:避免 "" / "null" 等被当作有效值参与签名并触发网关「无效的sessionId参数」
*/
private normalizeSessionIdValue(raw: any | null): string | null {
if (raw == null) {
return null;
}
const s = `${raw}`.trim();
if (s === "" || s === "null" || s === "undefined") {
return null;
}
return s;
}
/**
* 业务方法调用封装
* @param method ROP 接口方法名
* @param data 业务参数
* @param returnAll 是否返回完整响应体
* @param hostType 域名类型
*/
fetch(method: string, data: UTSJSONObject, returnAll: boolean = true, hostType: HostType | null = null): Promise<any> {
const payload: UTSJSONObject = {};
payload.method = method;
// 合并业务参数
for (const key in data) {
payload[key] = data[key];
}
return this.post(payload, returnAll, hostType, null);
}
get(params: UTSJSONObject, returnAll: boolean = false, hostType: HostType | null = null): Promise<any> {
return this.request("GET", params, returnAll, hostType, null);
}
post(params: UTSJSONObject, returnAll: boolean = false, hostType: HostType | null = null, timeout: null | number = null): Promise<any> {
return this.request("POST", params, returnAll, hostType, timeout);
}
/**
* 数科 linkwe-gateway JSON 接口(对齐 simgle_app/api/request/http.js `shukeRequest`:JSON、Authorization=sessionId、401 尝试 restore)
*/
shukeRequest(urlPath: string, body: UTSJSONObject, method: "GET" | "POST", returnAll: boolean): Promise<any> {
return new Promise((resolve, reject) => {
uni.getNetworkType({
success: (res) => {
if (res.networkType == "none") {
uni.hideLoading();
uni.showToast({
title: "网络异常",
icon: "none"
});
reject("网络异常");
return;
}
const rawSession = storage.get("sessionId");
const sessionId = (rawSession != null && rawSession != "") ? `${rawSession}` : null;
const header: UTSJSONObject = method === "POST"
? { "content-type": "application/json" }
: { "Cache-Control": "no-cache", "Content-Type": "application/json" };
if (sessionId != null) {
header.Authorization = sessionId;
}
const fullUrl = `${shukeDomain}/${urlPath}`;
const requestBody = this.ensureShukeJsonBodySessionId(body, sessionId);
const startAtMs = Date.now();
uni.request({
url: fullUrl,
data: requestBody,
method,
header,
dataType: "json",
responseType: "text",
timeout: 60_000,
success: (response) => {
const resData: any | null = response.data;
const statusCode = response.statusCode;
this.logResponse("shuke", method, fullUrl, startAtMs, statusCode as number, resData, null);
if (resData == null || statusCode != 200) {
uni.hideLoading();
const errMsg = resData == null ? "获取数据失败,请重试。" : "服务器暂时不可用,请稍后再次尝试。";
uni.showToast({
title: errMsg,
icon: "none"
});
reject(errMsg);
return;
}
const dataObj = resData as UTSJSONObject;
// 须先于 returnAll 分支:saveRecCustomer / confirm 等均 returnAll=true,否则 401 永远不会走 restore
const code = dataObj.code;
if (`${code}` == "401") {
const currentSessionId = storage.get("sessionId") as string | null;
if (currentSessionId != null && currentSessionId != "") {
this.restoreShukeLogin(resolve, reject, urlPath, requestBody, method, returnAll, `${currentSessionId}`);
} else {
this.redirectShukeToLogin(reject);
}
return;
}
if (returnAll) {
resolve(dataObj);
return;
}
const payload = dataObj.data;
resolve(payload != null ? (payload as any) : ({} as UTSJSONObject));
},
fail: (error) => {
uni.hideLoading();
const errMsg = error.errMsg != null && error.errMsg != "" ? `${error.errMsg}` : "系统异常";
this.logResponse("shuke", method, fullUrl, startAtMs, null, null, errMsg);
uni.showToast({
title: errMsg,
icon: "none"
});
reject(errMsg);
}
});
}
});
});
}
private restoreShukeLogin(
resolve: (v: any) => void,
reject: (e: any) => void,
urlPath: string,
body: UTSJSONObject,
method: "GET" | "POST",
returnAll: boolean,
currentSessionId: string
): void {
uni.request({
url: `${shukeDomain}/linkwe-gateway/auth/accountLoginSp/restore`,
data: { token: currentSessionId } as UTSJSONObject,
method: "POST",
header: { "content-type": "application/json" } as UTSJSONObject,
dataType: "json",
success: (restoreRes) => {
const restoreData = restoreRes.data as UTSJSONObject | null;
if (restoreData != null && `${restoreData["code"]}` == "200") {
const inner = restoreData["data"] as UTSJSONObject | null;
const newToken =
(inner != null ? (inner["sessionId"] as string | null) : null) ??
(inner != null ? (inner["token"] as string | null) : null) ??
(inner != null ? (inner["access_token"] as string | null) : null);
if (newToken != null && newToken != "") {
storage.set("sessionId", newToken, 0);
}
const userInfo = inner != null ? inner["loginUser"] : null;
if (userInfo == null) {
const u2 = inner != null ? inner["user"] : null;
if (u2 != null) {
storage.set("userInfo", u2, 0);
}
} else {
storage.set("userInfo", userInfo, 0);
}
const onAfterRestoreReject = (err: any): void => {
const msg: string = err != null ? `${err}` : "请求失败";
reject(msg);
};
this.shukeRequest(urlPath, body, method, returnAll).then(
(v: any): void => {
resolve(v);
},
onAfterRestoreReject
);
} else {
this.redirectShukeToLogin(reject);
}
},
fail: () => {
this.redirectShukeToLogin(reject);
}
});
}
private redirectShukeToLogin(reject: (e: any) => void): void {
storage.set("sessionId", "", 0);
storage.set("userInfo", {} as UTSJSONObject, 0);
storage.set("noSignInUuid", "", 0);
uni.hideLoading();
const pages = getCurrentPages();
if (pages.length > 0) {
const currentPage = pages[pages.length - 1];
if (currentPage.route != "pages/common/login/index") {
uni.reLaunch({
url: "/pages/common/login/index"
});
}
}
reject("登录已过期,请重新登录");
}
/**
* 简单的原始 uni.request 封装
*/
uni_request(options: UTSJSONObject): Promise<any> {
const url = options.url as string;
const method = (options.method ?? "GET") as string;
const data = (options.data ?? ({} as UTSJSONObject)) as UTSJSONObject;
const header = (options.header ?? ({} as UTSJSONObject)) as UTSJSONObject;
const dataType = (options.dataType ?? "json") as string;
const responseType = (options.responseType ?? "text") as string;
return new Promise((resolve) => {
const startAtMs = Date.now();
uni.request({
url,
data,
method,
header,
dataType,
responseType,
success: (response) => {
const resData = response.data;
this.logResponse("raw", method, url, startAtMs, response.statusCode as number, resData as any, null);
resolve(resData != null ? resData : ({} as UTSJSONObject));
},
fail: (error) => {
const errMsg = error.errMsg != null && error.errMsg != "" ? `${error.errMsg}` : "系统异常";
this.logResponse("raw", method, url, startAtMs, null, null, errMsg);
resolve({} as UTSJSONObject);
}
});
});
}
/**
* 组装 ROP 请求参数并完成签名
*/
private getData(params: UTSJSONObject, hostType: HostType): UTSJSONObject {
let projectName = (params.projectName ?? "") as string;
if (projectName == "") {
projectName = this.getRopProject(params.method as string);
} else {
// 使用后删除 projectName 字段(UTS 不支持 delete,改为置空)
params.projectName = null;
}
let appKey = "48e5e13229b82c1b4e6e8c96151f0637";
let secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";
const projectSecret = secretKey[projectName] as null | UTSJSONObject;
if (projectSecret != null) {
appKey = projectSecret.appKey as string;
secret = projectSecret.secret as string;
}
if (hostType == "dj") {
const djKey = djSecretKey as UTSJSONObject;
appKey = djKey.appKey as string;
secret = djKey.secret as string;
}
params.sessionId = this.normalizeSessionIdValue(params["sessionId"] as any|null);
const sessionFromStore = this.normalizeSessionIdValue(storage.get("sessionId") as any|null);
let noSignAttr: string[] = [];
if (params.sessionId == null && sessionFromStore != null) {
params.sessionId = sessionFromStore;
}
if (params.delSessionId != null) {
params.sessionId = null;
params.delSessionId = null;
}
if (params.noSignAttr != null) {
noSignAttr = params.noSignAttr as string[];
params.noSignAttr = null;
}
params.v = "1.0.0";
params.format = "json";
params.locale = "zh_CN";
params.source = "app";
params.appKey = appKey;
return sign(params, secret, noSignAttr);
}
/**
* 根据 method 解析出 rop 项目名
* @example sso.xxx.xxx => 第三个段作为项目名
*/
private getRopProject(method: string): string {
const parts = method.split(".");
if (parts.length >= 3) {
return parts[2];
}
return "";
}
private request(
requestMethod: "GET" | "POST",
params: UTSJSONObject,
returnAll: boolean,
hostType: HostType | null,
timeout: null | number
): Promise<any> {
const finalHostType: HostType = hostType != null ? hostType : "dj";
return new Promise((resolve, reject) => {
uni.getNetworkType({
success: (res) => {
if (res.networkType == "none") {
uni.hideLoading();
uni.showToast({
title: "网络异常",
icon: "none"
});
reject("网络异常");
return;
}
const header = requestMethod === "POST"
? { "content-type": "application/x-www-form-urlencoded" }
: { "Cache-Control": "no-cache" };
let projectName = (params.projectName ?? "") as string;
if (projectName == "") {
projectName = this.getRopProject(params.method as string);
}
const path = pathEnum[projectName] ?? "";
const requestData = this.getData(params, finalHostType);
// Android 原生层对 data 类型敏感:传 string 可能触发 ClassCastException
// 改为传 UTSJSONObject(全 string 值),由框架序列化为 form-urlencoded
const formDataObj: UTSJSONObject = {};
for (const key in requestData) {
const val = requestData[key];
if (val != null) {
let valStr: string;
if (typeof val === "string") {
valStr = val;
} else if (typeof val === "number" || typeof val === "boolean") {
valStr = `${val}`;
} else {
valStr = JSON.stringify(val);
}
formDataObj[key] = valStr;
}
}
const hostUrl = HOST[finalHostType] as string;
const pathStr = (path != null && path != "") ? `${path}` : "";
const methodStr = (requestData.method != null && requestData.method != "") ? `${requestData.method}` : "";
const fullUrl = `${hostUrl}${pathStr}router?method=${methodStr}`;
const startAtMs = Date.now();
uni.request({
url: fullUrl,
data: formDataObj,
method: requestMethod,
header,
dataType: "json",
responseType: "text",
timeout: timeout ?? 60_000,
success: (response) => {
const resData: any | null = response.data;
const statusCode = response.statusCode;
this.logResponse("rop", requestMethod, fullUrl, startAtMs, statusCode as number, resData, null);
if (resData == null || statusCode != 200) {
uni.hideLoading();
let errMsg = "";
if (resData == null) {
errMsg = "获取数据失败,请重试。";
} else {
errMsg = "服务器暂时不可用,请稍后再次尝试。";
}
reject(errMsg);
return;
}
const dataObj = resData as UTSJSONObject;
const code = (dataObj.code ?? "") as any;
const message = (dataObj.message ?? "") as string;
if (returnAll) {
resolve(resData);
return;
}
if (code == 20 || code == 21) {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
uni.hideLoading();
if (currentPage.route != "pages/common/login/index") {
// uni.reLaunch({
// url: "/pages/common/login/index"
// });
// this.redirectShukeToLogin(reject)
}
reject(message != "" ? message : "登录已过期,请重新登录");
return;
}
if (`${code}` == "0") {
const bizData: any | null = dataObj.data as any | null;
if (bizData != null) {
resolve(bizData);
} else {
resolve({} as UTSJSONObject);
}
return;
}
uni.hideLoading();
uni.showToast({
title: message != "" ? message : "系统异常",
icon: "none"
});
reject(message != "" ? message : "系统异常");
},
fail: (error) => {
uni.hideLoading();
console.error(`${params.method} 接口异常:`, error);
const errMsg = error.errMsg != null && error.errMsg != "" ? `${error.errMsg}` : "系统异常";
this.logResponse("rop", requestMethod, fullUrl, startAtMs, null, null, errMsg);
uni.showToast({
title: JSON.stringify(error),
icon: "error"
});
reject(error);
},
complete: () => {
uni.stopPullDownRefresh();
}
});
},
fail: () => {
uni.hideLoading();
reject("获取网络状态失败");
}
});
});
}
}
const http = new Request();
export default http;