@swirepay-developer/sparo-embed-sdk 1.0.5 → 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.
- package/CHANGELOG.md +15 -0
- package/GATEWAY-REACT-GUIDE.md +414 -270
- package/README.md +26 -10
- package/SPARO-EMBEDDING.md +57 -28
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/sparo-embed-sdk.global.js +1 -1
- package/package.json +1 -1
- package/types/index.d.ts +16 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.7
|
|
4
|
+
|
|
5
|
+
- `createGuestTokenFetcher` calls gateway Java API `GET /v1/sparo/guest-token` with `Authorization: Bearer <gateway-jwt>`.
|
|
6
|
+
- Supports wrapped responses `{ data: { token, expiresIn, account } }`.
|
|
7
|
+
- `getAuthorization` callback for dynamic Bearer token on each refresh.
|
|
8
|
+
- URLs are **host-configured** (staging vs prod) — not hardcoded in SDK.
|
|
9
|
+
|
|
10
|
+
## 1.0.6
|
|
11
|
+
|
|
12
|
+
- Add `createGuestTokenFetcher('/sparo/token')` helper for Java/gateway session cookie flow (Superset-style).
|
|
13
|
+
- Preserve `err.code` from BFF (`merchant_not_enabled`, `invalid_token`, etc.) in `onError`.
|
|
14
|
+
- Auto-refresh on iframe `expired_token` postMessage.
|
|
15
|
+
- `iframe_load_failed` on iframe element error.
|
|
16
|
+
- Example: `examples/embed-vanilla.html`.
|
|
17
|
+
|
|
3
18
|
## 1.0.5
|
|
4
19
|
|
|
5
20
|
- Fix DevOps publish: rename `eslint.config.js` → `eslint.config.mjs` and `vitest.config.js` → `vitest.config.mjs` (ESM configs without `"type": "module"` on package).
|
package/GATEWAY-REACT-GUIDE.md
CHANGED
|
@@ -1,162 +1,296 @@
|
|
|
1
1
|
# Gateway Frontend — SPARO SDK Integration Guide (React)
|
|
2
2
|
|
|
3
|
-
Step-by-step guide for **gateway-frontend**
|
|
3
|
+
Step-by-step guide for **gateway-frontend** developers integrating `@swirepay-developer/sparo-embed-sdk`.
|
|
4
4
|
|
|
5
|
-
> **Prerequisite:** DevOps
|
|
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
|
-
> ### Wrong package name (most common after publish)
|
|
9
|
-
>
|
|
10
|
-
> npm package is **`@swirepay-developer/sparo-embed-sdk`** (scope `swirepay-developer`).
|
|
11
|
-
> If your code imports **`@swirepay/sparo-embed-sdk`** (no `-developer`), webpack will always show **Module not found** even after `npm install` and cache clear.
|
|
12
|
-
>
|
|
13
|
-
> **Fix:** change import + `package.json` dependency to `@swirepay-developer/sparo-embed-sdk` (see Step 1).
|
|
14
|
-
>
|
|
15
|
-
> **`Module not found`** with the correct name usually means not installed — run `npm view @swirepay-developer/sparo-embed-sdk version` (DevOps screenshot should show `1.0.5`).
|
|
16
7
|
|
|
17
8
|
---
|
|
18
9
|
|
|
19
|
-
##
|
|
10
|
+
## How to use the SDK (overview)
|
|
20
11
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
→ 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';
|
|
29
19
|
```
|
|
30
20
|
|
|
31
|
-
|
|
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()` |
|
|
32
25
|
|
|
33
|
-
|
|
26
|
+
**Minimum working integration:**
|
|
27
|
+
|
|
28
|
+
```jsx
|
|
29
|
+
import { useEffect, useRef } from 'react';
|
|
30
|
+
import { embed, createGuestTokenFetcher } from '@swirepay-developer/sparo-embed-sdk';
|
|
34
31
|
|
|
35
|
-
|
|
32
|
+
function SparoChat() {
|
|
33
|
+
const mountRef = useRef(null);
|
|
36
34
|
|
|
37
|
-
|
|
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
|
+
});
|
|
38
49
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
50
|
+
return () => handle.unmount();
|
|
51
|
+
}, []);
|
|
52
|
+
|
|
53
|
+
return <div ref={mountRef} style={{ width: '100%', height: 720 }} />;
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
You must provide:
|
|
58
|
+
|
|
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 }`
|
|
46
62
|
|
|
47
63
|
---
|
|
48
64
|
|
|
49
|
-
##
|
|
65
|
+
## Architecture
|
|
50
66
|
|
|
51
|
-
|
|
67
|
+
Same pattern as **Apache Superset embedded analytics**: React SDK + backend guest-token API + embedded app iframe.
|
|
52
68
|
|
|
53
|
-
```
|
|
54
|
-
|
|
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
|
|
55
78
|
```
|
|
56
79
|
|
|
57
|
-
|
|
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
|
+
```
|
|
58
89
|
|
|
59
90
|
```json
|
|
60
91
|
{
|
|
61
92
|
"dependencies": {
|
|
62
|
-
"@swirepay-developer/sparo-embed-sdk": "^1.0.
|
|
93
|
+
"@swirepay-developer/sparo-embed-sdk": "^1.0.7"
|
|
63
94
|
}
|
|
64
95
|
}
|
|
65
96
|
```
|
|
66
97
|
|
|
67
|
-
|
|
98
|
+
Verify:
|
|
68
99
|
|
|
69
100
|
```bash
|
|
70
|
-
|
|
101
|
+
yarn why @swirepay-developer/sparo-embed-sdk
|
|
71
102
|
```
|
|
72
103
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
```bash
|
|
76
|
-
npm ls @swirepay-developer/sparo-embed-sdk
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
You should see the package listed. If not:
|
|
80
|
-
|
|
81
|
-
- Add `.npmrc` with `@swirepay-developer:registry` (see [.npmrc.example](../.npmrc.example)) and `npm login` if needed
|
|
82
|
-
- Remove any old `"file:..."` path dependency for this package
|
|
83
|
-
- Delete `node_modules` and `package-lock.json`, then `npm install` again
|
|
104
|
+
**Package name:** `@swirepay-developer/sparo-embed-sdk` (not `@swirepay/sparo-embed-sdk`).
|
|
84
105
|
|
|
85
106
|
---
|
|
86
107
|
|
|
87
|
-
## Step 2 — Environment variables
|
|
108
|
+
## Step 2 — Environment variables
|
|
88
109
|
|
|
89
|
-
|
|
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` |
|
|
90
114
|
|
|
91
|
-
|
|
115
|
+
`.env.development`:
|
|
92
116
|
|
|
93
117
|
```env
|
|
94
|
-
|
|
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
|
|
95
120
|
```
|
|
96
121
|
|
|
97
|
-
|
|
122
|
+
`.env.production`:
|
|
98
123
|
|
|
99
124
|
```env
|
|
125
|
+
REACT_APP_SPARO_GUEST_TOKEN_URL=https://backend.swirepay.com/v1/sparo/guest-token
|
|
100
126
|
REACT_APP_SPARO_DOMAIN=https://sparo.swirepay.com
|
|
101
127
|
```
|
|
102
128
|
|
|
103
|
-
|
|
104
|
-
`sparoDomain` must match the environment your **backend** uses when minting tokens.
|
|
129
|
+
Restart the dev server after changing env vars.
|
|
105
130
|
|
|
106
131
|
---
|
|
107
132
|
|
|
108
|
-
## Step 3 —
|
|
133
|
+
## Step 3 — Recommended file layout
|
|
109
134
|
|
|
110
|
-
|
|
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
|
+
```
|
|
111
144
|
|
|
112
|
-
|
|
145
|
+
---
|
|
113
146
|
|
|
114
|
-
|
|
147
|
+
## Code samples
|
|
115
148
|
|
|
116
|
-
|
|
149
|
+
### Sample 1 — `createGuestTokenFetcher` (recommended)
|
|
117
150
|
|
|
118
|
-
|
|
119
|
-
- `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**.
|
|
120
152
|
|
|
121
|
-
|
|
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
|
+
```
|
|
122
167
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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;
|
|
128
193
|
}
|
|
129
194
|
```
|
|
130
195
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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
|
+
```
|
|
136
207
|
|
|
137
|
-
**
|
|
208
|
+
**Option C — AWS Amplify (if gateway uses Cognito directly):**
|
|
138
209
|
|
|
139
|
-
|
|
210
|
+
```js
|
|
211
|
+
import { fetchAuthSession } from 'aws-amplify/auth';
|
|
140
212
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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
|
+
```
|
|
147
220
|
|
|
148
221
|
---
|
|
149
222
|
|
|
150
|
-
|
|
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
|
+
);
|
|
151
244
|
|
|
152
|
-
|
|
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
|
+
```
|
|
267
|
+
|
|
268
|
+
Or import the SDK normalizer:
|
|
269
|
+
|
|
270
|
+
```js
|
|
271
|
+
import { normalizeGuestTokenResponse } from '@swirepay-developer/sparo-embed-sdk';
|
|
272
|
+
|
|
273
|
+
const { data } = await axios.get(url, { headers: { Authorization: `Bearer ${token}` } });
|
|
274
|
+
return normalizeGuestTokenResponse(data);
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
---
|
|
278
|
+
|
|
279
|
+
### Sample 4 — Full `SparoChat` component (copy-paste ready)
|
|
280
|
+
|
|
281
|
+
Create `src/routes/SparoChat/index.js`:
|
|
153
282
|
|
|
154
283
|
```jsx
|
|
155
284
|
import React, { useEffect, useRef, useState } from 'react';
|
|
156
285
|
import { Alert, Spin } from 'antd';
|
|
157
|
-
import {
|
|
286
|
+
import {
|
|
287
|
+
embed,
|
|
288
|
+
createGuestTokenFetcher,
|
|
289
|
+
} from '@swirepay-developer/sparo-embed-sdk';
|
|
290
|
+
import { getGatewayAccessToken } from 'utils/sparoAuth';
|
|
158
291
|
|
|
159
|
-
const SPARO_DOMAIN = process.env.REACT_APP_SPARO_DOMAIN
|
|
292
|
+
const SPARO_DOMAIN = process.env.REACT_APP_SPARO_DOMAIN;
|
|
293
|
+
const GUEST_TOKEN_URL = process.env.REACT_APP_SPARO_GUEST_TOKEN_URL;
|
|
160
294
|
|
|
161
295
|
function SparoChat() {
|
|
162
296
|
const mountRef = useRef(null);
|
|
@@ -175,73 +309,60 @@ function SparoChat() {
|
|
|
175
309
|
id: 'sparo-chat',
|
|
176
310
|
sparoDomain: SPARO_DOMAIN,
|
|
177
311
|
mountPoint: mountElement,
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
window.location.href = '/login';
|
|
185
|
-
throw new Error('Unauthorized');
|
|
186
|
-
}
|
|
187
|
-
const payload = await response.json();
|
|
188
|
-
if (!response.ok) {
|
|
189
|
-
const apiError = new Error(
|
|
190
|
-
payload?.message || payload?.error || 'Unable to fetch SPARO token',
|
|
191
|
-
);
|
|
192
|
-
apiError.code = payload?.code || 'fetch_failed';
|
|
193
|
-
throw apiError;
|
|
194
|
-
}
|
|
195
|
-
return payload; // { token, expiresIn, account }
|
|
196
|
-
},
|
|
312
|
+
|
|
313
|
+
// SDK calls Java API with Bearer JWT on mount + each refresh
|
|
314
|
+
fetchGuestToken: createGuestTokenFetcher(GUEST_TOKEN_URL, {
|
|
315
|
+
getAuthorization: getGatewayAccessToken,
|
|
316
|
+
}),
|
|
317
|
+
|
|
197
318
|
uiConfig: {
|
|
198
319
|
theme: 'light',
|
|
199
320
|
showWelcome: true,
|
|
200
321
|
showSuggestions: true,
|
|
201
322
|
hideSidebar: false,
|
|
202
323
|
},
|
|
203
|
-
|
|
324
|
+
|
|
325
|
+
onReady: () => {
|
|
326
|
+
setLoading(false);
|
|
327
|
+
},
|
|
328
|
+
|
|
204
329
|
onError: (err) => {
|
|
205
|
-
console.error('[SPARO]', err);
|
|
330
|
+
console.error('[SPARO]', err.code, err.message);
|
|
206
331
|
setLoading(false);
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
break;
|
|
217
|
-
case 'iframe_load_failed':
|
|
218
|
-
setError('Unable to load SPARO assistant.');
|
|
219
|
-
break;
|
|
220
|
-
default:
|
|
221
|
-
setError(err?.message || 'Failed to initialize SPARO.');
|
|
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.');
|
|
222
341
|
}
|
|
223
342
|
},
|
|
224
343
|
});
|
|
225
344
|
|
|
345
|
+
// Required: tear down iframe + timers when user leaves the page
|
|
226
346
|
return () => {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
handleRef.current = null;
|
|
230
|
-
}
|
|
347
|
+
handleRef.current?.unmount();
|
|
348
|
+
handleRef.current = null;
|
|
231
349
|
};
|
|
232
350
|
}, []);
|
|
233
351
|
|
|
234
352
|
return (
|
|
235
353
|
<div style={{ padding: 20 }}>
|
|
236
354
|
<h2>SPARO Assistant</h2>
|
|
355
|
+
|
|
237
356
|
{loading && (
|
|
238
357
|
<div style={{ marginBottom: 16, textAlign: 'center' }}>
|
|
239
358
|
<Spin size="large" />
|
|
240
359
|
</div>
|
|
241
360
|
)}
|
|
361
|
+
|
|
242
362
|
{error && (
|
|
243
363
|
<Alert type="error" showIcon message={error} style={{ marginBottom: 16 }} />
|
|
244
364
|
)}
|
|
365
|
+
|
|
245
366
|
<div
|
|
246
367
|
ref={mountRef}
|
|
247
368
|
style={{
|
|
@@ -260,238 +381,261 @@ function SparoChat() {
|
|
|
260
381
|
export default SparoChat;
|
|
261
382
|
```
|
|
262
383
|
|
|
263
|
-
|
|
384
|
+
---
|
|
264
385
|
|
|
265
|
-
|
|
386
|
+
### Sample 5 — `embed()` options explained
|
|
266
387
|
|
|
267
388
|
```js
|
|
268
|
-
|
|
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
|
+
```
|
|
410
|
+
|
|
411
|
+
**`fetchGuestToken` return shape** (Java API must return this):
|
|
269
412
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
413
|
+
```js
|
|
414
|
+
{
|
|
415
|
+
token: 'eyJhbGciOi...', // SPARO guest JWT
|
|
416
|
+
expiresIn: 900, // seconds until expiry
|
|
417
|
+
account: 'account-72ec92...', // merchant account GID
|
|
418
|
+
}
|
|
274
419
|
```
|
|
275
420
|
|
|
276
421
|
---
|
|
277
422
|
|
|
278
|
-
|
|
423
|
+
### Sample 6 — Register route
|
|
279
424
|
|
|
280
|
-
|
|
425
|
+
React Router v5 (gateway pattern):
|
|
281
426
|
|
|
282
427
|
```js
|
|
283
428
|
import SparoChat from 'routes/SparoChat';
|
|
284
429
|
|
|
285
|
-
// In routes array:
|
|
430
|
+
// In your routes array:
|
|
286
431
|
{
|
|
287
432
|
key: 'sparo',
|
|
288
433
|
path: '/sparo',
|
|
289
434
|
exact: true,
|
|
290
435
|
protected: true,
|
|
291
436
|
component: SparoChat,
|
|
292
|
-
allowedRoles: [
|
|
437
|
+
allowedRoles: ['MERCHANT_ADMIN', 'MERCHANT_USER'],
|
|
293
438
|
}
|
|
294
439
|
```
|
|
295
440
|
|
|
296
|
-
|
|
441
|
+
Nav link example:
|
|
297
442
|
|
|
298
|
-
|
|
443
|
+
```jsx
|
|
444
|
+
import { Link } from 'react-router-dom';
|
|
299
445
|
|
|
300
|
-
|
|
301
|
-
npm start
|
|
446
|
+
<Link to="/sparo">SPARO Assistant</Link>
|
|
302
447
|
```
|
|
303
448
|
|
|
304
449
|
---
|
|
305
450
|
|
|
306
|
-
|
|
451
|
+
### Sample 7 — TypeScript (optional)
|
|
307
452
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
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';
|
|
316
462
|
|
|
317
|
-
|
|
463
|
+
export function SparoChat(): JSX.Element {
|
|
464
|
+
const mountRef = useRef<HTMLDivElement>(null);
|
|
465
|
+
const handleRef = useRef<EmbedHandle | null>(null);
|
|
318
466
|
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
| Production | `https://sparo.swirepay.com` (or prod host) | Production SPARO API |
|
|
467
|
+
useEffect(() => {
|
|
468
|
+
const el = mountRef.current;
|
|
469
|
+
if (!el) return undefined;
|
|
323
470
|
|
|
324
|
-
|
|
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
|
+
});
|
|
482
|
+
|
|
483
|
+
return () => handleRef.current?.unmount();
|
|
484
|
+
}, []);
|
|
485
|
+
|
|
486
|
+
return <div ref={mountRef} style={{ width: '100%', height: 720 }} />;
|
|
487
|
+
}
|
|
488
|
+
```
|
|
325
489
|
|
|
326
490
|
---
|
|
327
491
|
|
|
328
|
-
|
|
492
|
+
### Sample 8 — Manual refresh button (optional)
|
|
329
493
|
|
|
330
|
-
|
|
494
|
+
The SDK auto-refreshes ~30s before expiry. Use this only if you need a user-triggered refresh:
|
|
331
495
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
| `sparoDomain` | Yes | SPARO host, e.g. `https://sparo.swirepay.com` |
|
|
335
|
-
| `mountPoint` | Yes | DOM element (use `ref.current`) |
|
|
336
|
-
| `fetchGuestToken` | Yes | Async function returning `{ token, expiresIn, account }` |
|
|
337
|
-
| `id` | No | iframe id (default `sparo-embed`) |
|
|
338
|
-
| `uiConfig` | No | Theme and UI flags (see below) |
|
|
339
|
-
| `onReady` | No | Called when iframe signals ready |
|
|
340
|
-
| `onError` | No | Called on token/iframe errors |
|
|
496
|
+
```jsx
|
|
497
|
+
const handleRef = useRef(null);
|
|
341
498
|
|
|
342
|
-
|
|
499
|
+
// inside embed setup:
|
|
500
|
+
handleRef.current = embed({ ... });
|
|
343
501
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
502
|
+
// in JSX:
|
|
503
|
+
<button
|
|
504
|
+
type="button"
|
|
505
|
+
onClick={() => handleRef.current?.refresh()}
|
|
506
|
+
>
|
|
507
|
+
Refresh SPARO session
|
|
508
|
+
</button>
|
|
351
509
|
```
|
|
352
510
|
|
|
353
|
-
|
|
511
|
+
---
|
|
354
512
|
|
|
355
|
-
|
|
356
|
-
const handle = embed({ ... });
|
|
513
|
+
## Backend API contract
|
|
357
514
|
|
|
358
|
-
|
|
359
|
-
|
|
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
|
|
360
521
|
```
|
|
361
522
|
|
|
362
|
-
|
|
523
|
+
**Response `200`:**
|
|
363
524
|
|
|
364
|
-
|
|
525
|
+
```json
|
|
526
|
+
{
|
|
527
|
+
"token": "eyJhbGciOi...",
|
|
528
|
+
"expiresIn": 900,
|
|
529
|
+
"account": "account-72ec92..."
|
|
530
|
+
}
|
|
531
|
+
```
|
|
365
532
|
|
|
366
|
-
|
|
533
|
+
Wrapped responses (`{ "data": { ... } }`) are handled automatically by `createGuestTokenFetcher`.
|
|
367
534
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
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 |
|
|
374
541
|
|
|
375
542
|
---
|
|
376
543
|
|
|
377
|
-
##
|
|
544
|
+
## Test locally
|
|
378
545
|
|
|
379
|
-
|
|
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.
|
|
380
551
|
|
|
381
|
-
|
|
552
|
+
```bash
|
|
553
|
+
yarn start
|
|
554
|
+
```
|
|
382
555
|
|
|
383
|
-
|
|
556
|
+
---
|
|
557
|
+
|
|
558
|
+
## SDK exports reference
|
|
384
559
|
|
|
385
560
|
```js
|
|
386
|
-
|
|
387
|
-
|
|
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';
|
|
388
566
|
```
|
|
389
567
|
|
|
390
|
-
|
|
391
|
-
// package.json
|
|
392
|
-
"@swirepay-developer/sparo-embed-sdk": "^1.0.5"
|
|
393
|
-
```
|
|
568
|
+
### Error codes (`onError`)
|
|
394
569
|
|
|
395
|
-
|
|
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 |
|
|
396
578
|
|
|
397
|
-
|
|
398
|
-
npm uninstall @swirepay/sparo-embed-sdk
|
|
399
|
-
npm install @swirepay-developer/sparo-embed-sdk
|
|
400
|
-
npm start
|
|
401
|
-
```
|
|
579
|
+
---
|
|
402
580
|
|
|
403
|
-
|
|
581
|
+
## Security checklist
|
|
404
582
|
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
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).
|
|
408
588
|
|
|
409
589
|
---
|
|
410
590
|
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
Webpack shows this when the package is **not installed** under `node_modules` (install failed or was never run).
|
|
591
|
+
## Troubleshooting
|
|
414
592
|
|
|
415
|
-
|
|
593
|
+
### `Module not found: Can't resolve '@swirepay/sparo-embed-sdk'`
|
|
416
594
|
|
|
417
|
-
|
|
595
|
+
Wrong scope. Use `@swirepay-developer/sparo-embed-sdk`:
|
|
418
596
|
|
|
419
597
|
```bash
|
|
420
|
-
|
|
598
|
+
yarn add @swirepay-developer/sparo-embed-sdk
|
|
421
599
|
```
|
|
422
600
|
|
|
423
|
-
|
|
424
|
-
|--------|---------|
|
|
425
|
-
| `1.0.5` (or similar) | Published — go to Step 1 |
|
|
426
|
-
| `404 Not Found` | **Not on registry.npmjs.org** (or wrong scope/name). `npm install` will not add the package → this error persists |
|
|
427
|
-
|
|
428
|
-
If you see **404**, DevOps has not published yet (or gateway lacks npm read access to `@swirepay-developer`). Do not merge gateway code that imports the SDK until `npm view` returns a version.
|
|
429
|
-
|
|
430
|
-
**Step 1 — install and confirm**
|
|
601
|
+
### `Module not found: Can't resolve '@swirepay-developer/sparo-embed-sdk'`
|
|
431
602
|
|
|
432
603
|
```bash
|
|
433
|
-
|
|
434
|
-
npm install @swirepay-developer/sparo-embed-sdk
|
|
435
|
-
dir node_modules\@swirepay-developer\sparo-embed-sdk\dist
|
|
604
|
+
npm view @swirepay-developer/sparo-embed-sdk version
|
|
436
605
|
```
|
|
437
606
|
|
|
438
|
-
|
|
607
|
+
If version prints, run `yarn add` and restart dev server. If `404`, SDK not published yet.
|
|
439
608
|
|
|
440
|
-
|
|
609
|
+
### Guest-token returns HTML / 404
|
|
441
610
|
|
|
442
|
-
|
|
443
|
-
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.
|
|
611
|
+
Wrong `REACT_APP_SPARO_GUEST_TOKEN_URL` — must be Java API URL, not a React route.
|
|
444
612
|
|
|
445
|
-
### Blank iframe
|
|
613
|
+
### Blank iframe
|
|
446
614
|
|
|
447
|
-
-
|
|
448
|
-
-
|
|
449
|
-
- Confirm `sparoDomain` matches token mint environment (HTTPS in prod).
|
|
450
|
-
|
|
451
|
-
### Mixed content blocked
|
|
452
|
-
|
|
453
|
-
- Page is `https://` but `sparoDomain` is `http://` → use HTTPS SPARO URL.
|
|
454
|
-
|
|
455
|
-
### `merchant_not_enabled` (403)
|
|
456
|
-
|
|
457
|
-
- Merchant not on SPARO allowlist — contact SPARO admin, not a frontend bug.
|
|
458
|
-
|
|
459
|
-
### `fetch_failed`
|
|
460
|
-
|
|
461
|
-
- Backend down, CORS issue, or user session expired.
|
|
462
|
-
- 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).
|
|
463
617
|
|
|
464
618
|
### Iframe works on refresh but not first load
|
|
465
619
|
|
|
466
|
-
|
|
467
|
-
- Do not call `embed` with `null` mount point.
|
|
620
|
+
Call `embed` inside `useEffect` after `mountRef.current` is set.
|
|
468
621
|
|
|
469
622
|
---
|
|
470
623
|
|
|
471
|
-
##
|
|
624
|
+
## Checklist
|
|
472
625
|
|
|
473
|
-
- [ ] `
|
|
474
|
-
- [ ]
|
|
475
|
-
- [ ]
|
|
476
|
-
- [ ] `SparoChat`
|
|
477
|
-
- [ ]
|
|
478
|
-
- [ ]
|
|
479
|
-
- [ ] 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
|
|
480
633
|
|
|
481
634
|
---
|
|
482
635
|
|
|
483
636
|
## Related docs
|
|
484
637
|
|
|
485
|
-
- [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md) —
|
|
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)
|
|
486
640
|
- [INSTALL.md](./INSTALL.md) — npm install troubleshooting
|
|
487
|
-
- [SECURITY.md](./SECURITY.md) — trust boundaries
|
|
488
|
-
|
|
489
|
-
---
|
|
490
|
-
|
|
491
|
-
## Support contacts
|
|
492
|
-
|
|
493
|
-
| Issue | Contact |
|
|
494
|
-
|-------|---------|
|
|
495
|
-
| SDK npm / import errors | Frontend platform / SDK maintainers |
|
|
496
|
-
| `/sparo/token` / `SPARO_ADMIN_KEY` | Backend team |
|
|
497
|
-
| Merchant allowlist | SPARO admin |
|
|
641
|
+
- [SECURITY.md](./SECURITY.md) — trust boundaries
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|------|--------|
|
|
13
13
|
| **You (SDK)** | Push this repo to Bitbucket (`sdkmaster` or release branch). Bump version in `package.json` for each release. |
|
|
14
14
|
| **DevOps** | Clone repo → `npm ci` → `npm publish`. See **[DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md)**. |
|
|
15
|
-
| **Gateway developer** |
|
|
15
|
+
| **Gateway developer** | SDK: [GATEWAY-REACT-GUIDE.md](./GATEWAY-REACT-GUIDE.md) · Middleware: [../sparo-key-backend](../sparo-key-backend) |
|
|
16
16
|
|
|
17
17
|
Until DevOps publishes, gateway will show:
|
|
18
18
|
|
|
@@ -31,7 +31,7 @@ npm install @swirepay-developer/sparo-embed-sdk
|
|
|
31
31
|
```json
|
|
32
32
|
{
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@swirepay-developer/sparo-embed-sdk": "^1.0.
|
|
34
|
+
"@swirepay-developer/sparo-embed-sdk": "^1.0.7"
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
```
|
|
@@ -40,23 +40,39 @@ Private package: use [.npmrc.example](./.npmrc.example) with org `NPM_TOKEN` (De
|
|
|
40
40
|
|
|
41
41
|
---
|
|
42
42
|
|
|
43
|
-
## Quick Start
|
|
43
|
+
## Quick Start (Java guest-token API)
|
|
44
|
+
|
|
45
|
+
Gateway Java API (URLs from **host env**, not SDK):
|
|
46
|
+
|
|
47
|
+
| Environment | Guest-token URL |
|
|
48
|
+
|-------------|-----------------|
|
|
49
|
+
| Staging | `https://staging-backend.swirepay.com/v1/sparo/guest-token` |
|
|
50
|
+
| Production | `https://backend.swirepay.com/v1/sparo/guest-token` |
|
|
44
51
|
|
|
45
52
|
```js
|
|
46
|
-
import {
|
|
53
|
+
import {
|
|
54
|
+
embed,
|
|
55
|
+
createGuestTokenFetcher,
|
|
56
|
+
} from '@swirepay-developer/sparo-embed-sdk';
|
|
47
57
|
|
|
48
58
|
const handle = embed({
|
|
49
59
|
id: 'sparo-chat',
|
|
50
|
-
sparoDomain:
|
|
60
|
+
sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
|
|
51
61
|
mountPoint: document.getElementById('sparo'),
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
62
|
+
|
|
63
|
+
fetchGuestToken: createGuestTokenFetcher(
|
|
64
|
+
process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
|
|
65
|
+
{ getAuthorization: getGatewayBearerToken },
|
|
66
|
+
),
|
|
67
|
+
|
|
68
|
+
uiConfig: { theme: 'light' },
|
|
69
|
+
onReady: () => console.log('[Sparo] ready'),
|
|
70
|
+
onError: (err) => console.error('[Sparo]', err.code, err.message),
|
|
57
71
|
});
|
|
58
72
|
```
|
|
59
73
|
|
|
74
|
+
`getGatewayBearerToken()` returns the logged-in user's gateway JWT (same as other API calls).
|
|
75
|
+
|
|
60
76
|
---
|
|
61
77
|
|
|
62
78
|
## Docs
|
package/SPARO-EMBEDDING.md
CHANGED
|
@@ -7,12 +7,21 @@ Embed the SPARO assistant into your application with short-lived guest JWTs, no
|
|
|
7
7
|
|
|
8
8
|
## Architecture
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
Same pattern as **Apache Superset embedded analytics**:
|
|
11
|
+
|
|
12
|
+
| Role | Superset | SPARO |
|
|
13
|
+
|------|----------|-------|
|
|
14
|
+
| React SDK | `@superset-ui/embedded-sdk` | `@swirepay-developer/sparo-embed-sdk` |
|
|
15
|
+
| Guest-token middleware | `supersetmiddleware` | **`sparo-key-backend`** |
|
|
16
|
+
| Guest-token route | `POST /guest-token` | `POST /guest-token` |
|
|
17
|
+
| Embedded app | Superset UI URL | `sparoDomain` (e.g. `https://sparo-stag.swirepay.com`) |
|
|
18
|
+
|
|
19
|
+
1. User opens your page (gateway, Cognito session).
|
|
20
|
+
2. SDK calls `fetchGuestToken()` → **sparo-key-backend** `POST /guest-token` (Cognito Bearer).
|
|
21
|
+
3. Middleware loads `SPARO_ADMIN_KEY` from AWS Secrets Manager (`swirepay-sparoai/dev/backend-env`).
|
|
22
|
+
4. Middleware calls SPARO `POST /api/guest-token`.
|
|
23
|
+
5. SDK receives `{ token, expiresIn, account }`, loads iframe, `postMessage` auth.
|
|
24
|
+
6. SDK auto-refreshes before expiry.
|
|
16
25
|
|
|
17
26
|
## Prerequisites
|
|
18
27
|
|
|
@@ -21,34 +30,50 @@ Embed the SPARO assistant into your application with short-lived guest JWTs, no
|
|
|
21
30
|
- Merchant allowlisted in SPARO.
|
|
22
31
|
- Your backend endpoint that authenticates end users and returns guest token.
|
|
23
32
|
|
|
24
|
-
## Backend
|
|
33
|
+
## Backend — Java guest-token API
|
|
25
34
|
|
|
26
|
-
|
|
35
|
+
Gateway Java validates the user and mints the SPARO guest JWT.
|
|
27
36
|
|
|
28
|
-
|
|
29
|
-
-
|
|
30
|
-
|
|
37
|
+
```http
|
|
38
|
+
GET https://staging-backend.swirepay.com/v1/sparo/guest-token
|
|
39
|
+
Authorization: Bearer <gateway-session-jwt>
|
|
40
|
+
Accept: application/json
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Production: `https://backend.swirepay.com/v1/sparo/guest-token`
|
|
31
44
|
|
|
32
|
-
|
|
45
|
+
**Response** (direct or wrapped in `data`):
|
|
33
46
|
|
|
34
47
|
```json
|
|
35
48
|
{
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"ttl": 900
|
|
49
|
+
"token": "eyJhbGciOi...",
|
|
50
|
+
"expiresIn": 900,
|
|
51
|
+
"account": "account-72ec92..."
|
|
40
52
|
}
|
|
41
53
|
```
|
|
42
54
|
|
|
43
|
-
|
|
55
|
+
SDK usage:
|
|
44
56
|
|
|
45
|
-
```
|
|
46
|
-
{
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
57
|
+
```js
|
|
58
|
+
import { embed, createGuestTokenFetcher } from '@swirepay-developer/sparo-embed-sdk';
|
|
59
|
+
|
|
60
|
+
embed({
|
|
61
|
+
sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
|
|
62
|
+
mountPoint: document.getElementById('sparo'),
|
|
63
|
+
fetchGuestToken: createGuestTokenFetcher(
|
|
64
|
+
process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
|
|
65
|
+
{ getAuthorization: getGatewayBearerToken },
|
|
66
|
+
),
|
|
67
|
+
});
|
|
50
68
|
```
|
|
51
69
|
|
|
70
|
+
Two URLs (host config):
|
|
71
|
+
|
|
72
|
+
| Variable | Example |
|
|
73
|
+
|----------|---------|
|
|
74
|
+
| `REACT_APP_SPARO_GUEST_TOKEN_URL` | `https://staging-backend.swirepay.com/v1/sparo/guest-token` |
|
|
75
|
+
| `REACT_APP_SPARO_DOMAIN` | `https://sparo-stag.swirepay.com` |
|
|
76
|
+
|
|
52
77
|
## Frontend Integration
|
|
53
78
|
|
|
54
79
|
```html
|
|
@@ -56,20 +81,24 @@ Response:
|
|
|
56
81
|
```
|
|
57
82
|
|
|
58
83
|
```js
|
|
59
|
-
import {
|
|
84
|
+
import {
|
|
85
|
+
embed,
|
|
86
|
+
createGuestTokenFetcher,
|
|
87
|
+
} from '@swirepay-developer/sparo-embed-sdk';
|
|
60
88
|
|
|
61
89
|
const handle = embed({
|
|
62
90
|
id: 'sparo-chat',
|
|
63
91
|
sparoDomain: 'https://sparo.swirepay.com',
|
|
64
92
|
mountPoint: document.getElementById('sparo'),
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
},
|
|
93
|
+
|
|
94
|
+
// Java BFF: GET /sparo/token (credentials: include)
|
|
95
|
+
fetchGuestToken: createGuestTokenFetcher('/sparo/token'),
|
|
96
|
+
|
|
70
97
|
uiConfig: { theme: 'light' },
|
|
71
98
|
onReady: () => console.log('[Sparo] ready'),
|
|
72
99
|
onError: (err) => {
|
|
100
|
+
// err.code: merchant_not_enabled | invalid_token | expired_token |
|
|
101
|
+
// fetch_failed | iframe_load_failed
|
|
73
102
|
console.error('[Sparo]', err.code, err.message);
|
|
74
103
|
},
|
|
75
104
|
});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var I=(e,n)=>{for(var s in n)_(e,s,{get:n[s],enumerable:!0})},z=(e,n,s,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of M(n))!F.call(e,f)&&f!==s&&_(e,f,{get:()=>n[f],enumerable:!(r=D(n,f))||r.enumerable});return e};var N=e=>z(_({},"__esModule",{value:!0}),e);var U={};I(U,{createGuestTokenFetcher:()=>v,default:()=>G,embed:()=>y,normalizeGuestTokenResponse:()=>E});module.exports=N(U);function O(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function d(e,n,s){let r=new Error(n||e);return r.code=e,typeof s=="number"&&(r.status=s),r}function P(e){if(!e||typeof e!="object")throw d("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw d("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw d("invalid_token","Missing account in fetchGuestToken response");let n=Number(e.expiresIn||900);if(!Number.isFinite(n)||n<=0)throw d("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:n}}function H(e,n){let s=new URLSearchParams({embed:"true",account:n});return`${e}/embed.html?${s.toString()}`}function y(e){let{id:n="sparo-embed",sparoDomain:s,mountPoint:r,fetchGuestToken:f,uiConfig:g={},onReady:T,onError:m}=e||{};if(!r||!(r instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof f!="function")throw new Error("fetchGuestToken must be a function");let a=O(s),o=document.createElement("iframe");o.id=n,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let c=!0,u=!1,l=null,h=null,x=()=>{h&&(window.clearTimeout(h),h=null)},w=t=>{m&&m(b(t))},b=t=>t&&typeof t=="object"&&t.code?t:d("fetch_failed",(t==null?void 0:t.message)||"SPARO embed error"),R=()=>{if(!c||!u||!l)return;let t=o.contentWindow;!t||typeof t.postMessage!="function"||t.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:g},a)},L=t=>{x();let i=Math.max(5,t-30);h=window.setTimeout(()=>{k().catch(()=>{})},i*1e3)},k=async()=>{if(!c)return;let t;try{t=await f()}catch(j){let A=b(j);throw w(A),A}let i=P(t);l=i,L(i.expiresIn);let p=H(a,i.account);!o.src||o.src!==p?o.src=p:R()},S=t=>{if(!c||t.origin!==a)return;let i=t.data;if(!(!i||typeof i!="object"||typeof i.type!="string")){if(i.type==="sparo:ready"||i.type==="SPARO_EMBED_READY"){u=!0,R(),T&&T();return}if(i.type==="sparo:error"){let p=i.code||"iframe_error";if(p==="expired_token"){k().catch(()=>{});return}w(d(p,i.message||p,i.status))}}};return o.addEventListener("error",()=>{w(d("iframe_load_failed","Unable to load SPARO embed iframe"))}),window.addEventListener("message",S),r.innerHTML="",r.appendChild(o),k().catch(t=>{w(t)}),{refresh:()=>k(),unmount:()=>{c=!1,x(),window.removeEventListener("message",S),o.parentNode===r&&r.removeChild(o)}}}var G=y;function E(e){return!e||typeof e!="object"?e:e.data&&typeof e.data=="object"&&e.data.token?e.data:e.entity&&typeof e.entity=="object"&&e.entity.token?e.entity:e}function v(e,n={}){if(!e||typeof e!="string")throw new Error("createGuestTokenFetcher(tokenUrl) requires a URL string");let{getAuthorization:s,init:r={}}=n,f=r.method||"GET",g=r.credentials??(s?"omit":"include");return async function(){let m=new Headers(r.headers||{});if(s){let u=await s();u&&m.set("Authorization",u.startsWith("Bearer ")?u:`Bearer ${u}`)}m.has("Accept")||m.set("Accept","application/json");let a=await fetch(e,{...r,method:f,credentials:g,headers:m}),o=a.headers.get("content-type")||"",c={};if(o.includes("application/json")?c=await a.json().catch(()=>({})):a.ok||(c={message:(await a.text().catch(()=>"")).slice(0,200)||"Non-JSON error response"}),!a.ok){let u=E(c)||c,l=new Error(u.message||u.error||c.message||c.error||`token fetch failed (${a.status})`);throw l.code=u.code||c.code||(a.status===403?"merchant_not_enabled":a.status===401?"invalid_token":"fetch_failed"),l.status=a.status,l}return E(c)}}0&&(module.exports={createGuestTokenFetcher,embed,normalizeGuestTokenResponse});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function v(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function
|
|
1
|
+
function v(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function m(e,a,u){let r=new Error(a||e);return r.code=e,typeof u=="number"&&(r.status=u),r}function L(e){if(!e||typeof e!="object")throw m("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw m("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw m("invalid_token","Missing account in fetchGuestToken response");let a=Number(e.expiresIn||900);if(!Number.isFinite(a)||a<=0)throw m("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:a}}function j(e,a){let u=new URLSearchParams({embed:"true",account:a});return`${e}/embed.html?${u.toString()}`}function S(e){let{id:a="sparo-embed",sparoDomain:u,mountPoint:r,fetchGuestToken:p,uiConfig:E={},onReady:g,onError:l}=e||{};if(!r||!(r instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof p!="function")throw new Error("fetchGuestToken must be a function");let s=v(u),n=document.createElement("iframe");n.id=a,n.title="SPARO Assistant",n.style.width="100%",n.style.height="100%",n.style.border="0",n.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),n.setAttribute("referrerpolicy","no-referrer");let i=!0,c=!1,f=null,h=null,_=()=>{h&&(window.clearTimeout(h),h=null)},w=t=>{l&&l(y(t))},y=t=>t&&typeof t=="object"&&t.code?t:m("fetch_failed",(t==null?void 0:t.message)||"SPARO embed error"),x=()=>{if(!i||!c||!f)return;let t=n.contentWindow;!t||typeof t.postMessage!="function"||t.postMessage({type:"sparo:auth",token:f.token,account:f.account,uiConfig:E},s)},A=t=>{_();let o=Math.max(5,t-30);h=window.setTimeout(()=>{k().catch(()=>{})},o*1e3)},k=async()=>{if(!i)return;let t;try{t=await p()}catch(G){let R=y(G);throw w(R),R}let o=L(t);f=o,A(o.expiresIn);let d=j(s,o.account);!n.src||n.src!==d?n.src=d:x()},b=t=>{if(!i||t.origin!==s)return;let o=t.data;if(!(!o||typeof o!="object"||typeof o.type!="string")){if(o.type==="sparo:ready"||o.type==="SPARO_EMBED_READY"){c=!0,x(),g&&g();return}if(o.type==="sparo:error"){let d=o.code||"iframe_error";if(d==="expired_token"){k().catch(()=>{});return}w(m(d,o.message||d,o.status))}}};return n.addEventListener("error",()=>{w(m("iframe_load_failed","Unable to load SPARO embed iframe"))}),window.addEventListener("message",b),r.innerHTML="",r.appendChild(n),k().catch(t=>{w(t)}),{refresh:()=>k(),unmount:()=>{i=!1,_(),window.removeEventListener("message",b),n.parentNode===r&&r.removeChild(n)}}}var D=S;function T(e){return!e||typeof e!="object"?e:e.data&&typeof e.data=="object"&&e.data.token?e.data:e.entity&&typeof e.entity=="object"&&e.entity.token?e.entity:e}function M(e,a={}){if(!e||typeof e!="string")throw new Error("createGuestTokenFetcher(tokenUrl) requires a URL string");let{getAuthorization:u,init:r={}}=a,p=r.method||"GET",E=r.credentials??(u?"omit":"include");return async function(){let l=new Headers(r.headers||{});if(u){let c=await u();c&&l.set("Authorization",c.startsWith("Bearer ")?c:`Bearer ${c}`)}l.has("Accept")||l.set("Accept","application/json");let s=await fetch(e,{...r,method:p,credentials:E,headers:l}),n=s.headers.get("content-type")||"",i={};if(n.includes("application/json")?i=await s.json().catch(()=>({})):s.ok||(i={message:(await s.text().catch(()=>"")).slice(0,200)||"Non-JSON error response"}),!s.ok){let c=T(i)||i,f=new Error(c.message||c.error||i.message||i.error||`token fetch failed (${s.status})`);throw f.code=c.code||i.code||(s.status===403?"merchant_not_enabled":s.status===401?"invalid_token":"fetch_failed"),f.status=s.status,f}return T(i)}}export{M as createGuestTokenFetcher,D as default,S as embed,T as normalizeGuestTokenResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var SparoEmbedSDK=(()=>{var
|
|
1
|
+
var SparoEmbedSDK=(()=>{var _=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var s in t)_(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let f of M(t))!F.call(e,f)&&f!==s&&_(e,f,{get:()=>t[f],enumerable:!(r=D(t,f))||r.enumerable});return e};var N=e=>z(_({},"__esModule",{value:!0}),e);var U={};I(U,{createGuestTokenFetcher:()=>v,default:()=>G,embed:()=>y,normalizeGuestTokenResponse:()=>E});function O(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function d(e,t,s){let r=new Error(t||e);return r.code=e,typeof s=="number"&&(r.status=s),r}function P(e){if(!e||typeof e!="object")throw d("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw d("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw d("invalid_token","Missing account in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw d("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:t}}function H(e,t){let s=new URLSearchParams({embed:"true",account:t});return`${e}/embed.html?${s.toString()}`}function y(e){let{id:t="sparo-embed",sparoDomain:s,mountPoint:r,fetchGuestToken:f,uiConfig:g={},onReady:T,onError:m}=e||{};if(!r||!(r instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof f!="function")throw new Error("fetchGuestToken must be a function");let a=O(s),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let c=!0,u=!1,l=null,h=null,x=()=>{h&&(window.clearTimeout(h),h=null)},w=n=>{m&&m(b(n))},b=n=>n&&typeof n=="object"&&n.code?n:d("fetch_failed",n?.message||"SPARO embed error"),R=()=>{if(!c||!u||!l)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:g},a)},L=n=>{x();let i=Math.max(5,n-30);h=window.setTimeout(()=>{k().catch(()=>{})},i*1e3)},k=async()=>{if(!c)return;let n;try{n=await f()}catch(j){let A=b(j);throw w(A),A}let i=P(n);l=i,L(i.expiresIn);let p=H(a,i.account);!o.src||o.src!==p?o.src=p:R()},S=n=>{if(!c||n.origin!==a)return;let i=n.data;if(!(!i||typeof i!="object"||typeof i.type!="string")){if(i.type==="sparo:ready"||i.type==="SPARO_EMBED_READY"){u=!0,R(),T&&T();return}if(i.type==="sparo:error"){let p=i.code||"iframe_error";if(p==="expired_token"){k().catch(()=>{});return}w(d(p,i.message||p,i.status))}}};return o.addEventListener("error",()=>{w(d("iframe_load_failed","Unable to load SPARO embed iframe"))}),window.addEventListener("message",S),r.innerHTML="",r.appendChild(o),k().catch(n=>{w(n)}),{refresh:()=>k(),unmount:()=>{c=!1,x(),window.removeEventListener("message",S),o.parentNode===r&&r.removeChild(o)}}}var G=y;function E(e){return!e||typeof e!="object"?e:e.data&&typeof e.data=="object"&&e.data.token?e.data:e.entity&&typeof e.entity=="object"&&e.entity.token?e.entity:e}function v(e,t={}){if(!e||typeof e!="string")throw new Error("createGuestTokenFetcher(tokenUrl) requires a URL string");let{getAuthorization:s,init:r={}}=t,f=r.method||"GET",g=r.credentials??(s?"omit":"include");return async function(){let m=new Headers(r.headers||{});if(s){let u=await s();u&&m.set("Authorization",u.startsWith("Bearer ")?u:`Bearer ${u}`)}m.has("Accept")||m.set("Accept","application/json");let a=await fetch(e,{...r,method:f,credentials:g,headers:m}),o=a.headers.get("content-type")||"",c={};if(o.includes("application/json")?c=await a.json().catch(()=>({})):a.ok||(c={message:(await a.text().catch(()=>"")).slice(0,200)||"Non-JSON error response"}),!a.ok){let u=E(c)||c,l=new Error(u.message||u.error||c.message||c.error||`token fetch failed (${a.status})`);throw l.code=u.code||c.code||(a.status===403?"merchant_not_enabled":a.status===401?"invalid_token":"fetch_failed"),l.status=a.status,l}return E(c)}}return N(U);})();
|
package/package.json
CHANGED
package/types/index.d.ts
CHANGED
|
@@ -44,5 +44,21 @@ export type EmbedHandle = {
|
|
|
44
44
|
};
|
|
45
45
|
|
|
46
46
|
export declare function embed(options: EmbedOptions): EmbedHandle;
|
|
47
|
+
|
|
48
|
+
export type CreateGuestTokenFetcherOptions = {
|
|
49
|
+
/** Returns gateway session JWT (called on mount and each SDK refresh). */
|
|
50
|
+
getAuthorization?: () => string | Promise<string>;
|
|
51
|
+
init?: RequestInit;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export declare function normalizeGuestTokenResponse(
|
|
55
|
+
body: unknown,
|
|
56
|
+
): GuestTokenResponse;
|
|
57
|
+
|
|
58
|
+
export declare function createGuestTokenFetcher(
|
|
59
|
+
tokenUrl: string,
|
|
60
|
+
options?: CreateGuestTokenFetcherOptions,
|
|
61
|
+
): () => Promise<GuestTokenResponse>;
|
|
62
|
+
|
|
47
63
|
export default embed;
|
|
48
64
|
|