@swirepay-developer/sparo-embed-sdk 1.0.4 → 1.0.7

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.
@@ -1,435 +1,641 @@
1
1
  # Gateway Frontend — SPARO SDK Integration Guide (React)
2
2
 
3
- Step-by-step guide for **gateway-frontend** React developers integrating `@swirepay/sparo-embed-sdk` from npm.
3
+ Step-by-step guide for **gateway-frontend** developers integrating `@swirepay-developer/sparo-embed-sdk`.
4
4
 
5
- > **Prerequisite:** DevOps must publish the SDK from Bitbucket first.
5
+ > **Prerequisite:** DevOps publishes the SDK from Bitbucket.
6
6
  > Repo: https://bitbucket.org/zetametrics/sparo-swirepay-frontend.git — runbook: [DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md)
7
- >
8
- > **`Module not found: Can't resolve '@swirepay/sparo-embed-sdk'`** means the package is **not on npm** (or not installed). Ask DevOps to run `npm view @swirepay/sparo-embed-sdk version` — if **404**, publish is still pending. Your `SparoChat` code can be correct and this error will still appear.
9
7
 
10
8
  ---
11
9
 
12
- ## What you are building
10
+ ## How to use the SDK (overview)
13
11
 
14
- ```text
15
- User (logged into gateway)
16
- → React page (SparoChat)
17
- → SDK calls YOUR backend: GET /sparo/token
18
- → YOUR backend calls SPARO: POST /api/guest-token (SPARO_ADMIN_KEY)
19
- → SDK receives { token, expiresIn, account }
20
- → SDK loads SPARO iframe + sends JWT via postMessage
21
- → SPARO chat UI renders (no SPARO login screen)
12
+ The SDK exports two functions you need:
13
+
14
+ ```js
15
+ import {
16
+ embed, // mounts SPARO iframe + handles auth/refresh
17
+ createGuestTokenFetcher, // helper that calls Java GET /v1/sparo/guest-token
18
+ } from '@swirepay-developer/sparo-embed-sdk';
22
19
  ```
23
20
 
24
- You do **not** implement iframe auth yourself — the SDK handles iframe creation, `postMessage`, and token refresh.
21
+ | Function | Purpose |
22
+ |----------|---------|
23
+ | `embed({ ... })` | Creates iframe, fetches token, sends auth to SPARO, auto-refreshes |
24
+ | `createGuestTokenFetcher(url, { getAuthorization })` | Returns a `fetchGuestToken` function for `embed()` |
25
25
 
26
- ---
26
+ **Minimum working integration:**
27
27
 
28
- ## Prerequisites
28
+ ```jsx
29
+ import { useEffect, useRef } from 'react';
30
+ import { embed, createGuestTokenFetcher } from '@swirepay-developer/sparo-embed-sdk';
31
+
32
+ function SparoChat() {
33
+ const mountRef = useRef(null);
34
+
35
+ useEffect(() => {
36
+ const el = mountRef.current;
37
+ if (!el) return undefined;
38
+
39
+ const handle = embed({
40
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
41
+ mountPoint: el,
42
+ fetchGuestToken: createGuestTokenFetcher(
43
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
44
+ { getAuthorization: getGatewayAccessToken },
45
+ ),
46
+ onReady: () => console.log('[SPARO] ready'),
47
+ onError: (err) => console.error('[SPARO]', err.code, err.message),
48
+ });
49
+
50
+ return () => handle.unmount();
51
+ }, []);
52
+
53
+ return <div ref={mountRef} style={{ width: '100%', height: 720 }} />;
54
+ }
55
+ ```
29
56
 
30
- Before starting, confirm with your team:
57
+ You must provide:
31
58
 
32
- | Item | Owner | Notes |
33
- |------|--------|-------|
34
- | npm access to `@swirepay/sparo-embed-sdk` | DevOps / npm org | `npm login` if private scope |
35
- | `SPARO_ADMIN_KEY` | Backend | Never in React code or `.env` with `REACT_APP_` |
36
- | Merchant enabled in SPARO | SPARO admin | Deny-by-default allowlist |
37
- | Backend route `/sparo/token` | Backend | Returns guest JWT for logged-in user |
38
- | SPARO environment URL | Config | Staging vs production `sparoDomain` |
59
+ 1. **`sparoDomain`** — SPARO UI URL (iframe loads from here)
60
+ 2. **`mountPoint`** — DOM element to render into
61
+ 3. **`fetchGuestToken`** — async function returning `{ token, expiresIn, account }`
39
62
 
40
63
  ---
41
64
 
42
- ## Step 1 — Install the SDK
65
+ ## Architecture
43
66
 
44
- From the **gateway-frontend** project root:
67
+ Same pattern as **Apache Superset embedded analytics**: React SDK + backend guest-token API + embedded app iframe.
45
68
 
46
- ```bash
47
- npm install @swirepay/sparo-embed-sdk
69
+ ```text
70
+ User (logged into gateway)
71
+ → React SparoChat page
72
+ → SDK calls GET /v1/sparo/guest-token (Authorization: Bearer <gateway JWT>)
73
+ → Java validates user + merchant allowlist
74
+ → Returns { token, expiresIn, account }
75
+ → SDK loads SPARO iframe (sparoDomain) + postMessage auth
76
+ → SPARO chat UI (no SPARO login screen)
77
+ → SDK auto-refreshes token ~30s before expiry
48
78
  ```
49
79
 
50
- Or add to `package.json`:
80
+ You do **not** implement iframe auth, `postMessage`, or token refresh — the SDK handles that.
81
+
82
+ ---
83
+
84
+ ## Step 1 — Install
85
+
86
+ ```bash
87
+ yarn add @swirepay-developer/sparo-embed-sdk
88
+ ```
51
89
 
52
90
  ```json
53
91
  {
54
92
  "dependencies": {
55
- "@swirepay/sparo-embed-sdk": "^1.0.4"
93
+ "@swirepay-developer/sparo-embed-sdk": "^1.0.7"
56
94
  }
57
95
  }
58
96
  ```
59
97
 
60
- Then:
61
-
62
- ```bash
63
- npm install
64
- ```
65
-
66
- ### Verify install
98
+ Verify:
67
99
 
68
100
  ```bash
69
- npm ls @swirepay/sparo-embed-sdk
101
+ yarn why @swirepay-developer/sparo-embed-sdk
70
102
  ```
71
103
 
72
- You should see the package listed. If not:
73
-
74
- - Run `npm login` (private `@swirepay` scope)
75
- - Remove any old `"file:..."` path dependency for this package
76
- - Delete `node_modules` and `package-lock.json`, then `npm install` again
104
+ **Package name:** `@swirepay-developer/sparo-embed-sdk` (not `@swirepay/sparo-embed-sdk`).
77
105
 
78
106
  ---
79
107
 
80
- ## Step 2 — Environment variables (frontend)
108
+ ## Step 2 — Environment variables
81
109
 
82
- Add **non-secret** config only. Never put `SPARO_ADMIN_KEY` in React env vars.
110
+ | Variable | Staging | Production |
111
+ |----------|---------|------------|
112
+ | `REACT_APP_SPARO_GUEST_TOKEN_URL` | `https://staging-backend.swirepay.com/v1/sparo/guest-token` | `https://backend.swirepay.com/v1/sparo/guest-token` |
113
+ | `REACT_APP_SPARO_DOMAIN` | `https://sparo-stag.swirepay.com` | `https://sparo.swirepay.com` |
83
114
 
84
- ### `.env.development` (local / dev)
115
+ `.env.development`:
85
116
 
86
117
  ```env
87
- REACT_APP_SPARO_DOMAIN=https://sparo-staging.swirepay.com
118
+ REACT_APP_SPARO_GUEST_TOKEN_URL=https://staging-backend.swirepay.com/v1/sparo/guest-token
119
+ REACT_APP_SPARO_DOMAIN=https://sparo-stag.swirepay.com
88
120
  ```
89
121
 
90
- ### `.env.production`
122
+ `.env.production`:
91
123
 
92
124
  ```env
125
+ REACT_APP_SPARO_GUEST_TOKEN_URL=https://backend.swirepay.com/v1/sparo/guest-token
93
126
  REACT_APP_SPARO_DOMAIN=https://sparo.swirepay.com
94
127
  ```
95
128
 
96
- Use the URL your team provides for each environment.
97
- `sparoDomain` must match the environment your **backend** uses when minting tokens.
129
+ Restart the dev server after changing env vars.
98
130
 
99
131
  ---
100
132
 
101
- ## Step 3 — Backend contract (coordinate with backend team)
133
+ ## Step 3 — Recommended file layout
102
134
 
103
- Your React app will call **your** API, not SPARO directly.
135
+ ```text
136
+ src/
137
+ ├── utils/
138
+ │ └── sparoAuth.js # getGatewayAccessToken()
139
+ ├── routes/
140
+ │ └── SparoChat/
141
+ │ └── index.js # embed() + UI
142
+ └── routes.js # register /sparo route
143
+ ```
104
144
 
105
- ### Required endpoint (example)
145
+ ---
106
146
 
107
- `GET /sparo/token` (or `/api/sparo/token` — match your gateway API prefix)
147
+ ## Code samples
108
148
 
109
- **Request**
149
+ ### Sample 1 — `createGuestTokenFetcher` (recommended)
110
150
 
111
- - Authenticated user session (cookie or Bearer — same as rest of gateway)
112
- - `credentials: 'include'` if cookie-based
151
+ Use this when gateway Java exposes `GET /v1/sparo/guest-token`. The SDK calls it on **mount** and on **each auto-refresh**.
113
152
 
114
- **Response `200`**
153
+ ```js
154
+ import { createGuestTokenFetcher } from '@swirepay-developer/sparo-embed-sdk';
155
+ import { getGatewayAccessToken } from 'utils/sparoAuth';
156
+
157
+ const fetchGuestToken = createGuestTokenFetcher(
158
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
159
+ {
160
+ getAuthorization: getGatewayAccessToken,
161
+ },
162
+ );
163
+
164
+ // Pass to embed:
165
+ embed({ fetchGuestToken, sparoDomain, mountPoint, ... });
166
+ ```
115
167
 
116
- ```json
117
- {
118
- "token": "eyJhbGciOi...",
119
- "expiresIn": 900,
120
- "account": "account-72ec92..."
168
+ **What `getAuthorization` must return:** raw JWT string (`eyJ...`). The SDK adds `Bearer` if missing.
169
+
170
+ **Same-origin proxy** (if gateway BFF proxies the Java API):
171
+
172
+ ```js
173
+ const fetchGuestToken = createGuestTokenFetcher('/v1/sparo/guest-token', {
174
+ getAuthorization: getGatewayAccessToken,
175
+ });
176
+ ```
177
+
178
+ ---
179
+
180
+ ### Sample 2 — Auth helper (`src/utils/sparoAuth.js`)
181
+
182
+ Wire to whatever gateway already uses for API calls.
183
+
184
+ **Option A — existing axios / auth module:**
185
+
186
+ ```js
187
+ import { getAccessToken } from 'api/auth';
188
+
189
+ export async function getGatewayAccessToken() {
190
+ const token = await getAccessToken();
191
+ if (!token) throw new Error('Not authenticated');
192
+ return token;
121
193
  }
122
194
  ```
123
195
 
124
- | Field | Meaning |
125
- |-------|---------|
126
- | `token` | Short-lived guest JWT from SPARO |
127
- | `expiresIn` | Seconds until expiry (e.g. 900 = 15 min) |
128
- | `account` | Merchant account GID for this user |
196
+ **Option B — token from Redux / session store:**
197
+
198
+ ```js
199
+ import store from 'store';
200
+
201
+ export function getGatewayAccessToken() {
202
+ const token = store.getState().auth.accessToken;
203
+ if (!token) throw new Error('Not authenticated');
204
+ return token;
205
+ }
206
+ ```
207
+
208
+ **Option C — AWS Amplify (if gateway uses Cognito directly):**
209
+
210
+ ```js
211
+ import { fetchAuthSession } from 'aws-amplify/auth';
212
+
213
+ export async function getGatewayAccessToken() {
214
+ const session = await fetchAuthSession();
215
+ const token = session.tokens?.accessToken?.toString();
216
+ if (!token) throw new Error('Not authenticated');
217
+ return token;
218
+ }
219
+ ```
220
+
221
+ ---
222
+
223
+ ### Sample 3 — Custom `fetchGuestToken` with axios (alternative)
224
+
225
+ Use this if you prefer gateway's existing axios instance instead of `createGuestTokenFetcher`:
226
+
227
+ ```js
228
+ // src/utils/sparoGuestToken.js
229
+ import axios from 'axios';
230
+ import { getGatewayAccessToken } from './sparoAuth';
231
+
232
+ export async function fetchSparoGuestToken() {
233
+ const token = await getGatewayAccessToken();
234
+
235
+ const { data } = await axios.get(
236
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
237
+ {
238
+ headers: {
239
+ Authorization: `Bearer ${token}`,
240
+ Accept: 'application/json',
241
+ },
242
+ },
243
+ );
244
+
245
+ // Java may wrap response: { data: { token, expiresIn, account } }
246
+ const payload = data?.data?.token ? data.data : data;
247
+
248
+ return {
249
+ token: payload.token,
250
+ expiresIn: payload.expiresIn,
251
+ account: payload.account,
252
+ };
253
+ }
254
+ ```
255
+
256
+ ```jsx
257
+ import { embed } from '@swirepay-developer/sparo-embed-sdk';
258
+ import { fetchSparoGuestToken } from 'utils/sparoGuestToken';
259
+
260
+ embed({
261
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
262
+ mountPoint: mountRef.current,
263
+ fetchGuestToken: fetchSparoGuestToken,
264
+ // ...
265
+ });
266
+ ```
129
267
 
130
- **Important:** `account` must be the merchant the logged-in user belongs to. Backend resolves it from session/DB — frontend must not let users pick arbitrary merchant IDs.
268
+ Or import the SDK normalizer:
131
269
 
132
- ### Error responses to handle in UI
270
+ ```js
271
+ import { normalizeGuestTokenResponse } from '@swirepay-developer/sparo-embed-sdk';
133
272
 
134
- | HTTP | Meaning | Suggested UI |
135
- |------|---------|----------------|
136
- | 401 | User not logged in | Redirect to login |
137
- | 403 | `merchant_not_enabled` | “Contact us” / support message |
138
- | 429 | Rate limited | Retry message |
139
- | 500 | Mint failed | Generic error + support |
273
+ const { data } = await axios.get(url, { headers: { Authorization: `Bearer ${token}` } });
274
+ return normalizeGuestTokenResponse(data);
275
+ ```
140
276
 
141
277
  ---
142
278
 
143
- ## Step 4 — Create the React page component
279
+ ### Sample 4 — Full `SparoChat` component (copy-paste ready)
144
280
 
145
- Create a route component, e.g. `src/routes/SparoChat/index.js`:
281
+ Create `src/routes/SparoChat/index.js`:
146
282
 
147
283
  ```jsx
148
284
  import React, { useEffect, useRef, useState } from 'react';
149
- import { embed } from '@swirepay/sparo-embed-sdk';
285
+ import { Alert, Spin } from 'antd';
286
+ import {
287
+ embed,
288
+ createGuestTokenFetcher,
289
+ } from '@swirepay-developer/sparo-embed-sdk';
290
+ import { getGatewayAccessToken } from 'utils/sparoAuth';
150
291
 
151
- const SPARO_DOMAIN = process.env.REACT_APP_SPARO_DOMAIN || 'https://sparo.swirepay.com';
292
+ const SPARO_DOMAIN = process.env.REACT_APP_SPARO_DOMAIN;
293
+ const GUEST_TOKEN_URL = process.env.REACT_APP_SPARO_GUEST_TOKEN_URL;
152
294
 
153
- export default function SparoChat() {
295
+ function SparoChat() {
154
296
  const mountRef = useRef(null);
155
297
  const handleRef = useRef(null);
156
- const [error, setError] = useState(null);
157
- const [ready, setReady] = useState(false);
298
+ const [loading, setLoading] = useState(true);
299
+ const [error, setError] = useState('');
158
300
 
159
301
  useEffect(() => {
160
- const el = mountRef.current;
161
- if (!el) return undefined;
302
+ const mountElement = mountRef.current;
303
+ if (!mountElement) return undefined;
162
304
 
163
- setError(null);
164
- setReady(false);
305
+ setLoading(true);
306
+ setError('');
165
307
 
166
308
  handleRef.current = embed({
167
309
  id: 'sparo-chat',
168
310
  sparoDomain: SPARO_DOMAIN,
169
- mountPoint: el,
170
- fetchGuestToken: async () => {
171
- const res = await fetch('/sparo/token', {
172
- credentials: 'include',
173
- });
174
- if (res.status === 401) {
175
- window.location.href = '/login';
176
- throw new Error('Unauthorized');
177
- }
178
- if (!res.ok) {
179
- const body = await res.json().catch(() => ({}));
180
- const err = new Error(body.error || 'Failed to fetch SPARO token');
181
- err.code = body.code || 'fetch_failed';
182
- throw err;
183
- }
184
- return res.json();
185
- },
311
+ mountPoint: mountElement,
312
+
313
+ // SDK calls Java API with Bearer JWT on mount + each refresh
314
+ fetchGuestToken: createGuestTokenFetcher(GUEST_TOKEN_URL, {
315
+ getAuthorization: getGatewayAccessToken,
316
+ }),
317
+
186
318
  uiConfig: {
187
319
  theme: 'light',
188
320
  showWelcome: true,
189
321
  showSuggestions: true,
190
322
  hideSidebar: false,
191
323
  },
192
- onReady: () => setReady(true),
324
+
325
+ onReady: () => {
326
+ setLoading(false);
327
+ },
328
+
193
329
  onError: (err) => {
194
330
  console.error('[SPARO]', err.code, err.message);
195
- setError(err.message || 'SPARO failed to load');
331
+ setLoading(false);
332
+
333
+ if (err.code === 'merchant_not_enabled') {
334
+ setError('Your merchant account is not enabled for SPARO.');
335
+ } else if (err.code === 'invalid_token') {
336
+ setError('Session expired. Please sign in again.');
337
+ } else if (err.code === 'rate_limited') {
338
+ setError('Too many requests. Please try again shortly.');
339
+ } else {
340
+ setError(err.message || 'Failed to initialize SPARO.');
341
+ }
196
342
  },
197
343
  });
198
344
 
345
+ // Required: tear down iframe + timers when user leaves the page
199
346
  return () => {
200
- if (handleRef.current) {
201
- handleRef.current.unmount();
202
- handleRef.current = null;
203
- }
347
+ handleRef.current?.unmount();
348
+ handleRef.current = null;
204
349
  };
205
350
  }, []);
206
351
 
207
352
  return (
208
- <div style={{ padding: 16 }}>
209
- <h1>SPARO Assistant</h1>
210
- {ready && !error && (
211
- <p style={{ color: '#389e0d', fontSize: 13 }}>Connected</p>
353
+ <div style={{ padding: 20 }}>
354
+ <h2>SPARO Assistant</h2>
355
+
356
+ {loading && (
357
+ <div style={{ marginBottom: 16, textAlign: 'center' }}>
358
+ <Spin size="large" />
359
+ </div>
212
360
  )}
361
+
213
362
  {error && (
214
- <p style={{ color: '#cf1322' }} role="alert">
215
- {error}
216
- </p>
363
+ <Alert type="error" showIcon message={error} style={{ marginBottom: 16 }} />
217
364
  )}
365
+
218
366
  <div
219
367
  ref={mountRef}
220
368
  style={{
221
369
  width: '100%',
222
370
  height: '720px',
223
- minHeight: 480,
224
- border: '1px solid #e8e8e8',
371
+ minHeight: '480px',
372
+ border: '1px solid #d9d9d9',
225
373
  borderRadius: 8,
374
+ overflow: 'hidden',
226
375
  }}
227
376
  />
228
377
  </div>
229
378
  );
230
379
  }
380
+
381
+ export default SparoChat;
231
382
  ```
232
383
 
233
- ### If your API base URL is not same-origin
384
+ ---
234
385
 
235
- Use your existing axios instance or API helper:
386
+ ### Sample 5 — `embed()` options explained
236
387
 
237
388
  ```js
238
- import { axiosAuthInstance, API_END_POINTS } from 'api';
389
+ const handle = embed({
390
+ // Required
391
+ sparoDomain: 'https://sparo-stag.swirepay.com', // SPARO UI origin
392
+ mountPoint: document.getElementById('sparo'), // DOM node (use ref.current in React)
393
+ fetchGuestToken: createGuestTokenFetcher(url, { getAuthorization }),
394
+
395
+ // Optional
396
+ id: 'sparo-chat', // iframe element id (default: 'sparo-embed')
397
+ uiConfig: {
398
+ theme: 'light', // 'light' | 'dark'
399
+ showWelcome: true,
400
+ showSuggestions: true,
401
+ hideSidebar: false,
402
+ },
403
+ onReady: () => {}, // iframe authenticated and ready
404
+ onError: (err) => {}, // err.code + err.message
405
+ });
406
+
407
+ // handle.refresh() — force token refresh (rarely needed; SDK auto-refreshes)
408
+ // handle.unmount() — remove iframe + clear timers (call on route unmount)
409
+ ```
239
410
 
240
- fetchGuestToken: async () => {
241
- const { data } = await axiosAuthInstance.get('/sparo/token');
242
- return data;
243
- },
411
+ **`fetchGuestToken` return shape** (Java API must return this):
412
+
413
+ ```js
414
+ {
415
+ token: 'eyJhbGciOi...', // SPARO guest JWT
416
+ expiresIn: 900, // seconds until expiry
417
+ account: 'account-72ec92...', // merchant account GID
418
+ }
244
419
  ```
245
420
 
246
421
  ---
247
422
 
248
- ## Step 5 — Register the route
423
+ ### Sample 6 — Register route
249
424
 
250
- Add a protected route in your router config (example for React Router v5):
425
+ React Router v5 (gateway pattern):
251
426
 
252
427
  ```js
253
428
  import SparoChat from 'routes/SparoChat';
254
429
 
255
- // In routes array:
430
+ // In your routes array:
256
431
  {
257
432
  key: 'sparo',
258
433
  path: '/sparo',
259
434
  exact: true,
260
435
  protected: true,
261
436
  component: SparoChat,
262
- allowedRoles: [/* same roles as your team allows */],
437
+ allowedRoles: ['MERCHANT_ADMIN', 'MERCHANT_USER'],
263
438
  }
264
439
  ```
265
440
 
266
- Add a nav link or header icon that navigates to `/sparo`.
441
+ Nav link example:
267
442
 
268
- Restart the dev server after adding the route:
443
+ ```jsx
444
+ import { Link } from 'react-router-dom';
269
445
 
270
- ```bash
271
- npm start
446
+ <Link to="/sparo">SPARO Assistant</Link>
272
447
  ```
273
448
 
274
449
  ---
275
450
 
276
- ## Step 6 — Test locally
451
+ ### Sample 7 — TypeScript (optional)
277
452
 
278
- 1. Log in to gateway as a user tied to an **enabled** merchant.
279
- 2. Open `/sparo`.
280
- 3. Open DevTools → **Network**:
281
- - Confirm `GET /sparo/token` returns `200` with `token`, `expiresIn`, `account`.
282
- 4. Open DevTools → **Console**:
283
- - No `Module not found` for `@swirepay/sparo-embed-sdk`.
284
- 5. Confirm iframe loads (Elements tab → `iframe` under your mount div).
285
- 6. SPARO UI should appear without a SPARO login page.
453
+ ```tsx
454
+ import { useEffect, useRef } from 'react';
455
+ import {
456
+ embed,
457
+ createGuestTokenFetcher,
458
+ type EmbedHandle,
459
+ type SparoEmbedError,
460
+ } from '@swirepay-developer/sparo-embed-sdk';
461
+ import { getGatewayAccessToken } from 'utils/sparoAuth';
462
+
463
+ export function SparoChat(): JSX.Element {
464
+ const mountRef = useRef<HTMLDivElement>(null);
465
+ const handleRef = useRef<EmbedHandle | null>(null);
466
+
467
+ useEffect(() => {
468
+ const el = mountRef.current;
469
+ if (!el) return undefined;
286
470
 
287
- ### Staging vs production
471
+ handleRef.current = embed({
472
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN!,
473
+ mountPoint: el,
474
+ fetchGuestToken: createGuestTokenFetcher(
475
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL!,
476
+ { getAuthorization: getGatewayAccessToken },
477
+ ),
478
+ onError: (err: SparoEmbedError) => {
479
+ console.error(err.code, err.message);
480
+ },
481
+ });
288
482
 
289
- | Environment | `REACT_APP_SPARO_DOMAIN` | Backend mint URL |
290
- |-------------|--------------------------|------------------|
291
- | Staging | Staging SPARO host | Same SPARO env as domain |
292
- | Production | `https://sparo.swirepay.com` (or prod host) | Production SPARO API |
483
+ return () => handleRef.current?.unmount();
484
+ }, []);
293
485
 
294
- Mismatch (staging token + production domain) causes auth failures.
486
+ return <div ref={mountRef} style={{ width: '100%', height: 720 }} />;
487
+ }
488
+ ```
295
489
 
296
490
  ---
297
491
 
298
- ## Step 7 — SDK API reference (what you pass)
492
+ ### Sample 8 — Manual refresh button (optional)
299
493
 
300
- ### `embed(options)`
494
+ The SDK auto-refreshes ~30s before expiry. Use this only if you need a user-triggered refresh:
301
495
 
302
- | Option | Required | Description |
303
- |--------|----------|-------------|
304
- | `sparoDomain` | Yes | SPARO host, e.g. `https://sparo.swirepay.com` |
305
- | `mountPoint` | Yes | DOM element (use `ref.current`) |
306
- | `fetchGuestToken` | Yes | Async function returning `{ token, expiresIn, account }` |
307
- | `id` | No | iframe id (default `sparo-embed`) |
308
- | `uiConfig` | No | Theme and UI flags (see below) |
309
- | `onReady` | No | Called when iframe signals ready |
310
- | `onError` | No | Called on token/iframe errors |
496
+ ```jsx
497
+ const handleRef = useRef(null);
311
498
 
312
- ### `uiConfig` (optional)
499
+ // inside embed setup:
500
+ handleRef.current = embed({ ... });
313
501
 
314
- ```js
315
- {
316
- theme: 'light', // 'light' | 'dark'
317
- showWelcome: true,
318
- showSuggestions: true,
319
- hideSidebar: false,
320
- }
502
+ // in JSX:
503
+ <button
504
+ type="button"
505
+ onClick={() => handleRef.current?.refresh()}
506
+ >
507
+ Refresh SPARO session
508
+ </button>
321
509
  ```
322
510
 
323
- ### Return value
511
+ ---
324
512
 
325
- ```js
326
- const handle = embed({ ... });
513
+ ## Backend API contract
327
514
 
328
- handle.refresh(); // manually refresh token (usually not needed)
329
- handle.unmount(); // cleanup — call on route leave (useEffect return)
515
+ Gateway Java validates the logged-in user and returns a short-lived SPARO guest JWT.
516
+
517
+ ```http
518
+ GET /v1/sparo/guest-token
519
+ Authorization: Bearer <gateway-session-jwt>
520
+ Accept: application/json
330
521
  ```
331
522
 
332
- Token refresh is **automatic** ~30 seconds before expiry.
523
+ **Response `200`:**
333
524
 
334
- ---
525
+ ```json
526
+ {
527
+ "token": "eyJhbGciOi...",
528
+ "expiresIn": 900,
529
+ "account": "account-72ec92..."
530
+ }
531
+ ```
335
532
 
336
- ## Step 8 — Security checklist (frontend)
533
+ Wrapped responses (`{ "data": { ... } }`) are handled automatically by `createGuestTokenFetcher`.
337
534
 
338
- - Do not store `SPARO_ADMIN_KEY` in frontend.
339
- - Do not put guest `token` in URL query params.
340
- - Do not hardcode production tokens in source.
341
- - Always use `credentials: 'include'` if session is cookie-based.
342
- - Always `unmount()` when leaving the page (see `useEffect` cleanup).
343
- - Size the mount container with CSS (`height: 720px` or full viewport).
535
+ | HTTP | SDK `err.code` | UI suggestion |
536
+ |------|----------------|---------------|
537
+ | 401 | `invalid_token` | Redirect to login |
538
+ | 403 | `merchant_not_enabled` | Contact support |
539
+ | 429 | `rate_limited` | Retry later |
540
+ | 5xx | `fetch_failed` | Generic error |
344
541
 
345
542
  ---
346
543
 
347
- ## Troubleshooting
544
+ ## Test locally
348
545
 
349
- ### `Module not found: Can't resolve '@swirepay/sparo-embed-sdk'`
546
+ 1. Log in as a user tied to an **enabled** merchant.
547
+ 2. Open `/sparo`.
548
+ 3. **Network:** `GET .../v1/sparo/guest-token` → `200` JSON with `token`, `expiresIn`, `account`.
549
+ 4. **Console:** no `Module not found` errors.
550
+ 5. **Elements:** `iframe` under mount div; SPARO UI without login screen.
350
551
 
351
- Webpack shows this when the package is **not installed** under `node_modules` (install failed or was never run).
552
+ ```bash
553
+ yarn start
554
+ ```
352
555
 
353
- **Step 0 — verify the package exists on your registry**
556
+ ---
354
557
 
355
- From `gateway-frontend`:
558
+ ## SDK exports reference
356
559
 
357
- ```bash
358
- npm view @swirepay/sparo-embed-sdk version
560
+ ```js
561
+ import {
562
+ embed, // main entry — mount SPARO iframe
563
+ createGuestTokenFetcher, // build fetchGuestToken for Java API
564
+ normalizeGuestTokenResponse, // unwrap { data: {...} } from Java
565
+ } from '@swirepay-developer/sparo-embed-sdk';
359
566
  ```
360
567
 
361
- | Result | Meaning |
362
- |--------|---------|
363
- | `1.0.4` (or similar) | Published — go to Step 1 |
364
- | `404 Not Found` | **Not on registry.npmjs.org** (or wrong scope/name). `npm install` will not add the package → this error persists |
568
+ ### Error codes (`onError`)
365
569
 
366
- If you see **404**, DevOps has not published yet (or gateway CI lacks npm read access to `@swirepay`). Do not merge gateway code that imports the SDK until `npm view` returns a version.
570
+ | Code | Meaning |
571
+ |------|---------|
572
+ | `merchant_not_enabled` | Merchant not on SPARO allowlist (403) |
573
+ | `invalid_token` | 401 or malformed token response |
574
+ | `expired_token` | Token expired before refresh |
575
+ | `fetch_failed` | Network, CORS, or non-JSON error |
576
+ | `iframe_load_failed` | iframe did not load |
577
+ | `rate_limited` | 429 from backend |
367
578
 
368
- **Step 1 — install and confirm**
579
+ ---
369
580
 
370
- ```bash
371
- cd gateway-frontend
372
- npm install @swirepay/sparo-embed-sdk
373
- dir node_modules\@swirepay\sparo-embed-sdk\dist
374
- ```
581
+ ## Security checklist
582
+
583
+ - Do not store `SPARO_ADMIN_KEY` in frontend code.
584
+ - Do not put guest `token` in URL query params.
585
+ - Pass JWT via `getAuthorization` at runtime only.
586
+ - Always call `handle.unmount()` in `useEffect` cleanup.
587
+ - Size mount container with CSS (`height: 720px` minimum).
588
+
589
+ ---
375
590
 
376
- You must see `index.cjs` and `index.js` in that folder. If the folder is missing, the install did not succeed.
591
+ ## Troubleshooting
377
592
 
378
- **Step 2**
593
+ ### `Module not found: Can't resolve '@swirepay/sparo-embed-sdk'`
379
594
 
380
- 1. Restart `npm start` (CRA caches module resolution).
381
- 2. In `package.json`, use a normal semver dependency — not a broken `file:` path to a machine-specific folder unless every dev shares that path.
595
+ Wrong scope. Use `@swirepay-developer/sparo-embed-sdk`:
382
596
 
383
- ### Blank iframe / “Awaiting auth”
597
+ ```bash
598
+ yarn add @swirepay-developer/sparo-embed-sdk
599
+ ```
384
600
 
385
- - Check `/sparo/token` returns valid JSON shape.
386
- - Confirm `account` matches an allowlisted merchant.
387
- - Confirm `sparoDomain` matches token mint environment (HTTPS in prod).
601
+ ### `Module not found: Can't resolve '@swirepay-developer/sparo-embed-sdk'`
388
602
 
389
- ### Mixed content blocked
603
+ ```bash
604
+ npm view @swirepay-developer/sparo-embed-sdk version
605
+ ```
390
606
 
391
- - Page is `https://` but `sparoDomain` is `http://` → use HTTPS SPARO URL.
607
+ If version prints, run `yarn add` and restart dev server. If `404`, SDK not published yet.
392
608
 
393
- ### `merchant_not_enabled` (403)
609
+ ### Guest-token returns HTML / 404
394
610
 
395
- - Merchant not on SPARO allowlist — contact SPARO admin, not a frontend bug.
611
+ Wrong `REACT_APP_SPARO_GUEST_TOKEN_URL` — must be Java API URL, not a React route.
396
612
 
397
- ### `fetch_failed`
613
+ ### Blank iframe
398
614
 
399
- - Backend down, CORS issue, or user session expired.
400
- - Check Network tab on `/sparo/token`.
615
+ - Response missing `token`, `expiresIn`, or `account`.
616
+ - `REACT_APP_SPARO_DOMAIN` mismatched with token environment (staging vs prod).
401
617
 
402
618
  ### Iframe works on refresh but not first load
403
619
 
404
- - Ensure `mountRef.current` exists before calling `embed` (use `useEffect`, not render body).
405
- - Do not call `embed` with `null` mount point.
620
+ Call `embed` inside `useEffect` after `mountRef.current` is set.
406
621
 
407
622
  ---
408
623
 
409
- ## Minimal checklist
624
+ ## Checklist
410
625
 
411
- - [ ] `npm install @swirepay/sparo-embed-sdk`
412
- - [ ] `REACT_APP_SPARO_DOMAIN` set per environment
413
- - [ ] Backend `/sparo/token` implemented and tested
414
- - [ ] `SparoChat` component with `useEffect` + `unmount` cleanup
415
- - [ ] Route registered (e.g. `/sparo`)
416
- - [ ] User has access to enabled merchant
417
- - [ ] Dev server restarted after install
626
+ - [ ] `yarn add @swirepay-developer/sparo-embed-sdk`
627
+ - [ ] Env vars set (`REACT_APP_SPARO_GUEST_TOKEN_URL`, `REACT_APP_SPARO_DOMAIN`)
628
+ - [ ] `getGatewayAccessToken` wired in `src/utils/sparoAuth.js`
629
+ - [ ] `SparoChat` uses `embed` + `createGuestTokenFetcher`
630
+ - [ ] `useEffect` cleanup calls `handle.unmount()`
631
+ - [ ] Route `/sparo` registered
632
+ - [ ] Dev server restarted after install / env changes
418
633
 
419
634
  ---
420
635
 
421
636
  ## Related docs
422
637
 
423
- - [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md) — full architecture and backend mint examples
638
+ - [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md) — architecture and backend contract
639
+ - [examples/embed-vanilla.html](./examples/embed-vanilla.html) — vanilla JS example (no React)
424
640
  - [INSTALL.md](./INSTALL.md) — npm install troubleshooting
425
- - [SECURITY.md](./SECURITY.md) — trust boundaries and secrets
426
-
427
- ---
428
-
429
- ## Support contacts
430
-
431
- | Issue | Contact |
432
- |-------|---------|
433
- | SDK npm / import errors | Frontend platform / SDK maintainers |
434
- | `/sparo/token` / `SPARO_ADMIN_KEY` | Backend team |
435
- | Merchant allowlist | SPARO admin |
641
+ - [SECURITY.md](./SECURITY.md) — trust boundaries