@dev-crowagent/veripay-upi 0.0.0-stage → 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 veripay-upi contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,438 @@
1
- # Temporary Holding Version
1
+ # veripay-upi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Check whether a UPI payment actually arrived, by reading payment receipts from a Gmail inbox over IMAP.
4
+
5
+ Instead of asking a payer to copy a UTR by hand, match the payment by its exact amount (for example ₹25.01), by a 12-digit UPI reference, or by a transaction ID. A database is optional: without one it is a plain verifier, with one it also blocks the same payment from being counted twice.
6
+
7
+ Receipts from FamPay, Google Pay, PhonePe, Paytm, BHIM and any other app that sends a confirmation email all work, because matching is done on wording patterns rather than fixed templates.
8
+
9
+ Three ways to use it:
10
+
11
+ | Way | Folder | Best for |
12
+ |---|---|---|
13
+ | Node.js library | `src/` | bots, Express or Next.js server code, CLI tools |
14
+ | Python SDK | `sdk/` | Python bots, scripts, Django or FastAPI backends |
15
+ | HTTP API on Vercel | `api/` | any language, webhooks, frontends, no Node or Python code needed |
16
+
17
+ ## What you get
18
+
19
+ - Amount matching for fresh inbox mail with a 15 minute window
20
+ - UTR and transaction ID extraction from the email body
21
+ - QR code and `upi://pay` link generation for the amount you want to collect
22
+ - Optional duplicate protection through an `api_logs` table
23
+ - Works with no database, with Supabase, or with your own storage
24
+ - Zero framework lock-in: plain Node, plain Python, plain HTTP
25
+
26
+ ## Before you start
27
+
28
+ You need a Gmail address and a 16-character **Gmail App Password**: Google Account → Security → 2-Step Verification → App passwords. A normal Gmail password will not work over IMAP.
29
+
30
+ ## Node.js
31
+
32
+ ```bash
33
+ npm install @dev-crowagent/veripay-upi
34
+ ```
35
+
36
+ ### Demo without a database
37
+
38
+ Nothing to configure except the inbox. Keep in mind that without storage the same UTR can be verified again, because nothing remembers earlier checks.
39
+
40
+ ```javascript
41
+ import { VeriPayUPI } from '@dev-crowagent/veripay-upi';
42
+
43
+ const verifier = new VeriPayUPI({
44
+ gmail: process.env.GMAIL,
45
+ gmailAppPassword: process.env.GMAIL_APP_PASSWORD
46
+ });
47
+
48
+ const qr = await verifier.generateQr({
49
+ upiId: 'yourname@fam',
50
+ amount: 25.01,
51
+ name: 'Demo Store'
52
+ });
53
+
54
+ console.log('pay here:', qr.upi_uri);
55
+
56
+ const result = await verifier.verifyPayment({ amount: 25.01 });
57
+
58
+ if (result.verified) {
59
+ console.log('paid by', result.sender_name, 'utr', result.utr);
60
+ } else {
61
+ console.log('not paid yet:', result.details);
62
+ }
63
+ ```
64
+
65
+ `qr_image` is a base64 data URL, ready for `<img src={qr.qr_image} />` or for sending inside a bot message.
66
+
67
+ ### Demo with Supabase
68
+
69
+ Same code plus two credentials. Now each finished check is written to `api_logs`, and a UTR that was already accepted comes back with `"Transaction already verified"`.
70
+
71
+ ```javascript
72
+ import { VeriPayUPI } from '@dev-crowagent/veripay-upi';
73
+
74
+ const verifier = new VeriPayUPI({
75
+ gmail: process.env.GMAIL,
76
+ gmailAppPassword: process.env.GMAIL_APP_PASSWORD,
77
+ supabaseUrl: process.env.SUPABASE_URL,
78
+ supabaseServiceRoleKey: process.env.SUPABASE_SERVICE_ROLE_KEY
79
+ });
80
+
81
+ const first = await verifier.verifyPayment({
82
+ amount: 25.01,
83
+ utr: '412345678901',
84
+ userId: 'order-1001'
85
+ });
86
+
87
+ console.log(first.verified, first.sender_name);
88
+
89
+ const second = await verifier.verifyPayment({
90
+ amount: 25.01,
91
+ utr: '412345678901',
92
+ userId: 'order-1001'
93
+ });
94
+
95
+ console.log(second.verified, second.message);
96
+ ```
97
+
98
+ Table creation steps are in [Database setup](#database-setup-optional).
99
+
100
+ ### Node API
101
+
102
+ `new VeriPayUPI(config)`
103
+
104
+ | Field | Type | Required | Meaning |
105
+ |---|---|---|---|
106
+ | `gmail` | `string` | yes | Inbox to read |
107
+ | `gmailAppPassword` | `string` | yes | Gmail App Password, spaces allowed |
108
+ | `supabaseUrl` | `string` | no | Project URL for logging |
109
+ | `supabaseServiceRoleKey` | `string` | no | Service role key for logging |
110
+
111
+ `generateQr(params)` takes `upiId`, `amount`, `name` and an optional `userId`. Returns `qr_image`, `upi_uri`, `upi_id`, `amount`, `name`, `created_at_ist`.
112
+
113
+ `verifyPayment(params)` takes `amount` plus an optional `utr` or `txnid`, and an optional `userId`.
114
+
115
+ | Result field | Meaning |
116
+ |---|---|
117
+ | `verified` | `true` when a matching receipt was found |
118
+ | `amount` | The amount you asked about |
119
+ | `utr` | Reference pulled from the email, if any |
120
+ | `transaction_id` | Transaction ID or UTR |
121
+ | `sender_name` | Payer name read from the receipt |
122
+ | `payment_time_ist` | Receipt time in IST |
123
+ | `message` / `details` | Reason when nothing matched or the inbox could not be read |
124
+
125
+ Read failures come back as `verified: false` with a message instead of throwing. Missing parameters do throw.
126
+
127
+ ## Python SDK
128
+
129
+ Requirements: Python 3.9 or newer. Only dependency is `segno`, which draws the QR images.
130
+
131
+ ```bash
132
+ pip install veripay-upi
133
+ ```
134
+
135
+ Installing from a clone of this repository also works: run `pip install ./sdk` from the repo root.
136
+
137
+ ### Demo without a database
138
+
139
+ ```python
140
+ import os
141
+
142
+ from veripay_upi import VeriPayUPI
143
+
144
+ verifier = VeriPayUPI(
145
+ gmail=os.environ["GMAIL"],
146
+ gmail_app_password=os.environ["GMAIL_APP_PASSWORD"],
147
+ )
148
+
149
+ qr = verifier.generate_qr(upi_id="yourname@fam", amount="25.01", name="Demo Store")
150
+ print("pay here:", qr["upi_uri"])
151
+
152
+ result = verifier.verify_payment(amount="25.01")
153
+
154
+ if result["verified"]:
155
+ print("paid by", result["sender_name"], "utr", result["utr"])
156
+ else:
157
+ print("not paid yet:", result["details"])
158
+ ```
159
+
160
+ Reference based checks skip the 15 minute window:
161
+
162
+ ```python
163
+ result = verifier.verify_payment(amount="25.01", utr="412345678901")
164
+ result = verifier.verify_payment(amount="25.01", txnid="C1234567890")
165
+ ```
166
+
167
+ ### Demo with a database
168
+
169
+ Two extra arguments turn on logging and duplicate protection.
170
+
171
+ ```python
172
+ import os
173
+
174
+ from veripay_upi import VeriPayUPI
175
+
176
+ verifier = VeriPayUPI(
177
+ gmail=os.environ["GMAIL"],
178
+ gmail_app_password=os.environ["GMAIL_APP_PASSWORD"],
179
+ supabase_url=os.environ["SUPABASE_URL"],
180
+ supabase_service_role_key=os.environ["SUPABASE_SERVICE_ROLE_KEY"],
181
+ )
182
+
183
+ first = verifier.verify_payment(amount="25.01", utr="412345678901", user_id="order-1001")
184
+ print(first["verified"], first.get("sender_name"))
185
+
186
+ second = verifier.verify_payment(amount="25.01", utr="412345678901", user_id="order-1001")
187
+ print(second["verified"], second["message"])
188
+ ```
189
+
190
+ Create the table first, otherwise the checks fail: this SDK does not create it for you.
191
+
192
+ ### API mode
193
+
194
+ Use the deployed API instead of talking to Gmail from your machine. Nothing about the inbox lives in your app.
195
+
196
+ ```python
197
+ from veripay_upi import VeriPayClient
198
+
199
+ client = VeriPayClient("https://your-deployment.vercel.app", api_key="your-api-key")
200
+
201
+ print(client.health())
202
+ print(client.generate_qr(upi_id="yourname@fam", amount="25.01", name="Demo Store")["upi_uri"])
203
+ print(client.verify_payment(amount="25.01", utr="412345678901"))
204
+ ```
205
+
206
+ Leave `api_key` out when the deployment has no `API_KEY` environment variable.
207
+
208
+ ### Python API
209
+
210
+ `VeriPayUPI(gmail, gmail_app_password, supabase_url=None, supabase_service_role_key=None)`
211
+
212
+ | Method | Arguments | Returns |
213
+ |---|---|---|
214
+ | `generate_qr` | `upi_id`, `amount`, `name`, optional `user_id` | dict with `qr_image`, `upi_uri`, `upi_id`, `amount`, `name`, `created_at_ist` |
215
+ | `verify_payment` | `amount`, optional `utr`, optional `txnid`, optional `user_id` | dict with `verified`, `amount`, `utr`, `transaction_id`, `sender_name`, `payment_time_ist`, and `message` / `details` on failure |
216
+
217
+ `VeriPayClient(base_url, api_key=None, timeout=30)`
218
+
219
+ | Method | Arguments | Returns |
220
+ |---|---|---|
221
+ | `health` | none | dict with `ok`, `gmail_configured`, `supabase_configured`, `auth_required` |
222
+ | `generate_qr` | `upi_id`, `amount`, `name` | same dict as the library |
223
+ | `verify_payment` | `amount`, optional `utr`, optional `txnid` | same dict as the library |
224
+
225
+ `VeriPayError` is raised for missing parameters. Inbox or network problems come back inside the result, and `VeriPayClient` raises `VeriPayClientError` for non-200 responses.
226
+
227
+ ### Telegram bot example
228
+
229
+ `examples/telegram_bot/` is a ready-to-run bot built on this package: `/qr 25.50 Chai` sends a payment QR image and `/verify 25.50` checks Gmail for the matching payment. Its README lists the environment variables it needs.
230
+
231
+ ## HTTP API
232
+
233
+ The `api/` folder is a Python serverless API for Vercel, built on the same core as the SDK.
234
+
235
+ ### Deploy
236
+
237
+ 1. Import this repository on Vercel.
238
+ 2. Keep the **Root Directory** at the repository root, so `vercel.json` and `requirements.txt` are picked up.
239
+ 3. Add the environment variables listed below.
240
+ 4. Deploy. Functions appear at `/api/health`, `/api/qr` and `/api/verify`.
241
+
242
+ `vercel.json` bundles the `sdk/` folder with the functions, and `requirements.txt` installs `segno`.
243
+
244
+ ### Environment variables
245
+
246
+ | Name | Required | Used for |
247
+ |---|---|---|
248
+ | `GMAIL` | for `/api/verify` | inbox that receives payment receipts |
249
+ | `GMAIL_APP_PASSWORD` | for `/api/verify` | Gmail App Password |
250
+ | `SUPABASE_URL` | no | logging and duplicate protection |
251
+ | `SUPABASE_SERVICE_ROLE_KEY` | no | Supabase write access |
252
+ | `API_KEY` | no | when set, POST requests must send `x-api-key` |
253
+
254
+ Without the two Supabase values the API still verifies payments, it just keeps no history. Add them and redeploy to enable duplicate protection.
255
+
256
+ ### Endpoints
257
+
258
+ `GET /api/health`
259
+
260
+ ```bash
261
+ curl https://your-deployment.vercel.app/api/health
262
+ ```
263
+
264
+ ```json
265
+ { "ok": true, "gmail_configured": true, "supabase_configured": false, "auth_required": true }
266
+ ```
267
+
268
+ `POST /api/qr`
269
+
270
+ ```bash
271
+ curl -X POST https://your-deployment.vercel.app/api/qr \
272
+ -H 'content-type: application/json' \
273
+ -H 'x-api-key: your-api-key' \
274
+ -d '{"upi_id":"yourname@fam","amount":"25.01","name":"Demo Store"}'
275
+ ```
276
+
277
+ ```json
278
+ {
279
+ "qr_image": "data:image/png;base64,...",
280
+ "upi_uri": "upi://pay?pa=yourname@fam&pn=Demo%20Store&am=25.01&cu=INR",
281
+ "upi_id": "yourname@fam",
282
+ "amount": "25.01",
283
+ "name": "Demo Store",
284
+ "created_at_ist": "05/12/2026, 04:10:00 PM"
285
+ }
286
+ ```
287
+
288
+ `POST /api/verify`
289
+
290
+ ```bash
291
+ curl -X POST https://your-deployment.vercel.app/api/verify \
292
+ -H 'content-type: application/json' \
293
+ -H 'x-api-key: your-api-key' \
294
+ -d '{"amount":"25.01","utr":"412345678901"}'
295
+ ```
296
+
297
+ Found payment:
298
+
299
+ ```json
300
+ {
301
+ "verified": true,
302
+ "transaction_id": "412345678901",
303
+ "amount": 25.01,
304
+ "utr": "412345678901",
305
+ "sender_name": "Rahul Sharma",
306
+ "payment_time_ist": "05/12/2026, 04:08:12 PM"
307
+ }
308
+ ```
309
+
310
+ Nothing matched:
311
+
312
+ ```json
313
+ {
314
+ "verified": false,
315
+ "message": "Transaction not found",
316
+ "details": "No matching payment found in email inbox"
317
+ }
318
+ ```
319
+
320
+ Status codes:
321
+
322
+ | Code | When |
323
+ |---|---|
324
+ | `200` | request handled, check the `verified` field for the outcome |
325
+ | `400` | body is not a JSON object, or a required field is missing |
326
+ | `401` | `API_KEY` is set and `x-api-key` does not match |
327
+ | `500` | unexpected server error, message in `error` |
328
+
329
+ ## Database setup (optional)
330
+
331
+ Everything here is optional. It is what makes duplicate protection and history possible.
332
+
333
+ ### 1. Create a Supabase project
334
+
335
+ Sign up on supabase.com, create a project and wait for it to finish provisioning. The free tier is enough; idle projects pause after a while and wake on the next request.
336
+
337
+ ### 2. Create the table
338
+
339
+ Run this in the SQL editor:
340
+
341
+ ```sql
342
+ create table api_logs (
343
+ id bigint generated by default as identity primary key,
344
+ user_id text,
345
+ endpoint text,
346
+ status int,
347
+ utr text,
348
+ txn_id text,
349
+ amount numeric,
350
+ created_at timestamptz default now()
351
+ );
352
+ ```
353
+
354
+ The names matter: the code writes `endpoint`, `status`, `utr`, `txn_id`, `amount` and `user_id`.
355
+
356
+ ### 3. Copy two values
357
+
358
+ Project Settings → API gives you the **Project URL** and the **service_role** key. Use service_role, not anon: the anon key has no write access. The service role key bypasses row level security, so it belongs on the server only, never in a browser or a mobile app.
359
+
360
+ ### 4. Pass them in
361
+
362
+ | Where | How |
363
+ |---|---|
364
+ | Node | `supabaseUrl` and `supabaseServiceRoleKey` in the constructor |
365
+ | Python | `supabase_url` and `supabase_service_role_key` arguments |
366
+ | Vercel | `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` environment variables, then redeploy |
367
+
368
+ ### 5. Check it works
369
+
370
+ `GET /api/health` should report `"supabase_configured": true`. Then run one check and look at the table:
371
+
372
+ ```sql
373
+ select endpoint, status, utr, txn_id, amount, created_at
374
+ from api_logs
375
+ order by id desc
376
+ limit 10;
377
+ ```
378
+
379
+ ### What gets stored
380
+
381
+ | Column | Meaning |
382
+ |---|---|
383
+ | `user_id` | whatever you pass as `userId` / `user_id`, for grouping by order or customer |
384
+ | `endpoint` | `generate_qr` or `verify_payment` |
385
+ | `status` | `200` found, `400` bad request, `401` bad credentials, `404` nothing matched, `500` other failure |
386
+ | `utr` / `txn_id` | reference read from the receipt or sent by you |
387
+ | `amount` | amount that was checked |
388
+
389
+ Any check with status `200` marks a reference as used. A later check with the same reference is skipped, which is what stops a replay.
390
+
391
+ ### Optional: block races with a unique index
392
+
393
+ The check-then-write order means two simultaneous requests for the same UTR could both pass. A partial unique index closes that gap:
394
+
395
+ ```sql
396
+ create unique index if not exists api_logs_paid_utr
397
+ on api_logs (utr) where status = 200 and utr is not null;
398
+
399
+ create unique index if not exists api_logs_paid_txn
400
+ on api_logs (txn_id) where status = 200 and txn_id is not null;
401
+ ```
402
+
403
+ With these in place the losing request errors instead of silently accepting a second time. Failure rows (`404`, `500`) are untouched because the index only covers status `200`.
404
+
405
+ ### Using your own database
406
+
407
+ Supabase is just Postgres. To use Postgres, MySQL, MongoDB or Redis instead, keep the same table and column names in a small helper of your own, or replace `write_log` / `already_stored` in `sdk/veripay_upi/core.py` and their Node counterparts in `src/index.ts`.
408
+
409
+ ## How matching works
410
+
411
+ 1. IMAP search for the reference number, or for the amount as text.
412
+ 2. Each message is parsed and subject plus body are checked for credit wording: `received`, `credited`, `added`.
413
+ 3. The amount must match exactly a number tagged with `Rs.`, `INR`, `₹`, an `Amount` / `Amt` label, or written with two decimals. A ₹1 credit never satisfies a ₹3 check, and ₹13 never satisfies ₹1.
414
+ 4. UTR and transaction ID are extracted from the body.
415
+ 5. With logging on, a reference already stored with status `200` is skipped.
416
+
417
+ Without a reference, only mail from the last 15 minutes is considered. With a reference, the window is skipped and only that reference is searched.
418
+
419
+ ## Limits worth knowing
420
+
421
+ - Gmail IMAP must stay enabled on the account; Workspace admins can switch it off.
422
+ - Receipt layouts differ between apps, so wording and reference formats are matched by pattern, not by strict templates.
423
+ - Amount matching assumes a unique paise value per order, which is why `25.01` beats a round `25`.
424
+ - Without a database the same payment can be verified again; that is the only thing the database adds.
425
+ - Payment gateway callbacks and refunds are out of scope.
426
+
427
+ ## Development
428
+
429
+ ```bash
430
+ npm install
431
+ npm run build
432
+ ```
433
+
434
+ The build compiles `src/index.ts` into `dist/`, which is what the npm package and `examples/test.js` use. Python code is plain source in `sdk/` and `api/`, with no build step.
435
+
436
+ ## License
437
+
438
+ MIT.
@@ -0,0 +1,51 @@
1
+ export interface VeriPayConfig {
2
+ supabaseUrl?: string;
3
+ supabaseServiceRoleKey?: string;
4
+ gmail: string;
5
+ gmailAppPassword: string;
6
+ }
7
+ export interface GenerateQrParams {
8
+ upiId: string;
9
+ amount: number | string;
10
+ name: string;
11
+ userId?: string;
12
+ }
13
+ export interface VerifyPaymentParams {
14
+ amount: number | string;
15
+ utr?: string;
16
+ txnid?: string;
17
+ userId?: string;
18
+ }
19
+ export interface QrResult {
20
+ qr_image: string;
21
+ upi_uri: string;
22
+ upi_id: string;
23
+ amount: string;
24
+ name: string;
25
+ created_at_ist: string;
26
+ }
27
+ export interface VerificationResult {
28
+ verified: boolean;
29
+ transaction_id?: string;
30
+ amount?: number;
31
+ utr?: string | null;
32
+ sender_name?: string;
33
+ payment_time_ist?: string;
34
+ message?: string;
35
+ details?: string;
36
+ }
37
+ export declare class VeriPayUPI {
38
+ private readonly account;
39
+ private readonly passphrase;
40
+ private readonly store;
41
+ constructor(config: VeriPayConfig);
42
+ generateQr(params: GenerateQrParams): Promise<QrResult>;
43
+ verifyPayment(params: VerifyPaymentParams): Promise<VerificationResult>;
44
+ private paymentUri;
45
+ private senderName;
46
+ private utrOf;
47
+ private txnOf;
48
+ private alreadyStored;
49
+ private writeFailure;
50
+ private write;
51
+ }
package/dist/index.js ADDED
@@ -0,0 +1,217 @@
1
+ import { createClient } from '@supabase/supabase-js';
2
+ import imapSimple from 'imap-simple';
3
+ import { simpleParser } from 'mailparser';
4
+ import QRCode from 'qrcode';
5
+ const MAIL_HOST = 'imap.gmail.com';
6
+ const MAIL_PORT = 993;
7
+ const FRESH_WINDOW_MS = 15 * 60 * 1000;
8
+ const CREDIT_WORDS = ['received', 'credited', 'added'];
9
+ const UNKNOWN_SENDER = 'UPI User';
10
+ const SEARCH_SHAPE = { bodies: ['', 'HEADER', 'TEXT'], markSeen: false };
11
+ const NO_MATCH = {
12
+ verified: false,
13
+ message: 'Transaction not found',
14
+ details: 'No matching payment found in email inbox'
15
+ };
16
+ function istStamp(when) {
17
+ const moment = when ?? new Date();
18
+ return moment.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' });
19
+ }
20
+ const CURRENCY_AMOUNT = /(?:rs\.?|inr|₹)\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/gi;
21
+ const LABELED_AMOUNT = /(?:amount|amt)\s*[:\-]?\s*(?:rs\.?|inr|₹)?\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/gi;
22
+ const PLAIN_AMOUNT = /(?<![\d.])([0-9][0-9,]*\.[0-9]{2})(?![\d])/g;
23
+ function amountsIn(text) {
24
+ const values = [];
25
+ for (const pattern of [CURRENCY_AMOUNT, LABELED_AMOUNT, PLAIN_AMOUNT]) {
26
+ pattern.lastIndex = 0;
27
+ for (const hit of text.matchAll(pattern)) {
28
+ const value = Number(hit[1].replace(/,/g, ''));
29
+ if (Number.isFinite(value))
30
+ values.push(Math.round(value * 100) / 100);
31
+ }
32
+ }
33
+ return values;
34
+ }
35
+ function amountMatches(text, expected) {
36
+ const target = Math.round(expected * 100) / 100;
37
+ return amountsIn(text).some((value) => value === target);
38
+ }
39
+ export class VeriPayUPI {
40
+ constructor(config) {
41
+ if (!config.gmail || !config.gmailAppPassword) {
42
+ throw new Error('Gmail credentials (gmail and app password) are required.');
43
+ }
44
+ this.account = config.gmail.includes('@') ? config.gmail : `${config.gmail}@gmail.com`;
45
+ this.passphrase = config.gmailAppPassword.replace(/\s/g, '');
46
+ this.store =
47
+ config.supabaseUrl && config.supabaseServiceRoleKey
48
+ ? createClient(config.supabaseUrl, config.supabaseServiceRoleKey)
49
+ : null;
50
+ }
51
+ async generateQr(params) {
52
+ const { upiId, amount, name, userId = null } = params;
53
+ if (!upiId || !amount || !name) {
54
+ await this.write({ endpoint: 'generate_qr', status: 400, amount: amount ? Number(amount) : null, userId });
55
+ throw new Error('Missing parameters (upiId, amount, and name are required)');
56
+ }
57
+ try {
58
+ const uri = this.paymentUri(upiId, name, amount);
59
+ const image = await QRCode.toDataURL(uri, { margin: 2, width: 400 });
60
+ await this.write({ endpoint: 'generate_qr', status: 200, amount: Number(amount), userId });
61
+ return {
62
+ qr_image: image,
63
+ upi_uri: uri,
64
+ upi_id: upiId,
65
+ amount: String(amount),
66
+ name,
67
+ created_at_ist: istStamp()
68
+ };
69
+ }
70
+ catch (failure) {
71
+ await this.write({ endpoint: 'generate_qr', status: 500, amount: Number(amount), userId });
72
+ throw new Error(`Failed to generate QR code: ${failure?.message ?? failure}`);
73
+ }
74
+ }
75
+ async verifyPayment(params) {
76
+ const { amount, utr, txnid, userId = null } = params;
77
+ if (!amount) {
78
+ throw new Error('Amount is required for verification.');
79
+ }
80
+ const expected = Number(amount);
81
+ const reference = utr || txnid;
82
+ const referenceColumn = utr ? 'utr' : 'txn_id';
83
+ if (reference && (await this.alreadyStored(referenceColumn, reference))) {
84
+ return {
85
+ verified: false,
86
+ message: 'Transaction already verified',
87
+ details: 'This UTR / Txn ID has already been used.'
88
+ };
89
+ }
90
+ let session = null;
91
+ try {
92
+ session = await imapSimple.connect({
93
+ imap: {
94
+ user: this.account,
95
+ password: this.passphrase,
96
+ host: MAIL_HOST,
97
+ port: MAIL_PORT,
98
+ tls: true,
99
+ tlsOptions: { rejectUnauthorized: false },
100
+ authTimeout: 10000
101
+ }
102
+ });
103
+ await session.openBox('INBOX');
104
+ const mailbox = await session.search([['TEXT', reference || String(amount)]], SEARCH_SHAPE);
105
+ if (mailbox.length === 0) {
106
+ session.end();
107
+ await this.writeFailure(userId, 404, expected, utr, txnid);
108
+ return { ...NO_MATCH };
109
+ }
110
+ for (const message of mailbox) {
111
+ const rawPart = message.parts.find((part) => part.which === '');
112
+ if (!rawPart?.body)
113
+ continue;
114
+ const mail = await simpleParser(rawPart.body);
115
+ const body = mail.text ?? '';
116
+ const flat = `${mail.subject ?? ''}\n${body}`.toLowerCase();
117
+ const looksCredited = CREDIT_WORDS.some((word) => flat.includes(word));
118
+ if (!looksCredited)
119
+ continue;
120
+ if (!reference && mail.date && Date.now() - mail.date.getTime() > FRESH_WINDOW_MS)
121
+ continue;
122
+ const amountSeen = amountMatches(flat, expected);
123
+ if (!amountSeen)
124
+ continue;
125
+ const sender = this.senderName(body);
126
+ const foundUtr = utr ?? this.utrOf(body);
127
+ const foundTxn = txnid ?? this.txnOf(body);
128
+ const fingerprint = foundUtr || foundTxn;
129
+ if (fingerprint && (await this.alreadyStored(foundUtr ? 'utr' : 'txn_id', fingerprint)))
130
+ continue;
131
+ await this.write({
132
+ endpoint: 'verify_payment',
133
+ status: 200,
134
+ amount: expected,
135
+ userId,
136
+ utr: foundUtr,
137
+ txnId: foundTxn
138
+ });
139
+ session.end();
140
+ return {
141
+ verified: true,
142
+ transaction_id: foundTxn || foundUtr || undefined,
143
+ amount: expected,
144
+ utr: foundUtr,
145
+ sender_name: sender,
146
+ payment_time_ist: istStamp(mail.date ?? undefined)
147
+ };
148
+ }
149
+ session.end();
150
+ await this.writeFailure(userId, 404, expected, utr, txnid);
151
+ return { ...NO_MATCH };
152
+ }
153
+ catch (failure) {
154
+ if (session)
155
+ session.end();
156
+ const reason = String(failure?.message ?? failure);
157
+ const rejected = /authenticationfailed|invalid credentials|auth/i.test(reason);
158
+ await this.writeFailure(userId, rejected ? 401 : 500, expected, utr, txnid);
159
+ return {
160
+ verified: false,
161
+ message: rejected ? 'Invalid Gmail credentials' : 'Error during check',
162
+ details: reason
163
+ };
164
+ }
165
+ }
166
+ paymentUri(upiId, payee, amount) {
167
+ const params = [`pa=${upiId}`, `pn=${encodeURIComponent(payee)}`, `am=${encodeURIComponent(String(amount))}`, 'cu=INR'];
168
+ return `upi://pay?${params.join('&')}`;
169
+ }
170
+ senderName(body) {
171
+ const hit = body.match(/(?:from|received from|sender)\s+([a-zA-Z ]{3,30})/i);
172
+ if (!hit?.[1])
173
+ return UNKNOWN_SENDER;
174
+ const name = hit[1].trim();
175
+ return name.toLowerCase().endsWith('at') ? name.slice(0, -3).trim() : name;
176
+ }
177
+ utrOf(body) {
178
+ const hit = body.match(/(?:utr|upi ref no|ref no|reference no)\s*:\s*([0-9]{12})/i);
179
+ return hit?.[1]?.trim() ?? null;
180
+ }
181
+ txnOf(body) {
182
+ const hit = body.match(/(?:transaction id|txn id)\s*:\s*([a-zA-Z0-9]+)/i);
183
+ return hit?.[1]?.trim() ?? null;
184
+ }
185
+ async alreadyStored(column, value) {
186
+ if (!this.store)
187
+ return false;
188
+ const { data } = await this.store
189
+ .from('api_logs')
190
+ .select('id')
191
+ .eq('status', 200)
192
+ .eq(column, value);
193
+ return Array.isArray(data) && data.length > 0;
194
+ }
195
+ async writeFailure(userId, status, amount, utr, txnid) {
196
+ await this.write({
197
+ endpoint: 'verify_payment',
198
+ status,
199
+ amount,
200
+ userId,
201
+ utr: utr ?? null,
202
+ txnId: txnid ?? null
203
+ });
204
+ }
205
+ async write(entry) {
206
+ if (!this.store)
207
+ return;
208
+ await this.store.from('api_logs').insert({
209
+ user_id: entry.userId ?? null,
210
+ endpoint: entry.endpoint,
211
+ status: entry.status,
212
+ utr: entry.utr ?? null,
213
+ txn_id: entry.txnId ?? null,
214
+ amount: entry.amount
215
+ });
216
+ }
217
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@dev-crowagent/veripay-upi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Verify UPI payments automatically from a Gmail inbox over IMAP — amount or UTR matching, QR generation and duplicate protection.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "module",
8
+ "scripts": {
9
+ "build": "node node_modules/typescript/lib/tsc.js",
10
+ "prepublishOnly": "npm run build"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "keywords": [
16
+ "upi",
17
+ "payment-verification",
18
+ "qr-code",
19
+ "gmail",
20
+ "imap",
21
+ "india",
22
+ "payments",
23
+ "node"
24
+ ],
25
+ "license": "MIT",
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "overrides": {
32
+ "semver": "^7.5.4"
33
+ },
34
+ "dependencies": {
35
+ "@supabase/supabase-js": "^2.43.4",
36
+ "imap-simple": "^5.1.0",
37
+ "mailparser": "^3.7.1",
38
+ "qrcode": "^1.5.3"
39
+ },
40
+ "devDependencies": {
41
+ "@types/imap-simple": "^4.2.8",
42
+ "@types/mailparser": "^3.4.4",
43
+ "@types/node": "^20.14.2",
44
+ "@types/qrcode": "^1.5.5",
45
+ "typescript": "^5.2.2"
46
+ }
47
+ }