n8n-nodes-zalo-custom 1.0.0

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.
@@ -0,0 +1,579 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.ZaloLoginByQr = void 0;
40
+ const n8n_workflow_1 = require("n8n-workflow");
41
+ const zca_js_1 = require("zca-js");
42
+ const path = __importStar(require("path"));
43
+ const zalo_helper_1 = require("../utils/zalo.helper");
44
+ const crypto_helper_1 = require("../utils/crypto.helper");
45
+ const axios_1 = __importDefault(require("axios"));
46
+
47
+ class ZaloLoginByQr {
48
+ constructor() {
49
+ this.description = {
50
+ displayName: 'Zalo Login By QR',
51
+ name: 'zaloLoginByQr',
52
+ group: ['Zalo'],
53
+ version: 1,
54
+ description: 'Đăng nhập Zalo bằng QR code và lưu thông tin vào Credential',
55
+ defaults: {
56
+ name: 'Zalo Login QR',
57
+ },
58
+ inputs: ['main'],
59
+ outputs: ['main'],
60
+ icon: 'file:../shared/zalo.svg',
61
+ credentials: [
62
+ {
63
+ name: 'n8nZaloApi',
64
+ required: true,
65
+ displayName: 'n8n Account Credential',
66
+ description: 'Get "n8n API" from settings then create: "n8n Zalo API Credential"\n',
67
+ },
68
+ ],
69
+ properties: [
70
+ {
71
+ displayName: 'Proxy',
72
+ name: 'proxy',
73
+ type: 'string',
74
+ default: '',
75
+ placeholder: 'https://user:pass@host:port',
76
+ description: 'HTTP proxy to use for Zalo API requests',
77
+ },
78
+ // {
79
+ // displayName: 'Delete Zalo Credential Duplicate UserId',
80
+ // name: 'deleteOldZaloApi',
81
+ // type: 'boolean',
82
+ // default: false,
83
+ // description: 'Delete old zalo credential if exists',
84
+ // },
85
+ {
86
+ displayName: 'Notifications to Telegram',
87
+ name: 'sendToTelegram',
88
+ type: 'boolean',
89
+ default: false,
90
+ description: 'Whether to send QR code and status updates to a Telegram chat',
91
+ },
92
+ {
93
+ displayName: 'Bot Token',
94
+ name: 'telegramToken',
95
+ type: 'string',
96
+ required: true,
97
+ default: '',
98
+ displayOptions: {
99
+ show: { sendToTelegram: [true] },
100
+ },
101
+ description: 'The token for your Telegram bot',
102
+ },
103
+ {
104
+ displayName: 'Chat ID',
105
+ name: 'telegramChatId',
106
+ type: 'string',
107
+ required: true,
108
+ default: '',
109
+ displayOptions: {
110
+ show: { sendToTelegram: [true] },
111
+ },
112
+ description: 'Telegram chat_id to send notifications to',
113
+ },
114
+ ],
115
+ };
116
+ }
117
+ async execute() {
118
+ const returnData = [];
119
+ let proxy = this.getNodeParameter('proxy', 0, '');
120
+ if (proxy && !proxy.toLowerCase().startsWith('http')) {
121
+ this.logger.warn(`Proxy không hợp lệ: "${proxy}"`);
122
+ proxy = '';
123
+ }
124
+ const timeout = 30;
125
+ const fileName = 'zalo-qr-code.png';
126
+ const deleteOldZaloApi = this.getNodeParameter('deleteOldZaloApi', 0, false); // bỏ vì xoá xong gây ra lỗi k lưu được
127
+ const sendToTelegram = this.getNodeParameter('sendToTelegram', 0, false);
128
+ const telegramToken = this.getNodeParameter('telegramToken', 0, '');
129
+ const telegramChatId = this.getNodeParameter('telegramChatId', 0, '');
130
+
131
+ const telegramOptions = {
132
+ token: telegramToken,
133
+ chatId: telegramChatId,
134
+ logger: this.logger,
135
+ };
136
+ let n8nCredential;
137
+ try {
138
+ n8nCredential = await this.getCredentials('n8nZaloApi');
139
+ }
140
+ catch (error) {
141
+ }
142
+ const selectedCredential = n8nCredential;
143
+ if (selectedCredential) {
144
+ this.logger.info('Using n8n account credential');
145
+ }
146
+ else {
147
+ this.logger.info('No credentials provided, will generate QR code for login');
148
+ }
149
+ try {
150
+ const zaloOptions = {
151
+ selfListen: true,
152
+ logging: true,
153
+ };
154
+ if (proxy) {
155
+ zaloOptions.proxy = proxy;
156
+ }
157
+ let zalo;
158
+ if (selectedCredential) {
159
+ this.logger.info('Using existing Zalo credentials');
160
+ zalo = new zca_js_1.Zalo(zaloOptions);
161
+ this.logger.info('Using n8n credential to get Zalo credentials');
162
+ const n8nApiKey = selectedCredential.apiKey;
163
+ const n8nUrl = selectedCredential.url || 'http://localhost:5678';
164
+ this.logger.info(`Using n8n API at ${n8nUrl} with API key ${n8nApiKey ? 'provided' : 'not provided'}`);
165
+ this.logger.info('n8n credential support is not fully implemented yet. Will use QR code login.');
166
+ zalo = new zca_js_1.Zalo(zaloOptions);
167
+ }
168
+ else {
169
+ zalo = new zca_js_1.Zalo(zaloOptions);
170
+ }
171
+ this.logger.info('Starting Zalo QR login process...');
172
+ let userDisplayName = '';
173
+ let userAvatar = '';
174
+ let userImei = '';
175
+ let userUserAgent = '';
176
+ let userZaloUserId = '';
177
+ let createdCredentialId = '';
178
+ const processContext = (context) => {
179
+ if (!context) {
180
+ this.logger.warn('Context is null or undefined');
181
+ return;
182
+ }
183
+ const cookie = context.cookie || '';
184
+ const imei = context.imei || '';
185
+ const userAgent = context.userAgent || '';
186
+ const zaloUserId = context.userId || context.zaloUserId || '';
187
+ userImei = imei;
188
+ userUserAgent = userAgent;
189
+ userZaloUserId = zaloUserId;
190
+ this.logger.info('=== ZALO CREDENTIALS ===');
191
+ this.logger.info(`Cookie: ${cookie ? `Received (length: ${typeof cookie === 'string' ? cookie.length : (Array.isArray(cookie) ? cookie.length : 'unknown')})` : 'None'}`);
192
+ this.logger.info(`IMEI: ${imei ? imei : 'None'}`);
193
+ this.logger.info(`User Agent: ${userAgent ? userAgent : 'None'}`);
194
+ this.logger.info(`Zalo User ID: ${zaloUserId ? zaloUserId : 'None'}`);
195
+ this.logger.info('=== END CREDENTIALS ===');
196
+ };
197
+ const setupEventListeners = (api) => {
198
+ this.logger.info('Setting up event listeners to get credentials');
199
+ try {
200
+ if (typeof api.getContext === 'function') {
201
+ const contextResult = api.getContext();
202
+ if (contextResult && typeof contextResult.then === 'function') {
203
+ contextResult.then((context) => {
204
+ processContext(context);
205
+ }).catch((error) => {
206
+ this.logger.error(`Error getting context: ${error.message}`);
207
+ });
208
+ }
209
+ else {
210
+ processContext(contextResult);
211
+ }
212
+ }
213
+ else {
214
+ this.logger.warn('getContext is not a function');
215
+ if (api.context) {
216
+ this.logger.info('Found context in api object');
217
+ processContext(api.context);
218
+ }
219
+ else {
220
+ this.logger.warn('No context found in api object');
221
+ }
222
+ }
223
+ }
224
+ catch (error) {
225
+ this.logger.error(`Error in setupEventListeners: ${error.message}`);
226
+ }
227
+ };
228
+ const qrCodePromise = new Promise(async (resolve, reject) => {
229
+ let isResolved = false;
230
+ let api = null;
231
+ const timeoutId = setTimeout(() => {
232
+ if (!isResolved) {
233
+ isResolved = true;
234
+ const timeoutError = new n8n_workflow_1.NodeOperationError(this.getNode(), 'Timeout generating QR code. Please try again or check your Zalo connection.');
235
+ if (sendToTelegram) {
236
+ (0, zalo_helper_1.sendToTelegram)({
237
+ ...telegramOptions,
238
+ text: `❌ Đã hết thời gian chờ tạo mã QR Zalo. Vui lòng thử lại.`,
239
+ }).catch(e => this.logger.error(`Không thể gửi thông báo timeout đến Telegram: ${e.message}`));
240
+ }
241
+ reject(timeoutError);
242
+ }
243
+ }, timeout * 1000);
244
+ try {
245
+ api = await zalo.loginQR(null, (qrEvent) => {
246
+ var _a, _b, _c;
247
+ this.logger.info(`Received QR event type: ${qrEvent ? qrEvent.type : 'no event'}`);
248
+ switch (qrEvent.type) {
249
+ case 0:
250
+ if ((_a = qrEvent === null || qrEvent === void 0 ? void 0 : qrEvent.data) === null || _a === void 0 ? void 0 : _a.image) {
251
+ const qrCodeBase64 = qrEvent.data.image;
252
+ this.logger.info(`QR code generated, length: ${qrCodeBase64.length}`);
253
+ if (isResolved)
254
+ return;
255
+ clearTimeout(timeoutId);
256
+ if (qrCodeBase64) {
257
+ isResolved = true;
258
+ resolve(qrCodeBase64);
259
+ }
260
+ }
261
+ else {
262
+ console.log('Could not get QR code from Zalo SDK');
263
+ reject(new Error("Could not get QR code"));
264
+ }
265
+ break;
266
+ case 1:
267
+ if (sendToTelegram) {
268
+ (0, zalo_helper_1.sendToTelegram)({
269
+ ...telegramOptions,
270
+ text: `❌ Đã hết thời gian chờ tạo mã QR Zalo. Vui lòng thử lại.`,
271
+ }).catch(e => this.logger.error(`Không thể gửi thông báo timeout đến Telegram: ${e.message}`));
272
+ }
273
+ this.logger.warn('QR code expired. Please try again.');
274
+ break; // This event often precedes a timeout error, so a log is sufficient.
275
+ case 2:
276
+ this.logger.info('=== QR CODE SCANNED ===');
277
+ if (qrEvent === null || qrEvent === void 0 ? void 0 : qrEvent.data) {
278
+ userDisplayName = qrEvent.data.display_name || '';
279
+ userAvatar = qrEvent.data.avatar || '';
280
+ this.logger.info(`User: ${userDisplayName}`);
281
+ this.logger.info(`Avatar: ${userAvatar ? 'Yes' : 'No'}`);
282
+ }
283
+ break;
284
+ case 3:
285
+ this.logger.warn('=== QR CODE DECLINED ===');
286
+ if ((_b = qrEvent === null || qrEvent === void 0 ? void 0 : qrEvent.data) === null || _b === void 0 ? void 0 : _b.code) {
287
+ this.logger.warn(`Decline code: ${qrEvent.data.code}`);
288
+ if (sendToTelegram) {
289
+ (0, zalo_helper_1.sendToTelegram)({
290
+ ...telegramOptions,
291
+ text: `⚠️ Người dùng đã từ chối đăng nhập Zalo.`,
292
+ }).catch(e => this.logger.error(`Không thể gửi thông báo từ chối đến Telegram: ${e.message}`));
293
+ }
294
+ }
295
+ break;
296
+ case 4:
297
+ this.logger.info('=== GOT LOGIN INFO ===');
298
+ if (qrEvent === null || qrEvent === void 0 ? void 0 : qrEvent.data) {
299
+ const cookie = qrEvent.data.cookie || [];
300
+ const imei = qrEvent.data.imei || '';
301
+ const userAgent = qrEvent.data.userAgent || '';
302
+ const displayName = userDisplayName;
303
+ const avatar = userAvatar;
304
+
305
+ if (sendToTelegram) {
306
+ (0, zalo_helper_1.sendToTelegram)({
307
+ ...telegramOptions,
308
+ text: `${displayName}: đã xác nhận, tiến hành lưu trữ...`,
309
+ }).catch(e => this.logger.error(`Không thể gửi thông báo đăng nhập thành công đến Telegram: ${e.message}`));
310
+ }
311
+ if (cookie && cookie.length > 0 && imei && userAgent) {
312
+ // Use an async IIFE to handle the async login and subsequent actions
313
+ (async () => {
314
+ try {
315
+ this.logger.info('Login trực tiếp để lấy UID...');
316
+ const loginApi = await new zca_js_1.Zalo().login({ cookie, imei, userAgent });
317
+ const newInfo = await loginApi.fetchAccountInfo();
318
+ if (newInfo && newInfo.profile && newInfo.profile.userId) {
319
+ userZaloUserId = newInfo.profile.userId;
320
+ const rawPhoneNumber = newInfo.profile.phoneNumber || '';
321
+ const zaloPhoneNumber = rawPhoneNumber.startsWith('+84')
322
+ ? '0' + rawPhoneNumber.substring(3)
323
+ : rawPhoneNumber;
324
+ this.logger.info(`UID: ${userZaloUserId} - Phone: ${zaloPhoneNumber}`);
325
+
326
+ const now = new Date();
327
+ const time = now.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
328
+ const date = now.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit' }); // year: '2-digit'
329
+ const credentialName = `${zaloPhoneNumber} _ ${displayName} _ ${time} ${date}`;
330
+
331
+ const credentialData = {
332
+ cookie: JSON.stringify(cookie),
333
+ imei: imei,
334
+ userAgent: userAgent,
335
+ proxy: proxy || '',
336
+ nameAccount: displayName,
337
+ userId: userZaloUserId,
338
+ phoneNumber: zaloPhoneNumber,
339
+ telegramToken: telegramToken,
340
+ telegramChatId: telegramChatId,
341
+ supportCode: '',
342
+ licenseKey: ''
343
+ };
344
+ try {
345
+ this.logger.info('Attempting to create Zalo credential via n8n API');
346
+ const credentialApiData = {
347
+ name: credentialName,
348
+ type: 'zaloApi',
349
+ nodesAccess: [],
350
+ data: credentialData
351
+ };
352
+ const ports = [5678];
353
+ const createCredentialOnPort = async (port) => {
354
+ const n8nApi = await this.getCredentials('n8nZaloApi');
355
+ const n8nApiUrl = n8nApi.url;
356
+ const fullApiUrl = `${n8nApiUrl}/api/v1/credentials`;
357
+ const n8nApiKey = n8nApi.apiKey;
358
+ this.logger.info(`Trying to create credential via n8n API at ${fullApiUrl}`);
359
+ try {
360
+ const response = await axios_1.default.post(fullApiUrl, credentialApiData, {
361
+ headers: {
362
+ 'Content-Type': 'application/json',
363
+ 'X-N8N-API-KEY': n8nApiKey
364
+ },
365
+ });
366
+ this.logger.info('Credential created successfully via n8n API');
367
+ if (response.data && response.data.id) {
368
+ this.logger.info(`Credential ID: ${response.data.id}`);
369
+ createdCredentialId = response.data.id;
370
+ let text_telegram = '';
371
+ try {
372
+ if (userZaloUserId && userZaloUserId !== 'unknown') {
373
+ const encryptionKey = userZaloUserId.repeat(3);
374
+ const sessionDataToEncrypt = { cookie, imei, userAgent };
375
+ const encryptedData = (0, crypto_helper_1.encrypt)(sessionDataToEncrypt, encryptionKey);
376
+ const sessionDetails = {
377
+ userId: userZaloUserId,
378
+ name: displayName,
379
+ phone: zaloPhoneNumber,
380
+ credentialId: createdCredentialId,
381
+ encryptedData: encryptedData,
382
+ };
383
+ const { oldCredentialId } = await (0, zalo_helper_1.saveOrUpdateSession)(sessionDetails);
384
+ this.logger.info(`Session for user ID "${userZaloUserId}" has been securely saved/updated in the database.`);
385
+ text_telegram += '\n- Lưu thông tin đăng nhập';
386
+ // Xoá nếu hiện có sẵn ID cũ
387
+ if (oldCredentialId) {
388
+ text_telegram += `\n- Hãy xoá crendentialId cũ: ${oldCredentialId}`;
389
+ }
390
+ if (deleteOldZaloApi && oldCredentialId) {
391
+ this.logger.info(`[Delete] Found old credential ID "${oldCredentialId}" for user "${userZaloUserId}". Attempting to delete.`);
392
+ const deleteUrl = `${n8nApiUrl}/api/v1/credentials/${oldCredentialId}`;
393
+ await axios_1.default.delete(deleteUrl, {
394
+ headers: { 'X-N8N-API-KEY': n8nApiKey },
395
+ }).then(() => {
396
+ this.logger.info(`[Delete] Successfully deleted old credential with ID: ${oldCredentialId}`);
397
+ text_telegram += `\n- Xoá credential cũ: ${oldCredentialId}`;
398
+ }).catch(deleteError => {
399
+ if (deleteError.response && deleteError.response.status === 404) {
400
+ this.logger.warn(`[Delete] Old credential not found on n8n (404). It might have been deleted already.`);
401
+ } else {
402
+ this.logger.error(`[Delete] Failed to delete old credential: ${deleteError.message}`);
403
+ }
404
+ });
405
+ }
406
+ }
407
+ else {
408
+ this.logger.warn(`Skipping session save because userZaloUserId is invalid: "${userZaloUserId}"`);
409
+ }
410
+ }
411
+ catch (fileError) {
412
+ this.logger.error(`Failed to save session to database: ${fileError.message}`);
413
+ }
414
+
415
+ if (sendToTelegram) {
416
+ (0, zalo_helper_1.sendToTelegram)({
417
+ ...telegramOptions,
418
+ text: `✅ Đăng nhập thành công\n- ${displayName}: ${zaloPhoneNumber}${text_telegram}`,
419
+ }).catch(e => this.logger.error(`Không thể gửi thông báo đăng nhập thành công đến Telegram: ${e.message}`));
420
+ }
421
+ }
422
+ return true;
423
+ }
424
+ catch (apiError) {
425
+ this.logger.error(`Error creating credential on port ${port}: ${apiError.message}`);
426
+ if (apiError.response) {
427
+ this.logger.error(`API Error Status: ${apiError.response.status}`);
428
+ this.logger.error(`API Error Data: ${JSON.stringify(apiError.response.data)}`);
429
+ }
430
+ return false;
431
+ }
432
+ };
433
+ let credentialCreated = false;
434
+ for (const port of ports) {
435
+ try {
436
+ const result = await createCredentialOnPort.call(this, port);
437
+ if (result) {
438
+ credentialCreated = true;
439
+ break;
440
+ }
441
+ }
442
+ catch (error) {
443
+ this.logger.error(`Error trying port ${port}: ${error.message}`);
444
+ }
445
+ }
446
+ if (!credentialCreated) {
447
+ this.logger.warn('Could not create credential via n8n API on any port.');
448
+ this.logger.info('Credential info saved to file. You can create it manually using:');
449
+ this.logger.info('node auto-create-zalo-credential.js');
450
+ }
451
+ }
452
+ catch (error) {
453
+ this.logger.error(`Error creating credential: ${error.message}`);
454
+ this.logger.info('Credential info saved to file. You can create it manually using:');
455
+ this.logger.info('node auto-create-zalo-credential.js');
456
+ }
457
+ } // End of if (newInfo...)
458
+ else {
459
+ userZaloUserId = 'unknown';
460
+ this.logger.warn('Login successful but could not get UID from fetchAccountInfo.');
461
+ }
462
+ }
463
+ catch (error) {
464
+ this.logger.warn(`Login error: ${error.message}`);
465
+ userZaloUserId = 'unknown';
466
+ }
467
+ })();
468
+ }
469
+ else {
470
+ userZaloUserId = 'unknown';
471
+ }
472
+ }
473
+ break;
474
+ default:
475
+ this.logger.warn(`Unknown QR event type: ${qrEvent.type}`);
476
+ break;
477
+ }
478
+ });
479
+ this.logger.info('Starting Zalo listener');
480
+ api.listener.start();
481
+ api.listener.onConnected(() => {
482
+ this.logger.info("=== ZALO SDK CONNECTED ===");
483
+ setupEventListeners(api);
484
+ });
485
+ api.listener.onError((error) => {
486
+ this.logger.error("=== ZALO ERROR ===", error);
487
+ });
488
+ this.logger.info('All event listeners set up');
489
+ }
490
+ catch (error) {
491
+ clearTimeout(timeoutId);
492
+ if (!isResolved) {
493
+ isResolved = true;
494
+ reject(error);
495
+ }
496
+ }
497
+ });
498
+ const qrCodeBase64 = await qrCodePromise;
499
+ const binaryData = Buffer.from(qrCodeBase64, 'base64');
500
+ if (sendToTelegram) {
501
+ await (0, zalo_helper_1.sendToTelegram)({
502
+ ...telegramOptions,
503
+ binaryData: binaryData,
504
+ fileName: fileName,
505
+ caption: 'Vui lòng quét mã QR này bằng ứng dụng Zalo để đăng nhập. Mã có hiệu lực trong khoảng 45 giây.',
506
+ });
507
+ }
508
+ const newItem = {
509
+ json: {
510
+ success: true,
511
+ state: '',
512
+ message: selectedCredential
513
+ ? 'Using n8n account credential. QR code generated successfully.'
514
+ : 'QR code generated successfully. Scan with Zalo app to login.',
515
+ fileName,
516
+ usingExistingCredential: !!selectedCredential,
517
+ credentialType: selectedCredential ? 'n8nZaloApi' : null,
518
+ userInfo: {
519
+ displayName: userDisplayName || 'Not available yet - scan QR code first',
520
+ avatar: userAvatar || 'Not available yet - scan QR code first'
521
+ },
522
+ zaloApiInfo: {
523
+ imei: userImei || 'Not available yet',
524
+ userAgent: userUserAgent || 'Not available yet',
525
+ zaloUserId: userZaloUserId || 'Not available yet'
526
+ },
527
+ webhook: {
528
+ enabled: false
529
+ },
530
+ binary: {
531
+ data: await this.helpers.prepareBinaryData(binaryData, fileName, 'image/png'),
532
+ }
533
+ },
534
+ binary: {
535
+ data: await this.helpers.prepareBinaryData(binaryData, fileName, 'image/png'),
536
+ },
537
+ };
538
+ returnData.push(newItem);
539
+ if (returnData[0] && returnData[0].json) {
540
+ if (!selectedCredential) {
541
+ returnData[0].json.credentialInstructions = 'Credentials have been saved to file. Credentials will be created automatically if n8n API credentials are provided.';
542
+ returnData[0].json.credentialFilePath = path.join(process.cwd(), 'output', 'zalo-credentials.json');
543
+ returnData[0].json.autoCreateScript = 'node auto-create-zalo-credential.js';
544
+ returnData[0].json.autoCreateApi = 'Credentials will be created automatically via n8n API if n8n API credentials are provided.';
545
+ if (createdCredentialId) {
546
+ returnData[0].json.createdCredentialId = createdCredentialId;
547
+ returnData[0].json.credentialCreationStatus = 'success';
548
+ }
549
+ }
550
+ else if (selectedCredential) {
551
+ returnData[0].json.credentialInstructions = 'Using n8n account credential. New Zalo credentials will be created automatically after successful login.';
552
+ returnData[0].json.credentialName = selectedCredential.name || 'Unknown';
553
+ returnData[0].json.credentialId = selectedCredential.id || 'Unknown';
554
+ returnData[0].json.credentialType = 'n8nZaloApi';
555
+ returnData[0].json.autoCreateApi = 'Credentials will be created automatically via n8n API after successful login.';
556
+ if (createdCredentialId) {
557
+ returnData[0].json.createdCredentialId = createdCredentialId;
558
+ returnData[0].json.credentialCreationStatus = 'success';
559
+ }
560
+ }
561
+ }
562
+ return [returnData];
563
+ }
564
+ catch (error) {
565
+ if (this.continueOnFail()) {
566
+ const executionData = this.helpers.constructExecutionMetaData(this.helpers.returnJsonArray({
567
+ error: error.message,
568
+ state: '',
569
+ success: false
570
+ }), { itemData: { item: 0 } });
571
+ return [executionData];
572
+ }
573
+ else {
574
+ throw error;
575
+ }
576
+ }
577
+ }
578
+ }
579
+ exports.ZaloLoginByQr = ZaloLoginByQr;