wahdx-api 1.0.0 → 1.0.2

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.
package/README.md CHANGED
@@ -25,6 +25,8 @@ ORKUT_TOKEN_AUTH=your_orkut_token_auth
25
25
  ORKUT_USERNAME=your_orkut_username
26
26
  ```
27
27
 
28
+ > **Catatan:** Untuk mendapatkan tokenKey, Anda bisa membelinya di halaman [https://api.wahdx.co](https://api.wahdx.co)
29
+
28
30
  ## Penggunaan
29
31
 
30
32
  ### Contoh Lengkap
@@ -152,10 +154,35 @@ Output jika berhasil:
152
154
  */
153
155
  ```
154
156
 
155
- ## Persyaratan Sistem
157
+ ## FAQ
158
+
159
+ ### Q: Bagaimana cara mendapatkan tokenKey agar bisa menggunakan module ini?
160
+ A: Anda bisa membeli tokenKey di halaman utama [https://api.wahdx.co](https://api.wahdx.co)
161
+
162
+ ### Q: Bagaimana cara mendapatkan kredensial API OrderKuota?
163
+ A: Silahkan kunjungi dokumentasi api [https://api.wahdx.co/api-docs](https://api.wahdx.co/api-docs) untuk mendapatkan token pada akun orderkuota anda.
164
+
165
+ ### Q: Apakah module ini bisa digunakan di project CommonJS?
166
+ A: Ya! Package ini mendukung dual module system (ESM dan CommonJS). Anda bisa menggunakan dengan dua cara:
167
+
168
+ 1. Dengan ES Modules (dalam file .js dengan `type: "module"` di package.json):
169
+ ```javascript
170
+ import QRISPayment from 'wahdx-api';
171
+
172
+ const qrisPayment = new QRISPayment(config);
173
+ // gunakan qrisPayment
174
+ ```
175
+
176
+ 2. Dengan CommonJS (dalam file .cjs atau project tanpa `type: "module"`):
177
+ ```javascript
178
+ const QRISPayment = require('wahdx-api');
179
+
180
+ const qrisPayment = new QRISPayment(config);
181
+ // gunakan qrisPayment
182
+ ```
156
183
 
157
- - Node.js >= 20.18.3
184
+ Package secara otomatis mendeteksi format yang digunakan dan menyediakan versi yang sesuai.
158
185
 
159
186
  ## Lisensi
160
187
 
161
- MIT
188
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,61 @@
1
+ const QRISGenerator = require("./qr-generator.cjs");
2
+ const PaymentChecker = require("./payment-checker.cjs");
3
+ const ReceiptGenerator = require("./receipt-generator.cjs");
4
+
5
+ class QRISPayment {
6
+ constructor(config = {}) {
7
+ this.qrGenerator = new QRISGenerator(config);
8
+ this.paymentChecker = new PaymentChecker(config);
9
+ this.receiptGenerator = new ReceiptGenerator(config);
10
+ }
11
+
12
+ /**
13
+ * Membaca QR code dari file gambar dan mengekstrak baseQrString
14
+ * @param {string} imagePath - Path ke file gambar QR
15
+ * @returns {Promise<string>} - Promise yang menghasilkan baseQrString
16
+ */
17
+ async readQRCode(imagePath) {
18
+ return await this.qrGenerator.readQRFromImage(imagePath);
19
+ }
20
+
21
+ /**
22
+ * Generate QR dengan nominal tertentu
23
+ * @param {number} amount - Nominal pembayaran
24
+ * @returns {Promise<{qrString: string, qrBuffer: Buffer}>}
25
+ */
26
+ async generateQR(amount) {
27
+ const qrString = this.qrGenerator.generateQrString(amount);
28
+ const qrBuffer = await this.qrGenerator.generateQRWithLogo(qrString);
29
+ return {
30
+ qrString,
31
+ qrBuffer
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Membaca QR dari file gambar dan langsung menghasilkan QR baru dengan nominal
37
+ * @param {number} amount - Nominal pembayaran
38
+ * @param {string} qrImagePath - Path ke gambar QR (opsional)
39
+ * @returns {Promise<{qrString: string, qrBuffer: Buffer}>}
40
+ */
41
+ async generateQRFromImage(amount, qrImagePath = null) {
42
+ return await this.qrGenerator.generateQRFromImage(amount, qrImagePath);
43
+ }
44
+
45
+ async checkPayment(reference, amount) {
46
+ const result = await this.paymentChecker.checkPaymentStatus(reference, amount);
47
+ if (result.success && result.data.status === 'PAID') {
48
+ const receipt = await this.receiptGenerator.generateReceipt(result.data);
49
+ result.receipt = receipt;
50
+ }
51
+
52
+ return result;
53
+ }
54
+
55
+ async generateReceipt(transactionData) {
56
+ return await this.receiptGenerator.generateReceipt(transactionData);
57
+ }
58
+ }
59
+
60
+ // Mengekspor kelas utama
61
+ module.exports = QRISPayment;
@@ -1,6 +1,6 @@
1
- import QRISGenerator from './qr-generator.js';
2
- import PaymentChecker from './payment-checker.js';
3
- import ReceiptGenerator from './receipt-generator.js';
1
+ import QRISGenerator from './qr-generator.mjs';
2
+ import PaymentChecker from './payment-checker.mjs';
3
+ import ReceiptGenerator from './receipt-generator.mjs';
4
4
 
5
5
  class QRISPayment {
6
6
  constructor(config = {}) {
@@ -0,0 +1,90 @@
1
+ const axios = require("axios");
2
+
3
+ class PaymentChecker {
4
+ constructor(config) {
5
+ if (!config.tokenKey || !config.auth_username || !config.auth_token) {
6
+ throw new Error('tokenKey, auth_username, dan auth_token harus diisi');
7
+ }
8
+ this.config = {
9
+ tokenKey: config.tokenKey,
10
+ auth_username: config.auth_username,
11
+ auth_token: config.auth_token
12
+ };
13
+ }
14
+
15
+ async checkPaymentStatus(reference, amount) {
16
+ try {
17
+ if (!reference || !amount || amount <= 0) {
18
+ throw new Error('Reference dan amount harus diisi dengan benar');
19
+ }
20
+
21
+ const response = await axios.post(
22
+ 'https://api.wahdx.co/api/mutasi-orkut-v2',
23
+ {
24
+ username_orkut: this.config.auth_username,
25
+ token_orkut: this.config.auth_token
26
+ },
27
+ {
28
+ headers: {
29
+ 'tokenKey': this.config.tokenKey,
30
+ 'Content-Type': 'application/json'
31
+ }
32
+ }
33
+ );
34
+
35
+ if (!response.data || !response.data.status || !response.data.data) {
36
+ throw new Error('Response tidak valid dari server');
37
+ }
38
+
39
+ const transactions = response.data.data;
40
+
41
+ const matchingTransactions = transactions.filter(tx => {
42
+ const txAmount = parseInt(tx.amount);
43
+ const txDate = new Date(tx.date);
44
+ const now = new Date();
45
+ const timeDiff = now - txDate;
46
+
47
+ return txAmount === amount &&
48
+ tx.qris === "static" &&
49
+ tx.type === "CR" &&
50
+ timeDiff <= 5 * 60 * 1000;
51
+ });
52
+
53
+ if (matchingTransactions.length > 0) {
54
+ const latestTransaction = matchingTransactions.reduce((latest, current) => {
55
+ const currentDate = new Date(current.date);
56
+ const latestDate = new Date(latest.date);
57
+ return currentDate > latestDate ? current : latest;
58
+ });
59
+
60
+ return {
61
+ success: true,
62
+ data: {
63
+ status: 'PAID',
64
+ amount: parseInt(latestTransaction.amount),
65
+ reference: latestTransaction.issuer_reff,
66
+ date: latestTransaction.date,
67
+ brand_name: latestTransaction.brand_name,
68
+ buyer_reff: latestTransaction.buyer_reff
69
+ }
70
+ };
71
+ }
72
+
73
+ return {
74
+ success: true,
75
+ data: {
76
+ status: 'UNPAID',
77
+ amount: amount,
78
+ reference: reference
79
+ }
80
+ };
81
+ } catch (error) {
82
+ return {
83
+ success: false,
84
+ error: 'Gagal cek status pembayaran: ' + error.message
85
+ };
86
+ }
87
+ }
88
+ }
89
+
90
+ module.exports = PaymentChecker;
@@ -0,0 +1,199 @@
1
+ const QRCode = require("qrcode");
2
+ const { createCanvas, loadImage } = require("canvas");
3
+ const fs = require("fs");
4
+ const sharp = require("sharp");
5
+ const jsQR = require("jsqr");
6
+ const path = require("path");
7
+ // CJS sudah menyediakan __filename dan __dirname secara otomatis
8
+
9
+ class QRISGenerator {
10
+ constructor(config = {}) {
11
+ this.config = {
12
+ baseQrString: config.baseQrString || '',
13
+ logoPath: config.logoPath || null,
14
+ defaultQrPath: config.defaultQrPath || 'QRIS.png'
15
+ };
16
+ }
17
+
18
+ /**
19
+ * Membaca QR code dari gambar dan mengekstrak baseQrString
20
+ * @param {string} imagePath - Path relatif atau absolut ke file gambar QR
21
+ * @returns {Promise<string>} - Promise yang menghasilkan baseQrString
22
+ */
23
+ async readQRFromImage(imagePath) {
24
+ try {
25
+ // Konversi path relatif ke absolut jika diperlukan
26
+ const absolutePath = path.isAbsolute(imagePath)
27
+ ? imagePath
28
+ : path.resolve(process.cwd(), imagePath);
29
+
30
+ // Periksa apakah file ada
31
+ if (!fs.existsSync(absolutePath)) {
32
+ throw new Error(`File tidak ditemukan: ${absolutePath}`);
33
+ }
34
+
35
+ // Baca gambar menggunakan Sharp
36
+ const image = sharp(absolutePath);
37
+ const metadata = await image.metadata();
38
+ const { width, height } = metadata;
39
+
40
+ // Konversi ke raw pixel data
41
+ const rawData = await image
42
+ .raw()
43
+ .toBuffer();
44
+
45
+ // Format data untuk jsQR
46
+ const imageData = new Uint8ClampedArray(width * height * 4);
47
+
48
+ for (let i = 0; i < rawData.length; i += 3) { // RGB format
49
+ const pixelIndex = (i / 3) * 4; // Convert RGB index to RGBA index
50
+ imageData[pixelIndex] = rawData[i]; // R
51
+ imageData[pixelIndex + 1] = rawData[i + 1]; // G
52
+ imageData[pixelIndex + 2] = rawData[i + 2]; // B
53
+ imageData[pixelIndex + 3] = 255; // A (full opacity)
54
+ }
55
+
56
+ // Dekode QR code menggunakan jsQR
57
+ const code = jsQR(imageData, width, height);
58
+
59
+ if (code) {
60
+ // Simpan baseQrString yang dibaca ke config
61
+ this.config.baseQrString = code.data;
62
+ return code.data;
63
+ } else {
64
+ throw new Error('QR code tidak terdeteksi dalam gambar');
65
+ }
66
+ } catch (error) {
67
+ console.error('Error saat membaca QR code:', error);
68
+ throw error;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Membaca QR code dari file default (biasanya QRIS.png)
74
+ * @returns {Promise<string>} - Promise yang menghasilkan baseQrString
75
+ */
76
+ async readDefaultQR() {
77
+ try {
78
+ // Path default ke file QRIS.png
79
+ const defaultPath = path.resolve(process.cwd(), this.config.defaultQrPath);
80
+ return await this.readQRFromImage(defaultPath);
81
+ } catch (error) {
82
+ console.error(`Error saat membaca gambar default (${this.config.defaultQrPath}):`, error);
83
+ throw error;
84
+ }
85
+ }
86
+
87
+ async generateQRWithLogo(qrString) {
88
+ try {
89
+ if (!qrString) {
90
+ throw new Error('qrString tidak boleh kosong');
91
+ }
92
+ const canvas = createCanvas(500, 500);
93
+ const ctx = canvas.getContext('2d');
94
+ await QRCode.toCanvas(canvas, qrString, {
95
+ errorCorrectionLevel: 'H',
96
+ margin: 2,
97
+ width: 500,
98
+ color: {
99
+ dark: '#000000',
100
+ light: '#ffffff'
101
+ }
102
+ });
103
+ if (this.config.logoPath && fs.existsSync(this.config.logoPath)) {
104
+ const logo = await loadImage(this.config.logoPath);
105
+ const logoSize = canvas.width * 0.2;
106
+ const logoPosition = (canvas.width - logoSize) / 2;
107
+
108
+ ctx.fillStyle = '#FFFFFF';
109
+ ctx.fillRect(logoPosition - 5, logoPosition - 5, logoSize + 10, logoSize + 10);
110
+ ctx.drawImage(logo, logoPosition, logoPosition, logoSize, logoSize);
111
+ }
112
+ return canvas.toBuffer('image/png');
113
+ } catch (error) {
114
+ throw new Error('Gagal generate QR: ' + error.message);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Membaca QR dari file kemudian generate QR baru dengan nominal
120
+ * @param {number} amount - Nominal pembayaran
121
+ * @param {string} qrImagePath - Path ke gambar QR (opsional)
122
+ * @returns {Promise<{qrString: string, qrBuffer: Buffer}>}
123
+ */
124
+ async generateQRFromImage(amount, qrImagePath = null) {
125
+ try {
126
+ // Jika path gambar disediakan, baca dari path tersebut
127
+ if (qrImagePath) {
128
+ await this.readQRFromImage(qrImagePath);
129
+ }
130
+ // Jika tidak ada path dan baseQrString kosong, gunakan default
131
+ else if (!this.config.baseQrString) {
132
+ await this.readDefaultQR();
133
+ }
134
+
135
+ // Generate QR string dengan nominal
136
+ const qrString = this.generateQrString(amount);
137
+
138
+ // Generate QR image
139
+ const qrBuffer = await this.generateQRWithLogo(qrString);
140
+
141
+ return {
142
+ qrString,
143
+ qrBuffer
144
+ };
145
+ } catch (error) {
146
+ throw new Error('Gagal generate QR dari gambar: ' + error.message);
147
+ }
148
+ }
149
+
150
+ generateQrString(amount) {
151
+ try {
152
+ if (!amount || amount <= 0) {
153
+ throw new Error('Nominal harus lebih besar dari 0');
154
+ }
155
+
156
+ if (!this.config.baseQrString) {
157
+ throw new Error('BaseQrString tidak tersedia. Gunakan readQRFromImage terlebih dahulu atau berikan baseQrString pada config.');
158
+ }
159
+
160
+ if (!this.config.baseQrString.includes("5802ID")) {
161
+ throw new Error("Format QRIS tidak valid");
162
+ }
163
+
164
+ const finalAmount = Math.floor(amount);
165
+ const qrisBase = this.config.baseQrString.slice(0, -4).replace("010211", "010212");
166
+ const nominalStr = finalAmount.toString();
167
+ const nominalTag = `54${nominalStr.length.toString().padStart(2, '0')}${nominalStr}`;
168
+ const insertPosition = qrisBase.indexOf("5802ID");
169
+ const qrisWithNominal = qrisBase.slice(0, insertPosition) + nominalTag + qrisBase.slice(insertPosition);
170
+ const checksum = this.calculateCRC16(qrisWithNominal);
171
+
172
+ return qrisWithNominal + checksum;
173
+ } catch (error) {
174
+ throw new Error('Gagal generate string QRIS: ' + error.message);
175
+ }
176
+ }
177
+
178
+ calculateCRC16(str) {
179
+ try {
180
+ if (!str) {
181
+ throw new Error('String tidak boleh kosong');
182
+ }
183
+
184
+ let crc = 0xFFFF;
185
+ for (let i = 0; i < str.length; i++) {
186
+ crc ^= str.charCodeAt(i) << 8;
187
+ for (let j = 0; j < 8; j++) {
188
+ crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1);
189
+ }
190
+ crc &= 0xFFFF;
191
+ }
192
+ return crc.toString(16).toUpperCase().padStart(4, '0');
193
+ } catch (error) {
194
+ throw new Error('Gagal kalkulasi CRC16: ' + error.message);
195
+ }
196
+ }
197
+ }
198
+
199
+ module.exports = QRISGenerator;
@@ -0,0 +1,130 @@
1
+ const PDFDocument = require("pdfkit");
2
+ const fs = require("fs");
3
+ const moment = require("moment");
4
+ const path = require("path");
5
+
6
+ class ReceiptGenerator {
7
+ constructor(config) {
8
+ this.config = config;
9
+ }
10
+
11
+ async generateReceipt(transactionData) {
12
+ return new Promise((resolve, reject) => {
13
+ try {
14
+ const doc = new PDFDocument({
15
+ size: [300, 450],
16
+ margin: 20,
17
+ layout: 'portrait'
18
+ });
19
+
20
+ const fileName = `receipt_${transactionData.reference}_${Date.now()}.pdf`;
21
+ const filePath = `receipts/${fileName}`;
22
+ if (!fs.existsSync('receipts')) {
23
+ fs.mkdirSync('receipts');
24
+ }
25
+ const writeStream = fs.createWriteStream(filePath);
26
+ doc.pipe(writeStream);
27
+
28
+ if (this.config.logoPath && fs.existsSync(this.config.logoPath)) {
29
+ const logoWidth = 40;
30
+ const logoHeight = 40;
31
+ const logoX = 20 + (260 - logoWidth) / 2;
32
+ const logoY = 10;
33
+ doc.image(this.config.logoPath, logoX, logoY, { width: logoWidth, height: logoHeight });
34
+ doc.y = logoY + logoHeight + 4;
35
+ } else {
36
+ doc.moveDown(0.5);
37
+ }
38
+
39
+ doc.fontSize(14)
40
+ .fillColor('black')
41
+ .font('Helvetica-Bold');
42
+ const headerText = 'QRIS PAYMENT RECEIPT';
43
+ const headerWidth = doc.widthOfString(headerText);
44
+ doc.text(headerText, 20 + (260 - headerWidth) / 2, doc.y, { width: headerWidth });
45
+
46
+ doc.fontSize(9)
47
+ .font('Helvetica');
48
+ const merchantText = this.config.storeName || 'STORE NAME';
49
+ const merchantWidth = doc.widthOfString(merchantText);
50
+ doc.text(merchantText, 20 + (260 - merchantWidth) / 2, doc.y, { width: merchantWidth });
51
+
52
+ doc.moveDown(0.3);
53
+ const lineY = doc.y;
54
+ doc.moveTo(20, lineY)
55
+ .lineTo(280, lineY)
56
+ .strokeColor('#888').stroke();
57
+
58
+ doc.moveDown(0.5);
59
+ doc.fontSize(9)
60
+ .font('Helvetica-Bold');
61
+ const detailsTitle = 'TRANSACTION DETAILS';
62
+ const detailsTitleWidth = doc.widthOfString(detailsTitle);
63
+ doc.text(detailsTitle, 20 + (260 - detailsTitleWidth) / 2, doc.y, { width: detailsTitleWidth });
64
+ doc.moveDown(0.2);
65
+
66
+ const formattedDate = moment(transactionData.date).format('DD/MM/YYYY HH:mm:ss');
67
+ const details = [
68
+ ['Reference', transactionData.reference],
69
+ ['Date', formattedDate],
70
+ ['Amount', `Rp ${transactionData.amount.toLocaleString('id-ID')}`],
71
+ ['Status', transactionData.status],
72
+ ['Payment Method', transactionData.brand_name || '-'],
73
+ ['Buyer Reference', transactionData.buyer_reff || '-']
74
+ ];
75
+
76
+ const tableWidth = 240;
77
+ const startX = (300 - tableWidth) / 2;
78
+ const labelWidth = 100;
79
+ const valueWidth = 130;
80
+ let y = doc.y + 5;
81
+
82
+ details.forEach(([label, value], idx) => {
83
+ doc.font('Helvetica-Bold')
84
+ .fontSize(9)
85
+ .fillColor('black')
86
+ .text(label, startX, y, { width: labelWidth, align: 'left' });
87
+ doc.font('Helvetica')
88
+ .fontSize(9)
89
+ .fillColor('black')
90
+ .text(value, startX + labelWidth, y, { width: valueWidth, align: 'right' });
91
+
92
+ y += 14;
93
+ doc.moveTo(startX, y)
94
+ .lineTo(startX + labelWidth + valueWidth, y)
95
+ .strokeColor('#e0e0e0').stroke();
96
+ y += 2;
97
+ });
98
+
99
+ y += 6;
100
+ doc.moveTo(20, y)
101
+ .lineTo(280, y)
102
+ .strokeColor('#888').stroke();
103
+
104
+ y += 12;
105
+ doc.text('Thank you for your payment!', 0, y, { align: 'right', width: 260 });
106
+ y += 12;
107
+ doc.text(`Receipt No: ${transactionData.reference}`, 0, y, { align: 'right', width: 260 });
108
+
109
+ doc.end();
110
+
111
+ writeStream.on('finish', () => {
112
+ resolve({
113
+ success: true,
114
+ filePath: filePath,
115
+ fileName: fileName
116
+ });
117
+ });
118
+
119
+ writeStream.on('error', (error) => {
120
+ reject(error);
121
+ });
122
+
123
+ } catch (error) {
124
+ reject(error);
125
+ }
126
+ });
127
+ }
128
+ }
129
+
130
+ module.exports = ReceiptGenerator;
package/package.json CHANGED
@@ -1,8 +1,15 @@
1
1
  {
2
2
  "name": "wahdx-api",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Package untuk generate QRIS dan cek payment status secara realtime dengan API OrderKuota dari https://api.wahdx.co",
5
- "main": "dist/index.js",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.mjs",
7
+ "exports": {
8
+ ".": {
9
+ "require": "./dist/index.cjs",
10
+ "import": "./dist/index.mjs"
11
+ }
12
+ },
6
13
  "author": "wahdalo",
7
14
  "license": "MIT",
8
15
  "type": "module",
@@ -17,7 +24,8 @@
17
24
  ],
18
25
  "scripts": {
19
26
  "test": "node tes.js",
20
- "start": "node dist/index.js",
27
+ "test:cjs": "node tes-cjs.cjs",
28
+ "start": "node dist/index.mjs",
21
29
  "build": "node scripts/build.js",
22
30
  "prepublishOnly": "npm run build",
23
31
  "pack": "npm pack --dry-run"
File without changes