@dev-crowagent/veripay-upi 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +431 -2
- package/dist/index.d.ts +51 -0
- package/dist/index.js +201 -0
- package/package.json +45 -4
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,432 @@
|
|
|
1
|
-
#
|
|
1
|
+
# veripay-upi
|
|
2
2
|
|
|
3
|
-
|
|
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 ./sdk
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Demo without a database
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
import os
|
|
139
|
+
|
|
140
|
+
from veripay_upi import VeriPayUPI
|
|
141
|
+
|
|
142
|
+
verifier = VeriPayUPI(
|
|
143
|
+
gmail=os.environ["GMAIL"],
|
|
144
|
+
gmail_app_password=os.environ["GMAIL_APP_PASSWORD"],
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
qr = verifier.generate_qr(upi_id="yourname@fam", amount="25.01", name="Demo Store")
|
|
148
|
+
print("pay here:", qr["upi_uri"])
|
|
149
|
+
|
|
150
|
+
result = verifier.verify_payment(amount="25.01")
|
|
151
|
+
|
|
152
|
+
if result["verified"]:
|
|
153
|
+
print("paid by", result["sender_name"], "utr", result["utr"])
|
|
154
|
+
else:
|
|
155
|
+
print("not paid yet:", result["details"])
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Reference based checks skip the 15 minute window:
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
result = verifier.verify_payment(amount="25.01", utr="412345678901")
|
|
162
|
+
result = verifier.verify_payment(amount="25.01", txnid="C1234567890")
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Demo with a database
|
|
166
|
+
|
|
167
|
+
Two extra arguments turn on logging and duplicate protection.
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
import os
|
|
171
|
+
|
|
172
|
+
from veripay_upi import VeriPayUPI
|
|
173
|
+
|
|
174
|
+
verifier = VeriPayUPI(
|
|
175
|
+
gmail=os.environ["GMAIL"],
|
|
176
|
+
gmail_app_password=os.environ["GMAIL_APP_PASSWORD"],
|
|
177
|
+
supabase_url=os.environ["SUPABASE_URL"],
|
|
178
|
+
supabase_service_role_key=os.environ["SUPABASE_SERVICE_ROLE_KEY"],
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
first = verifier.verify_payment(amount="25.01", utr="412345678901", user_id="order-1001")
|
|
182
|
+
print(first["verified"], first.get("sender_name"))
|
|
183
|
+
|
|
184
|
+
second = verifier.verify_payment(amount="25.01", utr="412345678901", user_id="order-1001")
|
|
185
|
+
print(second["verified"], second["message"])
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Create the table first, otherwise the checks fail: this SDK does not create it for you.
|
|
189
|
+
|
|
190
|
+
### API mode
|
|
191
|
+
|
|
192
|
+
Use the deployed API instead of talking to Gmail from your machine. Nothing about the inbox lives in your app.
|
|
193
|
+
|
|
194
|
+
```python
|
|
195
|
+
from veripay_upi import VeriPayClient
|
|
196
|
+
|
|
197
|
+
client = VeriPayClient("https://your-deployment.vercel.app", api_key="your-api-key")
|
|
198
|
+
|
|
199
|
+
print(client.health())
|
|
200
|
+
print(client.generate_qr(upi_id="yourname@fam", amount="25.01", name="Demo Store")["upi_uri"])
|
|
201
|
+
print(client.verify_payment(amount="25.01", utr="412345678901"))
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Leave `api_key` out when the deployment has no `API_KEY` environment variable.
|
|
205
|
+
|
|
206
|
+
### Python API
|
|
207
|
+
|
|
208
|
+
`VeriPayUPI(gmail, gmail_app_password, supabase_url=None, supabase_service_role_key=None)`
|
|
209
|
+
|
|
210
|
+
| Method | Arguments | Returns |
|
|
211
|
+
|---|---|---|
|
|
212
|
+
| `generate_qr` | `upi_id`, `amount`, `name`, optional `user_id` | dict with `qr_image`, `upi_uri`, `upi_id`, `amount`, `name`, `created_at_ist` |
|
|
213
|
+
| `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 |
|
|
214
|
+
|
|
215
|
+
`VeriPayClient(base_url, api_key=None, timeout=30)`
|
|
216
|
+
|
|
217
|
+
| Method | Arguments | Returns |
|
|
218
|
+
|---|---|---|
|
|
219
|
+
| `health` | none | dict with `ok`, `gmail_configured`, `supabase_configured`, `auth_required` |
|
|
220
|
+
| `generate_qr` | `upi_id`, `amount`, `name` | same dict as the library |
|
|
221
|
+
| `verify_payment` | `amount`, optional `utr`, optional `txnid` | same dict as the library |
|
|
222
|
+
|
|
223
|
+
`VeriPayError` is raised for missing parameters. Inbox or network problems come back inside the result, and `VeriPayClient` raises `VeriPayClientError` for non-200 responses.
|
|
224
|
+
|
|
225
|
+
## HTTP API
|
|
226
|
+
|
|
227
|
+
The `api/` folder is a Python serverless API for Vercel, built on the same core as the SDK.
|
|
228
|
+
|
|
229
|
+
### Deploy
|
|
230
|
+
|
|
231
|
+
1. Import this repository on Vercel.
|
|
232
|
+
2. Keep the **Root Directory** at the repository root, so `vercel.json` and `requirements.txt` are picked up.
|
|
233
|
+
3. Add the environment variables listed below.
|
|
234
|
+
4. Deploy. Functions appear at `/api/health`, `/api/qr` and `/api/verify`.
|
|
235
|
+
|
|
236
|
+
`vercel.json` bundles the `sdk/` folder with the functions, and `requirements.txt` installs `segno`.
|
|
237
|
+
|
|
238
|
+
### Environment variables
|
|
239
|
+
|
|
240
|
+
| Name | Required | Used for |
|
|
241
|
+
|---|---|---|
|
|
242
|
+
| `GMAIL` | for `/api/verify` | inbox that receives payment receipts |
|
|
243
|
+
| `GMAIL_APP_PASSWORD` | for `/api/verify` | Gmail App Password |
|
|
244
|
+
| `SUPABASE_URL` | no | logging and duplicate protection |
|
|
245
|
+
| `SUPABASE_SERVICE_ROLE_KEY` | no | Supabase write access |
|
|
246
|
+
| `API_KEY` | no | when set, POST requests must send `x-api-key` |
|
|
247
|
+
|
|
248
|
+
Without the two Supabase values the API still verifies payments, it just keeps no history. Add them and redeploy to enable duplicate protection.
|
|
249
|
+
|
|
250
|
+
### Endpoints
|
|
251
|
+
|
|
252
|
+
`GET /api/health`
|
|
253
|
+
|
|
254
|
+
```bash
|
|
255
|
+
curl https://your-deployment.vercel.app/api/health
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
```json
|
|
259
|
+
{ "ok": true, "gmail_configured": true, "supabase_configured": false, "auth_required": true }
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
`POST /api/qr`
|
|
263
|
+
|
|
264
|
+
```bash
|
|
265
|
+
curl -X POST https://your-deployment.vercel.app/api/qr \
|
|
266
|
+
-H 'content-type: application/json' \
|
|
267
|
+
-H 'x-api-key: your-api-key' \
|
|
268
|
+
-d '{"upi_id":"yourname@fam","amount":"25.01","name":"Demo Store"}'
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
```json
|
|
272
|
+
{
|
|
273
|
+
"qr_image": "data:image/png;base64,...",
|
|
274
|
+
"upi_uri": "upi://pay?pa=yourname@fam&pn=Demo%20Store&am=25.01&cu=INR",
|
|
275
|
+
"upi_id": "yourname@fam",
|
|
276
|
+
"amount": "25.01",
|
|
277
|
+
"name": "Demo Store",
|
|
278
|
+
"created_at_ist": "05/12/2026, 04:10:00 PM"
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
`POST /api/verify`
|
|
283
|
+
|
|
284
|
+
```bash
|
|
285
|
+
curl -X POST https://your-deployment.vercel.app/api/verify \
|
|
286
|
+
-H 'content-type: application/json' \
|
|
287
|
+
-H 'x-api-key: your-api-key' \
|
|
288
|
+
-d '{"amount":"25.01","utr":"412345678901"}'
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
Found payment:
|
|
292
|
+
|
|
293
|
+
```json
|
|
294
|
+
{
|
|
295
|
+
"verified": true,
|
|
296
|
+
"transaction_id": "412345678901",
|
|
297
|
+
"amount": 25.01,
|
|
298
|
+
"utr": "412345678901",
|
|
299
|
+
"sender_name": "Rahul Sharma",
|
|
300
|
+
"payment_time_ist": "05/12/2026, 04:08:12 PM"
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Nothing matched:
|
|
305
|
+
|
|
306
|
+
```json
|
|
307
|
+
{
|
|
308
|
+
"verified": false,
|
|
309
|
+
"message": "Transaction not found",
|
|
310
|
+
"details": "No matching payment found in email inbox"
|
|
311
|
+
}
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Status codes:
|
|
315
|
+
|
|
316
|
+
| Code | When |
|
|
317
|
+
|---|---|
|
|
318
|
+
| `200` | request handled, check the `verified` field for the outcome |
|
|
319
|
+
| `400` | body is not a JSON object, or a required field is missing |
|
|
320
|
+
| `401` | `API_KEY` is set and `x-api-key` does not match |
|
|
321
|
+
| `500` | unexpected server error, message in `error` |
|
|
322
|
+
|
|
323
|
+
## Database setup (optional)
|
|
324
|
+
|
|
325
|
+
Everything here is optional. It is what makes duplicate protection and history possible.
|
|
326
|
+
|
|
327
|
+
### 1. Create a Supabase project
|
|
328
|
+
|
|
329
|
+
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.
|
|
330
|
+
|
|
331
|
+
### 2. Create the table
|
|
332
|
+
|
|
333
|
+
Run this in the SQL editor:
|
|
334
|
+
|
|
335
|
+
```sql
|
|
336
|
+
create table api_logs (
|
|
337
|
+
id bigint generated by default as identity primary key,
|
|
338
|
+
user_id text,
|
|
339
|
+
endpoint text,
|
|
340
|
+
status int,
|
|
341
|
+
utr text,
|
|
342
|
+
txn_id text,
|
|
343
|
+
amount numeric,
|
|
344
|
+
created_at timestamptz default now()
|
|
345
|
+
);
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
The names matter: the code writes `endpoint`, `status`, `utr`, `txn_id`, `amount` and `user_id`.
|
|
349
|
+
|
|
350
|
+
### 3. Copy two values
|
|
351
|
+
|
|
352
|
+
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.
|
|
353
|
+
|
|
354
|
+
### 4. Pass them in
|
|
355
|
+
|
|
356
|
+
| Where | How |
|
|
357
|
+
|---|---|
|
|
358
|
+
| Node | `supabaseUrl` and `supabaseServiceRoleKey` in the constructor |
|
|
359
|
+
| Python | `supabase_url` and `supabase_service_role_key` arguments |
|
|
360
|
+
| Vercel | `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` environment variables, then redeploy |
|
|
361
|
+
|
|
362
|
+
### 5. Check it works
|
|
363
|
+
|
|
364
|
+
`GET /api/health` should report `"supabase_configured": true`. Then run one check and look at the table:
|
|
365
|
+
|
|
366
|
+
```sql
|
|
367
|
+
select endpoint, status, utr, txn_id, amount, created_at
|
|
368
|
+
from api_logs
|
|
369
|
+
order by id desc
|
|
370
|
+
limit 10;
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
### What gets stored
|
|
374
|
+
|
|
375
|
+
| Column | Meaning |
|
|
376
|
+
|---|---|
|
|
377
|
+
| `user_id` | whatever you pass as `userId` / `user_id`, for grouping by order or customer |
|
|
378
|
+
| `endpoint` | `generate_qr` or `verify_payment` |
|
|
379
|
+
| `status` | `200` found, `400` bad request, `401` bad credentials, `404` nothing matched, `500` other failure |
|
|
380
|
+
| `utr` / `txn_id` | reference read from the receipt or sent by you |
|
|
381
|
+
| `amount` | amount that was checked |
|
|
382
|
+
|
|
383
|
+
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.
|
|
384
|
+
|
|
385
|
+
### Optional: block races with a unique index
|
|
386
|
+
|
|
387
|
+
The check-then-write order means two simultaneous requests for the same UTR could both pass. A partial unique index closes that gap:
|
|
388
|
+
|
|
389
|
+
```sql
|
|
390
|
+
create unique index if not exists api_logs_paid_utr
|
|
391
|
+
on api_logs (utr) where status = 200 and utr is not null;
|
|
392
|
+
|
|
393
|
+
create unique index if not exists api_logs_paid_txn
|
|
394
|
+
on api_logs (txn_id) where status = 200 and txn_id is not null;
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
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`.
|
|
398
|
+
|
|
399
|
+
### Using your own database
|
|
400
|
+
|
|
401
|
+
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`.
|
|
402
|
+
|
|
403
|
+
## How matching works
|
|
404
|
+
|
|
405
|
+
1. IMAP search for the reference number, or for the amount as text.
|
|
406
|
+
2. Each message is parsed and subject plus body are checked for credit wording: `received`, `credited`, `added`.
|
|
407
|
+
3. The amount is matched against patterns like `Rs.25.01`, `INR 25.01` or `₹25.01`.
|
|
408
|
+
4. UTR and transaction ID are extracted from the body.
|
|
409
|
+
5. With logging on, a reference already stored with status `200` is skipped.
|
|
410
|
+
|
|
411
|
+
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.
|
|
412
|
+
|
|
413
|
+
## Limits worth knowing
|
|
414
|
+
|
|
415
|
+
- Gmail IMAP must stay enabled on the account; Workspace admins can switch it off.
|
|
416
|
+
- Receipt layouts differ between apps, so wording and reference formats are matched by pattern, not by strict templates.
|
|
417
|
+
- Amount matching assumes a unique paise value per order, which is why `25.01` beats a round `25`.
|
|
418
|
+
- Without a database the same payment can be verified again; that is the only thing the database adds.
|
|
419
|
+
- Payment gateway callbacks and refunds are out of scope.
|
|
420
|
+
|
|
421
|
+
## Development
|
|
422
|
+
|
|
423
|
+
```bash
|
|
424
|
+
npm install
|
|
425
|
+
npm run build
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
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.
|
|
429
|
+
|
|
430
|
+
## License
|
|
431
|
+
|
|
432
|
+
MIT.
|
package/dist/index.d.ts
ADDED
|
@@ -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,201 @@
|
|
|
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
|
+
function rupees(value) {
|
|
21
|
+
return new RegExp(`(?:rs\\.?|inr|₹|\\s|^)${value}(?:\\.00)?(?:\\s|$|\\.)`, 'i');
|
|
22
|
+
}
|
|
23
|
+
export class VeriPayUPI {
|
|
24
|
+
constructor(config) {
|
|
25
|
+
if (!config.gmail || !config.gmailAppPassword) {
|
|
26
|
+
throw new Error('Gmail credentials (gmail and app password) are required.');
|
|
27
|
+
}
|
|
28
|
+
this.account = config.gmail.includes('@') ? config.gmail : `${config.gmail}@gmail.com`;
|
|
29
|
+
this.passphrase = config.gmailAppPassword.replace(/\s/g, '');
|
|
30
|
+
this.store =
|
|
31
|
+
config.supabaseUrl && config.supabaseServiceRoleKey
|
|
32
|
+
? createClient(config.supabaseUrl, config.supabaseServiceRoleKey)
|
|
33
|
+
: null;
|
|
34
|
+
}
|
|
35
|
+
async generateQr(params) {
|
|
36
|
+
const { upiId, amount, name, userId = null } = params;
|
|
37
|
+
if (!upiId || !amount || !name) {
|
|
38
|
+
await this.write({ endpoint: 'generate_qr', status: 400, amount: amount ? Number(amount) : null, userId });
|
|
39
|
+
throw new Error('Missing parameters (upiId, amount, and name are required)');
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const uri = this.paymentUri(upiId, name, amount);
|
|
43
|
+
const image = await QRCode.toDataURL(uri, { margin: 2, width: 400 });
|
|
44
|
+
await this.write({ endpoint: 'generate_qr', status: 200, amount: Number(amount), userId });
|
|
45
|
+
return {
|
|
46
|
+
qr_image: image,
|
|
47
|
+
upi_uri: uri,
|
|
48
|
+
upi_id: upiId,
|
|
49
|
+
amount: String(amount),
|
|
50
|
+
name,
|
|
51
|
+
created_at_ist: istStamp()
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
catch (failure) {
|
|
55
|
+
await this.write({ endpoint: 'generate_qr', status: 500, amount: Number(amount), userId });
|
|
56
|
+
throw new Error(`Failed to generate QR code: ${failure?.message ?? failure}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async verifyPayment(params) {
|
|
60
|
+
const { amount, utr, txnid, userId = null } = params;
|
|
61
|
+
if (!amount) {
|
|
62
|
+
throw new Error('Amount is required for verification.');
|
|
63
|
+
}
|
|
64
|
+
const expected = Number(amount);
|
|
65
|
+
const reference = utr || txnid;
|
|
66
|
+
const referenceColumn = utr ? 'utr' : 'txn_id';
|
|
67
|
+
if (reference && (await this.alreadyStored(referenceColumn, reference))) {
|
|
68
|
+
return {
|
|
69
|
+
verified: false,
|
|
70
|
+
message: 'Transaction already verified',
|
|
71
|
+
details: 'This UTR / Txn ID has already been used.'
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
let session = null;
|
|
75
|
+
try {
|
|
76
|
+
session = await imapSimple.connect({
|
|
77
|
+
imap: {
|
|
78
|
+
user: this.account,
|
|
79
|
+
password: this.passphrase,
|
|
80
|
+
host: MAIL_HOST,
|
|
81
|
+
port: MAIL_PORT,
|
|
82
|
+
tls: true,
|
|
83
|
+
tlsOptions: { rejectUnauthorized: false },
|
|
84
|
+
authTimeout: 10000
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
await session.openBox('INBOX');
|
|
88
|
+
const mailbox = await session.search([['TEXT', reference || String(amount)]], SEARCH_SHAPE);
|
|
89
|
+
if (mailbox.length === 0) {
|
|
90
|
+
session.end();
|
|
91
|
+
await this.writeFailure(userId, 404, expected, utr, txnid);
|
|
92
|
+
return { ...NO_MATCH };
|
|
93
|
+
}
|
|
94
|
+
for (const message of mailbox) {
|
|
95
|
+
const rawPart = message.parts.find((part) => part.which === '');
|
|
96
|
+
if (!rawPart?.body)
|
|
97
|
+
continue;
|
|
98
|
+
const mail = await simpleParser(rawPart.body);
|
|
99
|
+
const body = mail.text ?? '';
|
|
100
|
+
const flat = `${mail.subject ?? ''}\n${body}`.toLowerCase();
|
|
101
|
+
const looksCredited = CREDIT_WORDS.some((word) => flat.includes(word));
|
|
102
|
+
if (!looksCredited)
|
|
103
|
+
continue;
|
|
104
|
+
if (!reference && mail.date && Date.now() - mail.date.getTime() > FRESH_WINDOW_MS)
|
|
105
|
+
continue;
|
|
106
|
+
const amountSeen = rupees(expected).test(flat) || flat.includes(String(expected));
|
|
107
|
+
if (!amountSeen)
|
|
108
|
+
continue;
|
|
109
|
+
const sender = this.senderName(body);
|
|
110
|
+
const foundUtr = utr ?? this.utrOf(body);
|
|
111
|
+
const foundTxn = txnid ?? this.txnOf(body);
|
|
112
|
+
const fingerprint = foundUtr || foundTxn;
|
|
113
|
+
if (fingerprint && (await this.alreadyStored(foundUtr ? 'utr' : 'txn_id', fingerprint)))
|
|
114
|
+
continue;
|
|
115
|
+
await this.write({
|
|
116
|
+
endpoint: 'verify_payment',
|
|
117
|
+
status: 200,
|
|
118
|
+
amount: expected,
|
|
119
|
+
userId,
|
|
120
|
+
utr: foundUtr,
|
|
121
|
+
txnId: foundTxn
|
|
122
|
+
});
|
|
123
|
+
session.end();
|
|
124
|
+
return {
|
|
125
|
+
verified: true,
|
|
126
|
+
transaction_id: foundTxn || foundUtr || undefined,
|
|
127
|
+
amount: expected,
|
|
128
|
+
utr: foundUtr,
|
|
129
|
+
sender_name: sender,
|
|
130
|
+
payment_time_ist: istStamp(mail.date ?? undefined)
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
session.end();
|
|
134
|
+
await this.writeFailure(userId, 404, expected, utr, txnid);
|
|
135
|
+
return { ...NO_MATCH };
|
|
136
|
+
}
|
|
137
|
+
catch (failure) {
|
|
138
|
+
if (session)
|
|
139
|
+
session.end();
|
|
140
|
+
const reason = String(failure?.message ?? failure);
|
|
141
|
+
const rejected = /authenticationfailed|invalid credentials|auth/i.test(reason);
|
|
142
|
+
await this.writeFailure(userId, rejected ? 401 : 500, expected, utr, txnid);
|
|
143
|
+
return {
|
|
144
|
+
verified: false,
|
|
145
|
+
message: rejected ? 'Invalid Gmail credentials' : 'Error during check',
|
|
146
|
+
details: reason
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
paymentUri(upiId, payee, amount) {
|
|
151
|
+
const params = [`pa=${upiId}`, `pn=${encodeURIComponent(payee)}`, `am=${encodeURIComponent(String(amount))}`, 'cu=INR'];
|
|
152
|
+
return `upi://pay?${params.join('&')}`;
|
|
153
|
+
}
|
|
154
|
+
senderName(body) {
|
|
155
|
+
const hit = body.match(/(?:from|received from|sender)\s+([a-zA-Z ]{3,30})/i);
|
|
156
|
+
if (!hit?.[1])
|
|
157
|
+
return UNKNOWN_SENDER;
|
|
158
|
+
const name = hit[1].trim();
|
|
159
|
+
return name.toLowerCase().endsWith('at') ? name.slice(0, -3).trim() : name;
|
|
160
|
+
}
|
|
161
|
+
utrOf(body) {
|
|
162
|
+
const hit = body.match(/(?:utr|upi ref no|ref no|reference no)\s*:\s*([0-9]{12})/i);
|
|
163
|
+
return hit?.[1]?.trim() ?? null;
|
|
164
|
+
}
|
|
165
|
+
txnOf(body) {
|
|
166
|
+
const hit = body.match(/(?:transaction id|txn id)\s*:\s*([a-zA-Z0-9]+)/i);
|
|
167
|
+
return hit?.[1]?.trim() ?? null;
|
|
168
|
+
}
|
|
169
|
+
async alreadyStored(column, value) {
|
|
170
|
+
if (!this.store)
|
|
171
|
+
return false;
|
|
172
|
+
const { data } = await this.store
|
|
173
|
+
.from('api_logs')
|
|
174
|
+
.select('id')
|
|
175
|
+
.eq('status', 200)
|
|
176
|
+
.eq(column, value);
|
|
177
|
+
return Array.isArray(data) && data.length > 0;
|
|
178
|
+
}
|
|
179
|
+
async writeFailure(userId, status, amount, utr, txnid) {
|
|
180
|
+
await this.write({
|
|
181
|
+
endpoint: 'verify_payment',
|
|
182
|
+
status,
|
|
183
|
+
amount,
|
|
184
|
+
userId,
|
|
185
|
+
utr: utr ?? null,
|
|
186
|
+
txnId: txnid ?? null
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
async write(entry) {
|
|
190
|
+
if (!this.store)
|
|
191
|
+
return;
|
|
192
|
+
await this.store.from('api_logs').insert({
|
|
193
|
+
user_id: entry.userId ?? null,
|
|
194
|
+
endpoint: entry.endpoint,
|
|
195
|
+
status: entry.status,
|
|
196
|
+
utr: entry.utr ?? null,
|
|
197
|
+
txn_id: entry.txnId ?? null,
|
|
198
|
+
amount: entry.amount
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dev-crowagent/veripay-upi",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
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
|
+
}
|