@jayik/node 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 +672 -2
- package/dist/index.cjs +957 -0
- package/dist/index.d.cts +587 -0
- package/dist/index.d.ts +587 -0
- package/dist/index.js +895 -0
- package/package.json +55 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jayik
|
|
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,673 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/Jayik-app/jayik-node/main/art/banner.svg" alt="@jayik/node — Node.js client for the Jayik Merchant API" width="100%">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
# @jayik/node
|
|
6
|
+
|
|
7
|
+
Node.js client for the [Jayik Merchant API v2](https://www.jayik.app/api-docs): create and track delivery orders, manage warehouses and categories, and receive signed webhooks.
|
|
8
|
+
|
|
9
|
+
- Node.js 20+, TypeScript types included, ESM and CommonJS
|
|
10
|
+
- No runtime dependencies (uses the built-in `fetch`)
|
|
11
|
+
- Every endpoint of the Merchant API (39) is covered
|
|
12
|
+
- Official package, maintained by Jayik
|
|
13
|
+
|
|
14
|
+
Using Laravel? See [jayik/laravel](https://github.com/Jayik-app/jayik-laravel).
|
|
15
|
+
|
|
16
|
+
## Contents
|
|
17
|
+
|
|
18
|
+
- [Installation](#installation)
|
|
19
|
+
- [Configuration](#configuration)
|
|
20
|
+
- [Quick start](#quick-start)
|
|
21
|
+
- [How responses work](#how-responses-work)
|
|
22
|
+
- [Orders](#orders)
|
|
23
|
+
- [Warehouses](#warehouses)
|
|
24
|
+
- [Order categories](#order-categories)
|
|
25
|
+
- [Reference data](#reference-data)
|
|
26
|
+
- [Account](#account)
|
|
27
|
+
- [API keys](#api-keys)
|
|
28
|
+
- [Marketplaces](#marketplaces)
|
|
29
|
+
- [Webhooks](#webhooks)
|
|
30
|
+
- [Error handling](#error-handling)
|
|
31
|
+
- [Rate limits](#rate-limits)
|
|
32
|
+
- [Constants](#constants)
|
|
33
|
+
- [Testing your app](#testing-your-app)
|
|
34
|
+
- [Method reference](#method-reference)
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npm install @jayik/node
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Configuration
|
|
43
|
+
|
|
44
|
+
Create an API key in the Tajr dashboard (https://tajr.jayik.app/api-keys). A key acts as the merchant account that owns it, so keep it on the server and never ship it to a browser.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { Jayik } from '@jayik/node';
|
|
48
|
+
|
|
49
|
+
const jayik = new Jayik({ apiKey: process.env.JAYIK_API_KEY });
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Every option falls back to an environment variable, so with these set `new Jayik()` is enough:
|
|
53
|
+
|
|
54
|
+
```dotenv
|
|
55
|
+
JAYIK_API_KEY=jk_live_...
|
|
56
|
+
JAYIK_WEBHOOK_SECRET=whsec_...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| Option | Environment variable | Default | Purpose |
|
|
60
|
+
|---|---|---|---|
|
|
61
|
+
| `apiKey` | `JAYIK_API_KEY` | – | Sent as the `X-API-KEY` header |
|
|
62
|
+
| `baseUrl` | `JAYIK_BASE_URL` | `https://api.jayik.app/api/merchant` | API root |
|
|
63
|
+
| `timeout` | `JAYIK_TIMEOUT` | `30` | Request timeout, seconds (`0` disables) |
|
|
64
|
+
| `rateLimit.retries` | `JAYIK_RATE_LIMIT_RETRIES` | `2` | Retries after a 429 (`0` disables) |
|
|
65
|
+
| `rateLimit.maxWait` | `JAYIK_RATE_LIMIT_MAX_WAIT` | `30` | Longest wait per retry, seconds |
|
|
66
|
+
| `webhook.secret` | `JAYIK_WEBHOOK_SECRET` | – | Secret used to verify incoming webhooks |
|
|
67
|
+
| `webhook.tolerance` | `JAYIK_WEBHOOK_TOLERANCE` | `300` | Maximum webhook age, seconds (`0` disables) |
|
|
68
|
+
| `fetch` | – | global `fetch` | Custom fetch implementation |
|
|
69
|
+
|
|
70
|
+
Node does not read `.env` files by itself: start your app with `node --env-file=.env` or use your framework's loader.
|
|
71
|
+
|
|
72
|
+
## Quick start
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { Jayik } from '@jayik/node';
|
|
76
|
+
|
|
77
|
+
const jayik = new Jayik();
|
|
78
|
+
|
|
79
|
+
// 1. Create the order (it starts as Pending)
|
|
80
|
+
let order = await jayik.orders.create({
|
|
81
|
+
customer_name: 'Ali Hassan',
|
|
82
|
+
customer_phone: '07809876543',
|
|
83
|
+
customer_address: 'Baghdad, Karrada, near the bridge',
|
|
84
|
+
amount: 25000, // IQD; 0 when already paid
|
|
85
|
+
governorate_id: 1, // UUID or governorate number
|
|
86
|
+
order_category_id: categoryId,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// 2. Tell Jayik it is ready for the driver
|
|
90
|
+
await jayik.orders.readyToPickup(order.tr);
|
|
91
|
+
|
|
92
|
+
// 3. Later: look it up by tracking number
|
|
93
|
+
order = await jayik.orders.findByTr(order.tr, ['status']);
|
|
94
|
+
console.log(order.status.name); // "AwaitingPickup"
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
CommonJS works too: `const { Jayik } = require('@jayik/node');`
|
|
98
|
+
|
|
99
|
+
## How responses work
|
|
100
|
+
|
|
101
|
+
- Methods return **plain objects** exactly as the API sends them, with the API's snake_case keys. The `{status, message, data}` wrapper is removed, so you get `data` directly.
|
|
102
|
+
- List methods return a `Page`:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
const page = await jayik.orders.list({ take: 50 });
|
|
106
|
+
|
|
107
|
+
page.items; // array of orders
|
|
108
|
+
page.total; // number, or null when requested with simple: true
|
|
109
|
+
page.currentPage;
|
|
110
|
+
page.perPage;
|
|
111
|
+
page.lastPage;
|
|
112
|
+
page.hasMorePages;
|
|
113
|
+
page.isEmpty;
|
|
114
|
+
page.length; // items on this page
|
|
115
|
+
page.raw; // raw page object
|
|
116
|
+
|
|
117
|
+
for (const order of page) { ... }
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
- `lazy()` methods return an async iterator that fetches page after page as you loop.
|
|
121
|
+
- Amounts are Iraqi dinars. `take` is capped at 500 by the API.
|
|
122
|
+
- Failed calls throw errors; see [Error handling](#error-handling).
|
|
123
|
+
|
|
124
|
+
## Orders
|
|
125
|
+
|
|
126
|
+
<p align="center">
|
|
127
|
+
<img src="https://raw.githubusercontent.com/Jayik-app/jayik-laravel/main/art/order-flow.svg" alt="Order status flow" width="100%">
|
|
128
|
+
</p>
|
|
129
|
+
|
|
130
|
+
### Create an order
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
const order = await jayik.orders.create({ ... });
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
| Field | Type | Required | Notes |
|
|
137
|
+
|---|---|---|---|
|
|
138
|
+
| `customer_phone` | string | yes | e.g. `07809876543` |
|
|
139
|
+
| `customer_address` | string | yes | |
|
|
140
|
+
| `amount` | number | yes | IQD to collect; `0` for prepaid |
|
|
141
|
+
| `order_category_id` | uuid | yes | One of your categories |
|
|
142
|
+
| `governorate_id` | uuid \| number | yes | Governorate UUID or its `number` |
|
|
143
|
+
| `customer_name` | string | no | |
|
|
144
|
+
| `tr` | string | no | Your own tracking number; generated when omitted |
|
|
145
|
+
| `warehouse_id` | uuid | no | Pickup point; must be yours |
|
|
146
|
+
| `district_id` | uuid | no | Needed for fawri when the account has a fawri price list |
|
|
147
|
+
| `delivery_type` | number | no | `0` normal (default), `1` fawri / express |
|
|
148
|
+
| `notes` | string | no | |
|
|
149
|
+
| `business_name` | string | no | |
|
|
150
|
+
| `destination_coordinate` | string | no | `"lat,lng"`, e.g. `"33.312805,44.361488"` |
|
|
151
|
+
| `total_products` | number | no | |
|
|
152
|
+
| `scheduled_delivery_date_from` | datetime | no | `Date` objects are formatted for you (see below) |
|
|
153
|
+
| `scheduled_delivery_date_to` | datetime | no | Must be after `_from` |
|
|
154
|
+
| `invoice_url` | string | no | |
|
|
155
|
+
| `order_items` | array | no | Each: `attribute_id`, `name`, `weight`, `unit`, `count` |
|
|
156
|
+
|
|
157
|
+
`Date` objects anywhere in a request body are sent as `YYYY-MM-DD HH:MM:SS` in the **local time zone of your Node process**. Pass a string instead if your server does not run in the time zone you mean.
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
import { DeliveryType } from '@jayik/node';
|
|
161
|
+
|
|
162
|
+
await jayik.orders.create({
|
|
163
|
+
customer_phone: '07809876543',
|
|
164
|
+
customer_address: 'Erbil, 100m Street',
|
|
165
|
+
amount: 0,
|
|
166
|
+
governorate_id: governorateUuid,
|
|
167
|
+
order_category_id: categoryId,
|
|
168
|
+
delivery_type: DeliveryType.FAWRI,
|
|
169
|
+
district_id: districtId,
|
|
170
|
+
order_items: [{ attribute_id: attributeId, name: 'T-shirt', weight: 1, unit: 'kg', count: 2 }],
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### Create many orders
|
|
175
|
+
|
|
176
|
+
1 to 300 orders in one request. All are created or none are. The API returns no order data, so look them up by `tr` afterwards.
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
await jayik.orders.createBatch([
|
|
180
|
+
{ tr: 'A-1001', customer_name: 'Ali', customer_phone: '0780...', customer_address: '...', amount: 15000, order_category_id: cat, governorate_id: govUuid },
|
|
181
|
+
{ tr: 'A-1002', customer_name: 'Sara', customer_phone: '0770...', customer_address: '...', amount: 9000, order_category_id: cat, governorate_id: govUuid },
|
|
182
|
+
]);
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Differences from single create: `tr` and `customer_name` are **required**, and `governorate_id` must be the **UUID** (the number is not accepted).
|
|
186
|
+
|
|
187
|
+
### List and search
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
const page = await jayik.orders.list({
|
|
191
|
+
take: 50, // default 15
|
|
192
|
+
page: 1,
|
|
193
|
+
sort: '-created_at', // "-" = descending
|
|
194
|
+
from: '2026-11-01', // last-update range; send both
|
|
195
|
+
to: '2026-11-30',
|
|
196
|
+
simple: true, // skip the total count (faster)
|
|
197
|
+
include: ['status', 'customer', 'warehouse'],
|
|
198
|
+
filter: {
|
|
199
|
+
status_id: [pendingId, awaitingId], // arrays become CSV
|
|
200
|
+
warehouse_id: warehouseId,
|
|
201
|
+
'customer.phone': '07809876543',
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
| Filter | Matches |
|
|
207
|
+
|---|---|
|
|
208
|
+
| `tr`, `uuid` | Exact order |
|
|
209
|
+
| `status_id`, `not_status_id` | One or more status ids |
|
|
210
|
+
| `governorate_id`, `warehouse_id`, `order_category_id` | By relation |
|
|
211
|
+
| `delivery_type` | `0` or `1` |
|
|
212
|
+
| `customer.phone` | Phone |
|
|
213
|
+
| `customer.name`, `customer.address` | Search |
|
|
214
|
+
| `amount` | Amount |
|
|
215
|
+
|
|
216
|
+
Allowed `include` values: `status`, `customer`, `governorate`, `district`, `warehouse`, `orderCategory`, `orderItems`, `orderItems.attribute`, `merchant`, `history.merchant`, `driverRate`, `amountChanges`, `financial`. Nested objects only appear when included.
|
|
217
|
+
|
|
218
|
+
Walk through every match without handling pages yourself:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
for await (const order of jayik.orders.lazy({ filter: { warehouse_id: id } })) {
|
|
222
|
+
await syncOrder(order);
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
### Get one order
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
await jayik.orders.get(123, ['status', 'history.merchant']); // by numeric id
|
|
230
|
+
await jayik.orders.findByTr('100006537', ['status']); // by tracking number, null if none
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
An order has three identifiers: `tr` (tracking number, used by most actions), `id` (integer, used by `get` and `delete`) and `uuid`.
|
|
234
|
+
|
|
235
|
+
### Change an order
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
await jayik.orders.readyToPickup(tr); // Pending -> AwaitingPickup
|
|
239
|
+
await jayik.orders.cancel(tr); // while Pending, AwaitingPickup or PickupDelayed
|
|
240
|
+
await jayik.orders.delete(id); // permanent; only while Pending
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
### Tracking numbers
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
const tr = await jayik.orders.generateTr(); // "100006537"
|
|
247
|
+
await jayik.orders.trExists('A-1001'); // boolean
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
## Warehouses
|
|
251
|
+
|
|
252
|
+
Warehouses are your pickup points. Pass a warehouse's `id` as `warehouse_id` when creating an order.
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
const warehouse = await jayik.warehouses.create({
|
|
256
|
+
name: 'Main store', // required
|
|
257
|
+
address: 'Baghdad, Mansour', // required
|
|
258
|
+
governorate_id: 1, // UUID or number
|
|
259
|
+
lat: 33.3128,
|
|
260
|
+
long: 44.3615,
|
|
261
|
+
phone: '07801234567',
|
|
262
|
+
secondary_phone: null,
|
|
263
|
+
availability_times_from: '09:00',
|
|
264
|
+
availability_times_to: '18:00',
|
|
265
|
+
site_id: 'vendor-42', // your own reference
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
await jayik.warehouses.list(15, 1); // take, page
|
|
269
|
+
jayik.warehouses.lazy(); // async iterator
|
|
270
|
+
await jayik.warehouses.get(id);
|
|
271
|
+
await jayik.warehouses.update(id, { name: 'New name', governorate_id: 1 });
|
|
272
|
+
await jayik.warehouses.delete(id);
|
|
273
|
+
await jayik.warehouses.setDefault(id); // used when an order has no warehouse_id
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
> Always send `governorate_id` when updating. Leaving it out clears the warehouse's governorate.
|
|
277
|
+
|
|
278
|
+
### Business hours
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
await jayik.warehouses.businessHours(id);
|
|
282
|
+
// [{ day: 'sunday', opens_at: '09:00', closes_at: '17:00', is_closed: false }, ...]
|
|
283
|
+
|
|
284
|
+
await jayik.warehouses.updateBusinessHours(id, {
|
|
285
|
+
sunday: { is_closed: false, opens_at: '09:00', closes_at: '17:00' },
|
|
286
|
+
friday: { is_closed: true },
|
|
287
|
+
}); // days you leave out stay as they are
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
## Order categories
|
|
291
|
+
|
|
292
|
+
Every order needs one of your categories.
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
const category = await jayik.orderCategories.create('Clothes');
|
|
296
|
+
|
|
297
|
+
await jayik.orderCategories.list(10, 1); // take, page
|
|
298
|
+
jayik.orderCategories.lazy();
|
|
299
|
+
await jayik.orderCategories.get(id);
|
|
300
|
+
await jayik.orderCategories.update(id, 'Fashion');
|
|
301
|
+
await jayik.orderCategories.delete(id);
|
|
302
|
+
await jayik.orderCategories.setDefault(id);
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
## Reference data
|
|
306
|
+
|
|
307
|
+
These rarely change, so cache them on your side.
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
const governorates = await jayik.governorates.all();
|
|
311
|
+
// [{ id: '...', name: 'بغداد', number: 1 }, ...]
|
|
312
|
+
|
|
313
|
+
await jayik.statuses.all(); // id, name (stable code), ar_name, en_name, kr_name, color, ...
|
|
314
|
+
await jayik.attributes.all(); // product types for order_items[].attribute_id
|
|
315
|
+
|
|
316
|
+
// Paged and single lookups
|
|
317
|
+
await jayik.governorates.list(10, 1);
|
|
318
|
+
await jayik.governorates.get(id);
|
|
319
|
+
await jayik.statuses.list();
|
|
320
|
+
await jayik.statuses.get(id);
|
|
321
|
+
await jayik.attributes.list();
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
Status ids are UUIDs. To filter orders by status, map the stable `name` to its id once:
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
import { OrderStatus } from '@jayik/node';
|
|
328
|
+
|
|
329
|
+
const statusIds = Object.fromEntries((await jayik.statuses.all()).map((status) => [status.name, status.id]));
|
|
330
|
+
|
|
331
|
+
await jayik.orders.list({ filter: { status_id: statusIds[OrderStatus.DELIVERED] } });
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
## Account
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
const details = await jayik.account.details();
|
|
338
|
+
// { user: {...}, roles: [...], permissions: [...] }
|
|
339
|
+
|
|
340
|
+
await jayik.account.permissions(); // ['merchant-get-order', 'merchant-store-order', ...]
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Keys that belong to an employee only have that employee's permissions; a missing permission results in a `PermissionDeniedError`.
|
|
344
|
+
|
|
345
|
+
## API keys
|
|
346
|
+
|
|
347
|
+
```ts
|
|
348
|
+
const key = await jayik.apiKeys.create('Production server');
|
|
349
|
+
key.key; // shown only this once — store it now
|
|
350
|
+
|
|
351
|
+
await jayik.apiKeys.list();
|
|
352
|
+
await jayik.apiKeys.get(id); // never includes the value
|
|
353
|
+
await jayik.apiKeys.update(id, false); // switch off
|
|
354
|
+
await jayik.apiKeys.update(id, true, 'New label');
|
|
355
|
+
await jayik.apiKeys.regenerate(id); // old value stops working immediately
|
|
356
|
+
await jayik.apiKeys.delete(id);
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
## Marketplaces
|
|
360
|
+
|
|
361
|
+
**One Jayik account, many vendors.** Create a warehouse per vendor and keep its id:
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
const warehouse = await jayik.warehouses.create({
|
|
365
|
+
name: vendor.name,
|
|
366
|
+
address: vendor.address,
|
|
367
|
+
site_id: String(vendor.id),
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
await saveVendor(vendor.id, { jayikWarehouseId: warehouse.id });
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
An order has one pickup point, so a basket with products from several vendors becomes one order per vendor:
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
// itemsByVendor: { [vendorId]: cartItem[] }
|
|
377
|
+
for (const [vendorId, items] of Object.entries(itemsByVendor)) {
|
|
378
|
+
await jayik.orders.create({
|
|
379
|
+
warehouse_id: vendors[vendorId].jayikWarehouseId,
|
|
380
|
+
amount: items.reduce((sum, item) => sum + item.total, 0),
|
|
381
|
+
total_products: items.reduce((sum, item) => sum + item.quantity, 0),
|
|
382
|
+
// customer and destination fields...
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
Then list a vendor's orders with `filter: { warehouse_id: id }`.
|
|
388
|
+
|
|
389
|
+
**Each vendor has their own Jayik account.** Switch keys per call; the default key is untouched:
|
|
390
|
+
|
|
391
|
+
```ts
|
|
392
|
+
await jayik.withKey(vendor.jayikApiKey).orders.create({ ... });
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
## Webhooks
|
|
396
|
+
|
|
397
|
+
<p align="center">
|
|
398
|
+
<img src="https://raw.githubusercontent.com/Jayik-app/jayik-laravel/main/art/webhook-flow.svg" alt="Webhook flow" width="100%">
|
|
399
|
+
</p>
|
|
400
|
+
|
|
401
|
+
Jayik sends a `POST` to your URL whenever one of your orders is created or changes. The package verifies the signature and hands you a parsed event.
|
|
402
|
+
|
|
403
|
+
### 1. Register your URL
|
|
404
|
+
|
|
405
|
+
```ts
|
|
406
|
+
await jayik.webhook.set('https://your-app.com/jayik/webhook'); // must be https
|
|
407
|
+
await jayik.webhook.secret(); // "whsec_..." -> put it in JAYIK_WEBHOOK_SECRET
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
### 2. Listen
|
|
411
|
+
|
|
412
|
+
`jayik.webhook.handler()` returns a `(req, res)` handler for Express, Connect and `node:http`. It answers `401` to anything not signed by Jayik and `{"received": true}` once your callback has finished.
|
|
413
|
+
|
|
414
|
+
```ts
|
|
415
|
+
import express from 'express';
|
|
416
|
+
import { Jayik, OrderStatus } from '@jayik/node';
|
|
417
|
+
|
|
418
|
+
const jayik = new Jayik();
|
|
419
|
+
const app = express();
|
|
420
|
+
|
|
421
|
+
// Mount this BEFORE express.json(): the signature is checked against the raw body.
|
|
422
|
+
app.post(
|
|
423
|
+
'/jayik/webhook',
|
|
424
|
+
jayik.webhook.handler(async (event) => {
|
|
425
|
+
if (event.status === OrderStatus.DELIVERED) {
|
|
426
|
+
await markDelivered(event.tr);
|
|
427
|
+
}
|
|
428
|
+
}),
|
|
429
|
+
);
|
|
430
|
+
|
|
431
|
+
app.use(express.json());
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
If a JSON body parser must run first, keep the raw bytes for the handler: `express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })`.
|
|
435
|
+
|
|
436
|
+
| On `event` | |
|
|
437
|
+
|---|---|
|
|
438
|
+
| `.operation` | `created`, `updated`, `assigned`, `deleted`, `restored`, `forceDeleted` |
|
|
439
|
+
| `.order` | The order record (includes `driver`) |
|
|
440
|
+
| `.payload` | The full decoded body |
|
|
441
|
+
| `.tr` | Tracking number |
|
|
442
|
+
| `.status` | Status code, e.g. `Delivered` |
|
|
443
|
+
| `.driver` | `id`, `name`, `phone` (null unless enabled for your account) |
|
|
444
|
+
| `.isCreated`, `.isUpdated`, `.isAssigned`, `.isDeleted` | Shortcuts |
|
|
445
|
+
| `.is(operation)` | Compare against any `WebhookOperation` |
|
|
446
|
+
|
|
447
|
+
Jayik expects a 2xx answer within 5 seconds. Hand slow work to a queue and return quickly. If your callback throws, the handler answers `500`; pass `{ onEvent, onError }` instead of a function to receive the error.
|
|
448
|
+
|
|
449
|
+
### Other frameworks
|
|
450
|
+
|
|
451
|
+
Anywhere you can read the raw body and the headers, use `constructEvent`. It throws `InvalidSignatureError` when the request is not from Jayik. For example in a Next.js route handler, Hono, or any fetch-style runtime:
|
|
452
|
+
|
|
453
|
+
```ts
|
|
454
|
+
import { InvalidSignatureError } from '@jayik/node';
|
|
455
|
+
|
|
456
|
+
export async function POST(request: Request) {
|
|
457
|
+
try {
|
|
458
|
+
const event = jayik.webhook.constructEvent(await request.text(), request.headers);
|
|
459
|
+
// ...
|
|
460
|
+
return Response.json({ received: true });
|
|
461
|
+
} catch (error) {
|
|
462
|
+
if (error instanceof InvalidSignatureError) {
|
|
463
|
+
return Response.json({ message: 'Invalid signature.' }, { status: 401 });
|
|
464
|
+
}
|
|
465
|
+
throw error;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
Fastify, NestJS and others work the same way: enable their raw-body option and pass the raw body with `request.headers`.
|
|
471
|
+
|
|
472
|
+
### 3. Test it
|
|
473
|
+
|
|
474
|
+
```ts
|
|
475
|
+
await jayik.webhook.test(); // sample data, operation "created"
|
|
476
|
+
await jayik.webhook.test(tr, 'updated'); // a real order's data
|
|
477
|
+
await jayik.webhook.redeliver(tr); // re-send "created" for an order
|
|
478
|
+
await jayik.webhook.get(); // current URL, secret and signature scheme
|
|
479
|
+
await jayik.webhook.remove(); // stop receiving events
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
### How verification works
|
|
483
|
+
|
|
484
|
+
Each request carries `X-Jayik-Timestamp` (Unix seconds) and `X-Jayik-Signature` (`sha256=` + hex digest). The signature is HMAC-SHA256 of `{timestamp}.{raw body}` with your webhook secret. Requests with a wrong signature, missing headers, or a timestamp older than the tolerance are rejected, and so is everything when no secret is configured. The comparison is timing-safe.
|
|
485
|
+
|
|
486
|
+
To verify by hand:
|
|
487
|
+
|
|
488
|
+
```ts
|
|
489
|
+
import { SignatureVerifier } from '@jayik/node';
|
|
490
|
+
|
|
491
|
+
const verifier = new SignatureVerifier(process.env.JAYIK_WEBHOOK_SECRET, 300);
|
|
492
|
+
|
|
493
|
+
const valid = verifier.isValid(rawBody, req.headers['x-jayik-signature'], req.headers['x-jayik-timestamp']);
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
## Error handling
|
|
497
|
+
|
|
498
|
+
Every failed call throws a subclass of `RequestError`, which itself extends `JayikError`.
|
|
499
|
+
|
|
500
|
+
| Status | Error | Meaning |
|
|
501
|
+
|---|---|---|
|
|
502
|
+
| 400 | `ValidationError` | Invalid or refused input |
|
|
503
|
+
| 401 | `AuthenticationError` | Missing or invalid key |
|
|
504
|
+
| 403 | `PermissionDeniedError` | Inactive account, missing permission, or action not allowed |
|
|
505
|
+
| 404 | `NotFoundError` | Nothing with that id on your account |
|
|
506
|
+
| 409 | `ConflictError` | Not possible in the order's current state |
|
|
507
|
+
| 422 | `UnprocessableError` | Valid request that cannot be carried out |
|
|
508
|
+
| 429 | `RateLimitError` | Too many requests |
|
|
509
|
+
| other | `RequestError` | Anything else, e.g. 5xx |
|
|
510
|
+
|
|
511
|
+
```ts
|
|
512
|
+
import { RequestError, ValidationError } from '@jayik/node';
|
|
513
|
+
|
|
514
|
+
try {
|
|
515
|
+
await jayik.orders.create(data);
|
|
516
|
+
} catch (error) {
|
|
517
|
+
if (error instanceof ValidationError) {
|
|
518
|
+
error.errors; // { customer_phone: ['The customer phone field is required.'] }
|
|
519
|
+
error.message; // first message
|
|
520
|
+
} else if (error instanceof RequestError) {
|
|
521
|
+
error.status; // HTTP status
|
|
522
|
+
error.response; // { status, headers, body, text }
|
|
523
|
+
} else {
|
|
524
|
+
throw error;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
A missing API key throws a `JayikError` before any request is sent. Network failures and timeouts throw a `ConnectionError` (also a `JayikError`) with the original error in `cause`.
|
|
530
|
+
|
|
531
|
+
## Rate limits
|
|
532
|
+
|
|
533
|
+
The API allows 120 requests per minute per account. When it answers `429`, the client waits the number of seconds in `Retry-After` and tries again, up to `rateLimit.retries` times. If the wait would be longer than `rateLimit.maxWait`, or retries run out, you get a `RateLimitError`:
|
|
534
|
+
|
|
535
|
+
```ts
|
|
536
|
+
if (error instanceof RateLimitError) {
|
|
537
|
+
await requeue(job, { delaySeconds: error.retryAfter ?? 60 });
|
|
538
|
+
}
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
For bulk work, prefer `createBatch()` and a larger `take` over many small calls.
|
|
542
|
+
|
|
543
|
+
## Constants
|
|
544
|
+
|
|
545
|
+
```ts
|
|
546
|
+
import { CANCELLABLE_STATUSES, DeliveryType, OrderStatus, WebhookOperation } from '@jayik/node';
|
|
547
|
+
|
|
548
|
+
DeliveryType.NORMAL; // 0
|
|
549
|
+
DeliveryType.FAWRI; // 1
|
|
550
|
+
WebhookOperation; // CREATED, UPDATED, ASSIGNED, DELETED, RESTORED, FORCE_DELETED
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
| `OrderStatus` | Value | Meaning |
|
|
554
|
+
|---|---|---|
|
|
555
|
+
| `PENDING` | `Pending` | Created, waiting for you to mark it ready |
|
|
556
|
+
| `AWAITING_PICKUP` | `AwaitingPickup` | Ready for the driver |
|
|
557
|
+
| `PICKUP_DELAYED` | `PickupDelayed` | |
|
|
558
|
+
| `CANCELLED_BY_MERCHANT` | `CancelledByMerchant` | |
|
|
559
|
+
| `IN_TRANSIT` | `InTransit` | |
|
|
560
|
+
| `IN_DELIVERY_COMPANY_WAREHOUSE` | `InDeliveryCompanyWarehouse` | |
|
|
561
|
+
| `RECEIVED` | `Received` | With the driver, out for delivery |
|
|
562
|
+
| `HAND_OVER` | `HandOver` | |
|
|
563
|
+
| `DELAYED` | `Delayed` | |
|
|
564
|
+
| `RE_DELIVERY` | `ReDelivery` | |
|
|
565
|
+
| `DELIVERED` | `Delivered` | |
|
|
566
|
+
| `RETURNED` | `Returned` | |
|
|
567
|
+
| `RETURNED_TO_COMPANY` | `ReturnedToCompany` | |
|
|
568
|
+
| `ON_THE_WAY_TO_MERCHANT_WAREHOUSE` | `OnTheWayToMerchantWarehouse` | |
|
|
569
|
+
| `RETURNED_TO_MAIN_WAREHOUSE` | `ReturnedToMainWarehouse` | |
|
|
570
|
+
| `CANCELLED` | `Cancelled` | |
|
|
571
|
+
|
|
572
|
+
`CANCELLABLE_STATUSES` lists the statuses in which `cancel()` is allowed.
|
|
573
|
+
|
|
574
|
+
## Testing your app
|
|
575
|
+
|
|
576
|
+
Pass your own `fetch` to answer requests without touching the network:
|
|
577
|
+
|
|
578
|
+
```ts
|
|
579
|
+
const calls = [];
|
|
580
|
+
|
|
581
|
+
const jayik = new Jayik({
|
|
582
|
+
apiKey: 'jk_test',
|
|
583
|
+
fetch: async (url, init) => {
|
|
584
|
+
calls.push({ url, body: JSON.parse(init.body) });
|
|
585
|
+
|
|
586
|
+
return Response.json({
|
|
587
|
+
status: true,
|
|
588
|
+
message: 'Order Created Successfully',
|
|
589
|
+
data: { id: 1, tr: '100006537' },
|
|
590
|
+
});
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
await checkout(jayik);
|
|
595
|
+
|
|
596
|
+
assert.equal(calls[0].url, 'https://api.jayik.app/api/merchant/v2/orders');
|
|
597
|
+
assert.equal(calls[0].body.amount, 25000);
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
To fake an incoming webhook, sign it with the verifier:
|
|
601
|
+
|
|
602
|
+
```ts
|
|
603
|
+
const body = JSON.stringify({ opration: 'updated', data: { tr: '100', status: { name: 'Delivered' } } });
|
|
604
|
+
const time = Math.floor(Date.now() / 1000);
|
|
605
|
+
|
|
606
|
+
await fetch('http://localhost:3000/jayik/webhook', {
|
|
607
|
+
method: 'POST',
|
|
608
|
+
body,
|
|
609
|
+
headers: {
|
|
610
|
+
'Content-Type': 'application/json',
|
|
611
|
+
'X-Jayik-Timestamp': String(time),
|
|
612
|
+
'X-Jayik-Signature': jayik.webhook.verifier.sign(body, time),
|
|
613
|
+
},
|
|
614
|
+
});
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
Run the package's own tests with `npm test`.
|
|
618
|
+
|
|
619
|
+
## Method reference
|
|
620
|
+
|
|
621
|
+
| Call | Endpoint | Permission |
|
|
622
|
+
|---|---|---|
|
|
623
|
+
| `account.details()` | `GET /auth/details` | – |
|
|
624
|
+
| `orders.list(query)` / `lazy(query)` | `GET /v2/orders` | `merchant-get-order` |
|
|
625
|
+
| `orders.get(id, include)` | `GET /v2/orders/{id}` | `merchant-show-order` |
|
|
626
|
+
| `orders.findByTr(tr, include)` | `GET /v2/orders?filter[tr]=` | `merchant-get-order` |
|
|
627
|
+
| `orders.create(order)` | `POST /v2/orders` | `merchant-store-order` |
|
|
628
|
+
| `orders.createBatch(orders)` | `POST /v2/orders/batch` | `merchant-store-order` |
|
|
629
|
+
| `orders.generateTr()` | `GET /v2/orders/generate-tr` | – |
|
|
630
|
+
| `orders.trExists(tr)` | `GET /v2/orders/tr-exists/{tr}` | – |
|
|
631
|
+
| `orders.cancel(tr)` | `PUT /v2/orders/cancel` | `merchant-cancel-order` |
|
|
632
|
+
| `orders.readyToPickup(tr)` | `PUT /v2/orders/ready-to-pickup` | `merchant-update-order` |
|
|
633
|
+
| `orders.delete(id)` | `DELETE /v2/orders/{id}` | `merchant-delete-order` |
|
|
634
|
+
| `warehouses.list()` / `lazy()` | `GET /v2/warehouses` | `merchant-get-warehouse` |
|
|
635
|
+
| `warehouses.get(id)` | `GET /v2/warehouses/{id}` | `merchant-show-warehouse` |
|
|
636
|
+
| `warehouses.create(data)` | `POST /v2/warehouses` | `merchant-store-warehouse` |
|
|
637
|
+
| `warehouses.update(id, data)` | `PUT /v2/warehouses/{id}` | `merchant-update-warehouse` |
|
|
638
|
+
| `warehouses.delete(id)` | `DELETE /v2/warehouses/{id}` | `merchant-delete-warehouse` |
|
|
639
|
+
| `warehouses.setDefault(id)` | `PUT /v2/warehouses/default` | `merchant-update-DefaultWarehouse` |
|
|
640
|
+
| `warehouses.businessHours(id)` | `GET /v2/warehouses/{id}/business-hours` | – |
|
|
641
|
+
| `warehouses.updateBusinessHours(id, hours)` | `PUT /v2/warehouses/{id}/business-hours` | `merchant-update-warehouse` |
|
|
642
|
+
| `orderCategories.list()` / `lazy()` | `GET /v2/order-categories` | `merchant-get-orderCategory` |
|
|
643
|
+
| `orderCategories.get(id)` | `GET /v2/order-categories/{id}` | `merchant-show-orderCategory` |
|
|
644
|
+
| `orderCategories.create(name)` | `POST /v2/order-categories` | `merchant-store-orderCategory` |
|
|
645
|
+
| `orderCategories.update(id, name)` | `PUT /v2/order-categories/{id}` | `merchant-update-orderCategory` |
|
|
646
|
+
| `orderCategories.delete(id)` | `DELETE /v2/order-categories/{id}` | `merchant-delete-orderCategory` |
|
|
647
|
+
| `orderCategories.setDefault(id)` | `PUT /v2/order-categories/default` | `merchant-update-DefaultCategory` |
|
|
648
|
+
| `governorates.list()` / `all()` | `GET /v2/governorates` | – |
|
|
649
|
+
| `governorates.get(id)` | `GET /v2/governorates/{id}` | – |
|
|
650
|
+
| `statuses.list()` / `all()` | `GET /v2/statuses` | – |
|
|
651
|
+
| `statuses.get(id)` | `GET /v2/statuses/{id}` | – |
|
|
652
|
+
| `attributes.list()` / `all()` | `GET /v2/attributes` | – |
|
|
653
|
+
| `webhook.get()` / `secret()` | `GET /v2/webhook` | `merchant-get-webhook` |
|
|
654
|
+
| `webhook.set(url)` / `remove()` | `PUT /v2/webhook` | `merchant-store-webhook` |
|
|
655
|
+
| `webhook.test(tr, operation)` | `POST /v2/webhook/test` | `merchant-send-webhook` |
|
|
656
|
+
| `webhook.redeliver(tr)` | `POST /v2/webhook/deliveries/{tr}` | `merchant-send-webhook` |
|
|
657
|
+
| `apiKeys.list()` | `GET /v2/api-keys` | `merchant-get-apiKey` |
|
|
658
|
+
| `apiKeys.get(id)` | `GET /v2/api-keys/{id}` | `merchant-show-apiKey` |
|
|
659
|
+
| `apiKeys.create(description)` | `POST /v2/api-keys` | `merchant-store-apiKey` |
|
|
660
|
+
| `apiKeys.regenerate(id)` | `POST /v2/api-keys/regenerate` | `merchant-re-generate-apiKey` |
|
|
661
|
+
| `apiKeys.update(id, active, description)` | `PUT /v2/api-keys/{id}` | `merchant-update-apiKey` |
|
|
662
|
+
| `apiKeys.delete(id)` | `DELETE /v2/api-keys/{id}` | `merchant-delete-apiKey` |
|
|
663
|
+
|
|
664
|
+
For an endpoint the package does not wrap yet, use the client directly:
|
|
665
|
+
|
|
666
|
+
```ts
|
|
667
|
+
await jayik.client.get('v2/something', { take: 10 });
|
|
668
|
+
await jayik.client.post('v2/something', { field: 'value' });
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
## License
|
|
672
|
+
|
|
673
|
+
MIT. See [LICENSE](LICENSE).
|