-
Notifications
You must be signed in to change notification settings - Fork 942
Expand file tree
/
Copy pathgopay-utils.js
More file actions
462 lines (419 loc) · 16 KB
/
gopay-utils.js
File metadata and controls
462 lines (419 loc) · 16 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
(function attachGoPayUtils(root, factory) {
root.GoPayUtils = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createGoPayUtils() {
const PLUS_PAYMENT_METHOD_PAYPAL = 'paypal';
const PLUS_PAYMENT_METHOD_PAYPAL_HOSTED = 'paypal-hosted';
const PLUS_PAYMENT_METHOD_NONE = 'none';
const PLUS_PAYMENT_METHOD_GOPAY = 'gopay';
const PLUS_PAYMENT_METHOD_GPC_HELPER = 'gpc-helper';
const DEFAULT_GPC_HELPER_API_URL = 'https://gpc.qlhazycoder.top';
const GPC_HELPER_PHONE_MODE_AUTO = 'auto';
const GPC_HELPER_PHONE_MODE_MANUAL = 'manual';
const ALLOWED_GPC_HELPER_REMOTE_HOST = 'gpc.qlhazycoder.top';
function normalizePlusPaymentMethod(value = '') {
const normalized = String(value || '').trim().toLowerCase();
if (normalized === PLUS_PAYMENT_METHOD_NONE || normalized === 'no-payment' || normalized === 'skip-payment') {
return PLUS_PAYMENT_METHOD_NONE;
}
if (normalized === PLUS_PAYMENT_METHOD_PAYPAL_HOSTED || normalized === 'paypal_direct' || normalized === 'paypal-direct') {
return PLUS_PAYMENT_METHOD_PAYPAL_HOSTED;
}
if (normalized === PLUS_PAYMENT_METHOD_GPC_HELPER) {
return PLUS_PAYMENT_METHOD_GPC_HELPER;
}
return normalized === PLUS_PAYMENT_METHOD_GOPAY ? PLUS_PAYMENT_METHOD_GOPAY : PLUS_PAYMENT_METHOD_PAYPAL;
}
const DEFAULT_GOPAY_COUNTRY_CODE = '+86';
function normalizeGoPayCountryCode(value = '') {
const normalized = String(value || '').trim().replace(/[^\d+]/g, '');
const digits = normalized.replace(/\D/g, '');
return digits ? `+${digits}` : DEFAULT_GOPAY_COUNTRY_CODE;
}
function normalizeGoPayPhone(value = '') {
return String(value || '').trim().replace(/[^\d+]/g, '');
}
function normalizeGoPayPhoneForCountry(value = '', countryCode = DEFAULT_GOPAY_COUNTRY_CODE) {
const normalizedPhone = normalizeGoPayPhone(value);
const normalizedCountryCode = normalizeGoPayCountryCode(countryCode);
const countryDigits = normalizedCountryCode.replace(/\D/g, '');
let nationalNumber = normalizedPhone.replace(/\D/g, '');
if (countryDigits && nationalNumber.startsWith(countryDigits)) {
nationalNumber = nationalNumber.slice(countryDigits.length);
}
return nationalNumber;
}
function normalizeGoPayPin(value = '') {
return String(value || '').trim().replace(/[^\d]/g, '');
}
function normalizeGoPayOtp(value = '') {
return String(value || '').trim().replace(/[^\d]/g, '');
}
function normalizeGpcHelperPhoneMode(value = '') {
const normalized = String(value || '').trim().toLowerCase();
return normalized === GPC_HELPER_PHONE_MODE_AUTO || normalized === 'builtin'
? GPC_HELPER_PHONE_MODE_AUTO
: GPC_HELPER_PHONE_MODE_MANUAL;
}
function normalizeGpcRemainingUses(value) {
if (value === undefined || value === null || String(value).trim() === '') {
return null;
}
const numeric = Number(value);
return Number.isFinite(numeric) ? Math.max(0, Math.floor(numeric)) : null;
}
function unwrapGpcBalancePayload(payload = {}) {
const data = unwrapGpcResponse(payload);
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return data;
}
const hasBalanceFields = [
'remaining_uses',
'remainingUses',
'balance',
'remaining',
'uses',
'available_uses',
'availableUses',
'auto_mode_enabled',
'autoModeEnabled',
'auto_enabled',
'autoEnabled',
'status',
'card_status',
'cardStatus',
].some((key) => Object.prototype.hasOwnProperty.call(data, key));
if (!hasBalanceFields && data.data && typeof data.data === 'object' && !Array.isArray(data.data)) {
return data.data;
}
return data;
}
function getGpcBalanceRemainingUses(payload = {}) {
const data = unwrapGpcBalancePayload(payload);
if (!data || typeof data !== 'object') {
return null;
}
return normalizeGpcRemainingUses(
data.remaining_uses
?? data.remainingUses
?? data.balance
?? data.remaining
?? data.uses
?? data.available_uses
?? data.availableUses
);
}
function isGpcAutoModeEnabled(payload = {}) {
const data = unwrapGpcBalancePayload(payload);
if (!data || typeof data !== 'object') {
return false;
}
const raw = data.auto_mode_enabled ?? data.autoModeEnabled ?? data.auto_enabled ?? data.autoEnabled;
if (typeof raw === 'boolean') {
return raw;
}
const normalized = String(raw ?? '').trim().toLowerCase();
return normalized === 'true' || normalized === '1' || normalized === 'yes' || normalized === 'enabled';
}
function getGpcApiKeyStatus(payload = {}) {
const data = unwrapGpcBalancePayload(payload);
if (!data || typeof data !== 'object') {
return '';
}
return String(data.status || data.card_status || data.cardStatus || '').trim();
}
function normalizeGpcOtpChannel(value = '') {
const normalized = String(value || '').trim().toLowerCase();
if (normalized === 'sms') {
return 'sms';
}
return 'whatsapp';
}
function normalizeGpcHelperBaseUrl(apiUrl = '') {
let normalized = String(apiUrl || DEFAULT_GPC_HELPER_API_URL).trim();
if (!normalized) {
return DEFAULT_GPC_HELPER_API_URL;
}
normalized = normalized.replace(/\/+$/g, '');
normalized = normalized.replace(/\/api\/checkout\/start$/i, '');
normalized = normalized.replace(/\/api\/gopay\/(?:otp|pin)$/i, '');
normalized = normalized.replace(/\/api\/gp\/tasks(?:\/[^/?#]+)?(?:\/(?:otp|pin|stop))?(?:\?.*)?$/i, '');
normalized = normalized.replace(/\/api\/gp\/balance(?:\?.*)?$/i, '');
normalized = normalized.replace(/\/api\/card\/balance(?:\?.*)?$/i, '');
normalized = normalized.replace(/\/api\/card\/redeem-api-key(?:\?.*)?$/i, '');
try {
const parsed = new URL(normalized);
const hostname = parsed.hostname.toLowerCase();
if (hostname === ALLOWED_GPC_HELPER_REMOTE_HOST || hostname === 'localhost' || hostname === '127.0.0.1') {
return normalized || DEFAULT_GPC_HELPER_API_URL;
}
return DEFAULT_GPC_HELPER_API_URL;
} catch {
return DEFAULT_GPC_HELPER_API_URL;
}
}
function buildGpcHelperApiUrl(apiUrl = '', path = '') {
const baseUrl = normalizeGpcHelperBaseUrl(apiUrl);
if (!baseUrl) {
return '';
}
const normalizedPath = String(path || '').startsWith('/') ? String(path || '') : `/${String(path || '')}`;
return `${baseUrl}${normalizedPath}`;
}
function buildGpcApiKeyBalanceUrl(apiUrl = '') {
return buildGpcHelperApiUrl(apiUrl, '/api/gp/balance');
}
function buildGpcCardBalanceUrl(apiUrl = '') {
return buildGpcApiKeyBalanceUrl(apiUrl);
}
function buildGpcApiKeyHeaders(apiKey = '', extraHeaders = {}) {
const headers = {
...(extraHeaders && typeof extraHeaders === 'object' ? extraHeaders : {}),
};
const normalizedApiKey = String(apiKey || '').trim();
if (normalizedApiKey) {
headers['X-API-Key'] = normalizedApiKey;
}
return headers;
}
function buildGpcTaskCreateUrl(apiUrl = '') {
return buildGpcHelperApiUrl(apiUrl, '/api/gp/tasks');
}
function normalizeGpcTaskId(value = '') {
return String(value || '').trim();
}
function buildGpcTaskQueryUrl(apiUrl = '', taskId = '') {
const normalizedTaskId = normalizeGpcTaskId(taskId);
return buildGpcHelperApiUrl(apiUrl, `/api/gp/tasks/${encodeURIComponent(normalizedTaskId)}`);
}
function buildGpcTaskActionUrl(apiUrl = '', taskId = '', action = '') {
const normalizedTaskId = normalizeGpcTaskId(taskId);
const normalizedAction = String(action || '').trim().replace(/^\/+|\/+$/g, '');
return buildGpcHelperApiUrl(apiUrl, `/api/gp/tasks/${encodeURIComponent(normalizedTaskId)}/${normalizedAction}`);
}
function unwrapGpcResponse(payload = {}) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return payload;
}
const hasUnifiedShape = Object.prototype.hasOwnProperty.call(payload, 'data')
&& (
Object.prototype.hasOwnProperty.call(payload, 'code')
|| Object.prototype.hasOwnProperty.call(payload, 'message')
);
return hasUnifiedShape ? (payload.data ?? {}) : payload;
}
function isGpcUnifiedResponseOk(payload = {}) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return true;
}
if (!Object.prototype.hasOwnProperty.call(payload, 'code')) {
return payload.ok !== false;
}
const code = Number(payload.code);
if (Number.isFinite(code)) {
return code >= 200 && code < 300;
}
return String(payload.code || '').trim() === '200';
}
function formatGpcErrorField(field) {
if (field === undefined || field === null) {
return '';
}
if (typeof field === 'string') {
return field.trim();
}
if (typeof field !== 'object') {
return String(field).trim();
}
const key = Array.isArray(field.loc)
? field.loc.join('.')
: String(field.field || field.path || field.name || field.param || '').trim();
const message = String(field.msg || field.message || field.error || field.detail || field.reason || '').trim();
return [key, message].filter(Boolean).join(': ') || JSON.stringify(field);
}
function extractGpcResponseErrorDetail(payload = {}, status = 0) {
if (!payload || typeof payload !== 'object') {
return status ? `HTTP ${status}` : '未知错误';
}
const payloadText = JSON.stringify(payload).toLowerCase();
if (/account\s+already\s+linked/i.test(payloadText)) {
return 'GOPAY已经绑了订阅,需要手动解绑';
}
const data = payload.data;
if (data && typeof data === 'object' && !Array.isArray(data)) {
const nestedDetail = data.detail ?? data.error ?? data.reason;
if (nestedDetail !== undefined && nestedDetail !== null && String(nestedDetail).trim()) {
const nestedText = String(nestedDetail).trim();
return /account\s+already\s+linked/i.test(nestedText)
? 'GOPAY已经绑了订阅,需要手动解绑'
: nestedText;
}
const fields = data.fields ?? data.errors;
if (Array.isArray(fields) && fields.length > 0) {
const formatted = fields
.map(formatGpcErrorField)
.filter(Boolean)
.join('; ');
if (formatted) {
return formatted;
}
}
}
const direct = payload.detail
?? payload.message
?? payload.error
?? payload.error_description
?? payload.reason;
if (direct !== undefined && direct !== null && String(direct).trim()) {
const directText = String(direct).trim();
return /account\s+already\s+linked/i.test(directText)
? 'GOPAY已经绑了订阅,需要手动解绑'
: directText;
}
const errorMessages = payload.error_messages ?? payload.errorMessages;
if (Array.isArray(errorMessages) && errorMessages.length > 0) {
const firstMessage = String(errorMessages[0] || '').trim();
if (/account\s+already\s+linked/i.test(firstMessage)) {
return 'GOPAY已经绑了订阅,需要手动解绑';
}
if (firstMessage) {
return firstMessage;
}
}
const errors = payload.errors;
if (Array.isArray(errors) && errors.length > 0) {
const first = errors[0];
if (typeof first === 'string') {
return first.trim() || (status ? `HTTP ${status}` : '未知错误');
}
if (first && typeof first === 'object') {
const field = Array.isArray(first.loc) ? first.loc.join('.') : String(first.field || first.path || '').trim();
const message = String(first.msg || first.message || first.error || '').trim();
return [field, message].filter(Boolean).join(': ') || JSON.stringify(first);
}
}
return status ? `HTTP ${status}` : '未知错误';
}
function buildGpcOtpPayload(input = {}) {
const payload = {
reference_id: String(input.reference_id ?? input.referenceId ?? '').trim(),
otp: normalizeGoPayOtp(input.otp ?? input.code ?? ''),
};
const flowId = String(input.flow_id ?? input.flowId ?? '').trim();
const gopayGuid = String(input.gopay_guid ?? input.gopayGuid ?? '').trim();
const redirectUrl = String(input.redirect_url ?? input.redirectUrl ?? '').trim();
if (flowId) payload.flow_id = flowId;
if (gopayGuid) payload.gopay_guid = gopayGuid;
if (redirectUrl) payload.redirect_url = redirectUrl;
return payload;
}
function buildGpcOtpRetryPayload(input = {}) {
const payload = buildGpcOtpPayload(input);
return { ...payload, code: payload.otp };
}
function buildGpcPinPayload(input = {}) {
const payload = {
reference_id: String(input.reference_id ?? input.referenceId ?? '').trim(),
challenge_id: String(input.challenge_id ?? input.challengeId ?? '').trim(),
gopay_guid: String(input.gopay_guid ?? input.gopayGuid ?? '').trim(),
pin: normalizeGoPayPin(input.pin ?? ''),
};
const flowId = String(input.flow_id ?? input.flowId ?? '').trim();
const redirectUrl = String(input.redirect_url ?? input.redirectUrl ?? '').trim();
if (flowId) payload.flow_id = flowId;
if (redirectUrl) payload.redirect_url = redirectUrl;
return payload;
}
function buildGpcPinRetryPayload(input = {}) {
const payload = buildGpcPinPayload(input);
return { ...payload, challengeId: payload.challenge_id };
}
function buildGpcTaskOtpPayload(input = {}) {
return {
otp: normalizeGoPayOtp(input.otp ?? input.code ?? ''),
};
}
function buildGpcTaskPinPayload(input = {}) {
return {
pin: normalizeGoPayPin(input.pin ?? ''),
};
}
function formatGpcBalancePayload(payload = {}) {
const data = unwrapGpcBalancePayload(payload);
if (!data || typeof data !== 'object') {
return '';
}
const candidates = [
data.remaining_uses,
data.remainingUses,
data.balance,
data.remaining,
data.uses,
data.available_uses,
data.availableUses,
];
const firstValue = candidates.find((value) => value !== undefined && value !== null && String(value).trim() !== '');
const totalUses = data.total_uses ?? data.totalUses;
const usedUses = data.used_uses ?? data.usedUses;
const status = String(data.status || data.card_status || data.cardStatus || '').trim();
const flowId = String(data.flow_id || data.flowId || '').trim();
const parts = [];
if (firstValue !== undefined) {
parts.push(totalUses !== undefined && totalUses !== null && String(totalUses).trim() !== ''
? `余额 ${firstValue}/${totalUses}`
: `余额 ${firstValue}`);
}
if (usedUses !== undefined && usedUses !== null && String(usedUses).trim() !== '') {
parts.push(`已用 ${usedUses}`);
}
if (status) {
parts.push(`状态 ${status}`);
}
if (flowId) {
parts.push(`flow_id ${flowId}`);
}
return parts.join(',');
}
return {
DEFAULT_GOPAY_COUNTRY_CODE,
DEFAULT_GPC_HELPER_API_URL,
GPC_HELPER_PHONE_MODE_AUTO,
GPC_HELPER_PHONE_MODE_MANUAL,
PLUS_PAYMENT_METHOD_GPC_HELPER,
PLUS_PAYMENT_METHOD_GOPAY,
PLUS_PAYMENT_METHOD_NONE,
PLUS_PAYMENT_METHOD_PAYPAL,
PLUS_PAYMENT_METHOD_PAYPAL_HOSTED,
buildGpcCardBalanceUrl,
buildGpcApiKeyBalanceUrl,
buildGpcApiKeyHeaders,
buildGpcHelperApiUrl,
buildGpcOtpPayload,
buildGpcOtpRetryPayload,
buildGpcPinPayload,
buildGpcPinRetryPayload,
buildGpcTaskActionUrl,
buildGpcTaskCreateUrl,
buildGpcTaskOtpPayload,
buildGpcTaskPinPayload,
buildGpcTaskQueryUrl,
extractGpcResponseErrorDetail,
formatGpcBalancePayload,
getGpcApiKeyStatus,
getGpcBalanceRemainingUses,
isGpcUnifiedResponseOk,
isGpcAutoModeEnabled,
normalizeGpcHelperBaseUrl,
normalizeGpcHelperPhoneMode,
normalizeGpcRemainingUses,
normalizeGpcTaskId,
normalizeGoPayCountryCode,
normalizeGoPayPhone,
normalizeGoPayPhoneForCountry,
normalizeGoPayOtp,
normalizeGoPayPin,
normalizeGpcOtpChannel,
normalizePlusPaymentMethod,
unwrapGpcBalancePayload,
unwrapGpcResponse,
};
});