@tranzakpackage/cards-react-native 0.0.0-stage → 2.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/README.md +10 -2
- package/package.json +18 -4
- package/src/TranzakCardView.js +231 -0
- package/src/api.js +82 -0
- package/src/index.d.ts +23 -0
- package/src/index.js +2 -0
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Tranzak Cards - React Native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A native card component for React Native (no WebView).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @tranzakpackage/cards-react-native
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Full documentation and API reference: https://docs.tranzak.co (Cards section).
|
|
10
|
+
|
|
11
|
+
Proprietary software of Lomotec LLC. All rights reserved.
|
package/package.json
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tranzakpackage/cards-react-native",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Tranzak Cards for React Native: a native card component, no WebView.",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"types": "src/index.d.ts",
|
|
7
|
+
"peerDependencies": {
|
|
8
|
+
"react": ">=17",
|
|
9
|
+
"react-native": ">=0.70"
|
|
10
|
+
},
|
|
11
|
+
"license": "UNLICENSED",
|
|
12
|
+
"files": [
|
|
13
|
+
"src",
|
|
14
|
+
"README.md"
|
|
15
|
+
],
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://docs.tranzak.co"
|
|
20
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { createElement as h, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
2
|
+
import { ActivityIndicator, AppState, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
|
|
3
|
+
import { createCardsApi, errorText } from './api.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Carte virtuelle affichée NATIVEMENT dans votre écran (React Native) : aucune WebView, aucune page ouverte.
|
|
7
|
+
*
|
|
8
|
+
* <TranzakCardView apiBase={session.api_base} sessionSecret={session.session_secret} onFrozen={refresh} />
|
|
9
|
+
*
|
|
10
|
+
* Design noir et blanc (carte blanche, bordure et texte noirs) ; le thème « dark » du serveur inverse le noir et le blanc.
|
|
11
|
+
* Tout est dimensionné sur la largeur disponible. Les détails (numéro, CVC, expiration) ne sont gardés en mémoire que le
|
|
12
|
+
* temps de l'affichage, puis effacés, et dès que l'application quitte le premier plan. Activez le drapeau « écran sécurisé »
|
|
13
|
+
* de votre application sur l'écran qui affiche ce composant.
|
|
14
|
+
*/
|
|
15
|
+
export function TranzakCardView({ apiBase, sessionSecret, api: apiProp, onReady, onFrozen, onUnfrozen, onError, minFeedbackMs = 600 }) {
|
|
16
|
+
const api = useMemo(() => apiProp || createCardsApi({ apiBase, sessionSecret }), [apiProp, apiBase, sessionSecret]);
|
|
17
|
+
const handlers = useRef({});
|
|
18
|
+
handlers.current = { onReady, onFrozen, onUnfrozen, onError };
|
|
19
|
+
|
|
20
|
+
const [phase, setPhase] = useState('loading'); // loading | ready | failed
|
|
21
|
+
const [state, setState] = useState(null);
|
|
22
|
+
const [details, setDetails] = useState(null);
|
|
23
|
+
const [secondsLeft, setSecondsLeft] = useState(0);
|
|
24
|
+
const [busy, setBusy] = useState(null); // libellé de l'action en cours
|
|
25
|
+
const [revealing, setRevealing] = useState(false);
|
|
26
|
+
const [showPin, setShowPin] = useState(false);
|
|
27
|
+
const [message, setMessage] = useState(null);
|
|
28
|
+
const [pin1, setPin1] = useState('');
|
|
29
|
+
const [pin2, setPin2] = useState('');
|
|
30
|
+
const [width, setWidth] = useState(360);
|
|
31
|
+
const [pulse, setPulse] = useState(0);
|
|
32
|
+
|
|
33
|
+
const busyRef = useRef(false); // verrou SYNCHRONE : deux appuis dans le même instant ne passent pas tous les deux
|
|
34
|
+
const mounted = useRef(true);
|
|
35
|
+
const timer = useRef(null);
|
|
36
|
+
useEffect(() => () => { mounted.current = false; clearInterval(timer.current); }, []);
|
|
37
|
+
|
|
38
|
+
// Pulsation du squelette et de la barre de progression.
|
|
39
|
+
useEffect(() => {
|
|
40
|
+
if (phase === 'ready' && !busy) return undefined;
|
|
41
|
+
const t = setInterval(() => setPulse((p) => (p + 1) % 2), 550);
|
|
42
|
+
return () => clearInterval(t);
|
|
43
|
+
}, [phase, busy]);
|
|
44
|
+
|
|
45
|
+
const say = (text, error = false) => { if (mounted.current) setMessage(text ? { text, error } : null); };
|
|
46
|
+
|
|
47
|
+
const load = useCallback(async () => {
|
|
48
|
+
setPhase('loading');
|
|
49
|
+
const started = Date.now();
|
|
50
|
+
let next = null;
|
|
51
|
+
let err = null;
|
|
52
|
+
try { next = await api.state(); } catch (e) { err = e; }
|
|
53
|
+
if (!next && !err) err = { code: 'service_unavailable' }; // réponse vide : jamais bloqué sur le squelette
|
|
54
|
+
const wait = 350 - (Date.now() - started);
|
|
55
|
+
if (wait > 0) await new Promise((r) => setTimeout(r, wait)); // le squelette reste visible un instant
|
|
56
|
+
if (!mounted.current) return;
|
|
57
|
+
if (next) { setState(next); setPhase('ready'); handlers.current.onReady && handlers.current.onReady(); }
|
|
58
|
+
else { setPhase('failed'); say(errorText(err), true); handlers.current.onError && handlers.current.onError(err.code); }
|
|
59
|
+
}, [api]);
|
|
60
|
+
|
|
61
|
+
useEffect(() => { load(); }, [load]);
|
|
62
|
+
|
|
63
|
+
const hide = useCallback(() => {
|
|
64
|
+
clearInterval(timer.current);
|
|
65
|
+
if (!mounted.current) return;
|
|
66
|
+
setDetails(null);
|
|
67
|
+
setSecondsLeft(0);
|
|
68
|
+
}, []);
|
|
69
|
+
|
|
70
|
+
// L'application quitte le premier plan : on ne laisse jamais un numéro affiché sans surveillance.
|
|
71
|
+
useEffect(() => {
|
|
72
|
+
const sub = AppState.addEventListener('change', (s) => { if (s !== 'active') hide(); });
|
|
73
|
+
return () => sub && sub.remove && sub.remove();
|
|
74
|
+
}, [hide]);
|
|
75
|
+
|
|
76
|
+
function startTimer(seconds) {
|
|
77
|
+
clearInterval(timer.current);
|
|
78
|
+
setSecondsLeft(seconds);
|
|
79
|
+
let left = seconds;
|
|
80
|
+
timer.current = setInterval(() => {
|
|
81
|
+
left -= 1;
|
|
82
|
+
if (left <= 0) hide(); else if (mounted.current) setSecondsLeft(left);
|
|
83
|
+
}, 1000);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Action avec retour visuel : libellé et roue sur le bouton, contrôles verrouillés, durée minimale. */
|
|
87
|
+
async function run(label, work) {
|
|
88
|
+
if (busyRef.current) return undefined;
|
|
89
|
+
busyRef.current = true;
|
|
90
|
+
setBusy(label);
|
|
91
|
+
const started = Date.now();
|
|
92
|
+
let result;
|
|
93
|
+
let err = null;
|
|
94
|
+
try { result = await work(); } catch (e) { err = e; }
|
|
95
|
+
const wait = minFeedbackMs - (Date.now() - started);
|
|
96
|
+
if (wait > 0) await new Promise((r) => setTimeout(r, wait));
|
|
97
|
+
busyRef.current = false;
|
|
98
|
+
if (!mounted.current) return undefined;
|
|
99
|
+
setBusy(null);
|
|
100
|
+
if (err) {
|
|
101
|
+
say(errorText(err), true);
|
|
102
|
+
handlers.current.onError && handlers.current.onError(err.code);
|
|
103
|
+
if (err.code === 'session_expired') setPhase('failed');
|
|
104
|
+
if (err.code === 'pin_already_set' || err.code === 'pin_not_set') {
|
|
105
|
+
api.state().then((fresh) => { if (mounted.current) setState(fresh); }, () => {}); // l'état local était périmé
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function submitPin() {
|
|
113
|
+
const pinSet = state.pin_set;
|
|
114
|
+
if (!/^\d{4}$/.test(pin1)) return say('Le code PIN doit avoir 4 chiffres.', true);
|
|
115
|
+
if (!pinSet && pin1 !== pin2) return say('Les deux codes ne correspondent pas.', true);
|
|
116
|
+
|
|
117
|
+
say(pinSet ? 'Vérification du code…' : 'Enregistrement du code…');
|
|
118
|
+
setRevealing(true);
|
|
119
|
+
const pin = pin1;
|
|
120
|
+
const card = await run(pinSet ? 'Vérification…' : 'Enregistrement…', async () => {
|
|
121
|
+
if (!pinSet) setState(await api.setPin(pin));
|
|
122
|
+
return api.reveal(pin);
|
|
123
|
+
});
|
|
124
|
+
setPin1(''); setPin2('');
|
|
125
|
+
if (mounted.current) setRevealing(false);
|
|
126
|
+
if (!card) return undefined;
|
|
127
|
+
setDetails(card);
|
|
128
|
+
setShowPin(false);
|
|
129
|
+
setMessage(null);
|
|
130
|
+
startTimer(state.reveal_seconds || 45);
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function lifecycle(freeze) {
|
|
135
|
+
say(null);
|
|
136
|
+
const next = await run(freeze ? 'Gel en cours…' : 'Dégel en cours…', () => (freeze ? api.freeze() : api.unfreeze()));
|
|
137
|
+
if (!next) {
|
|
138
|
+
try { const fresh = await api.state(); if (mounted.current) setState(fresh); } catch { /* l'erreur est déjà affichée */ }
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
hide();
|
|
142
|
+
setState(next);
|
|
143
|
+
say(freeze ? 'Carte gelée.' : 'Carte dégelée.');
|
|
144
|
+
const cb = freeze ? handlers.current.onFrozen : handlers.current.onUnfrozen;
|
|
145
|
+
if (cb) cb();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// -- Affichage ---------------------------------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
const style = (state && state.style) || {};
|
|
151
|
+
const dark = style.theme === 'dark';
|
|
152
|
+
const ink = dark ? '#FFFFFF' : '#000000';
|
|
153
|
+
const paper = dark ? '#000000' : '#FFFFFF';
|
|
154
|
+
const soft = dark ? '#A8A8A8' : '#5F6368';
|
|
155
|
+
const radius = { none: 0, sm: 8, lg: 26 }[style.radius] ?? 16;
|
|
156
|
+
const cardW = Math.min(Math.max(width, 200), 420);
|
|
157
|
+
const u = cardW / 100;
|
|
158
|
+
const loading = phase !== 'ready' || !state;
|
|
159
|
+
const frozen = !!(state && state.status === 'frozen');
|
|
160
|
+
const statusLabel = { active: 'ACTIVE', frozen: 'GELÉE', canceled: 'ANNULÉE', provisioning: 'EN CRÉATION', failed: 'ÉCHEC' }[state && state.status] || String((state && state.status) || 'ACTIVE').toUpperCase();
|
|
161
|
+
const family = style.font === 'serif' ? Platform.select({ ios: 'Georgia', default: 'serif' }) : style.font === 'mono' ? Platform.select({ ios: 'Courier', default: 'monospace' }) : undefined;
|
|
162
|
+
const withFont = (s) => (family ? { ...s, fontFamily: family } : s);
|
|
163
|
+
const skel = (w, hh) => h(View, { testID: 'tz-skeleton', style: { width: w, height: hh, borderRadius: 6, backgroundColor: ink, opacity: 0.1 + 0.1 * pulse } });
|
|
164
|
+
const numberText = details ? String(details.number).replace(/\D/g, '').replace(/(.{4})/g, '$1 ').trim() : `•••• •••• •••• ${(state && state.last4) || '••••'}`;
|
|
165
|
+
const expiry = details ? `${String(details.exp_month).padStart(2, '0')}/${String(details.exp_year).slice(-2)}` : '••/••';
|
|
166
|
+
|
|
167
|
+
const button = (testID, label, { primary = false, loadingBtn = false, onPress, disabled = false }) => h(
|
|
168
|
+
Pressable,
|
|
169
|
+
{ testID, accessibilityRole: 'button', accessibilityLabel: label, onPress: disabled ? undefined : onPress, disabled, style: { minHeight: 48, borderRadius: radius * 0.7, borderWidth: 1.5, borderColor: ink, backgroundColor: primary ? ink : paper, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 14, flexGrow: 1, flexBasis: 140, opacity: disabled && !loadingBtn ? 0.5 : 1 } },
|
|
170
|
+
h(View, { style: { flexDirection: 'row', alignItems: 'center' } },
|
|
171
|
+
loadingBtn ? h(ActivityIndicator, { testID: 'tz-spinner', color: primary ? paper : ink, size: 'small', style: { marginRight: 8 } }) : null,
|
|
172
|
+
h(Text, { style: withFont({ color: primary ? paper : ink, fontWeight: '600', fontSize: 15 }) }, label)),
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
const meta = (label, value, flex, isSkel) => h(View, { style: { flex, minWidth: 0 } },
|
|
176
|
+
h(Text, { numberOfLines: 1, style: { fontSize: Math.max(7, u * 2.3), letterSpacing: 0.9, fontWeight: '600', color: soft } }, label),
|
|
177
|
+
isSkel ? skel('90%', u * 3.6) : h(Text, { numberOfLines: 1, style: withFont({ fontSize: Math.max(9, u * 3.3), fontWeight: '600', color: ink }) }, value));
|
|
178
|
+
|
|
179
|
+
const face = h(View, { testID: 'tz-card-face', style: { width: cardW, height: cardW / 1.586, backgroundColor: paper, borderRadius: radius, borderWidth: Math.max(1.5, u * 0.5), borderColor: ink, padding: u * 6, justifyContent: 'space-between', overflow: 'hidden', opacity: frozen ? 0.6 : 1 } },
|
|
180
|
+
h(View, { style: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' } },
|
|
181
|
+
h(View, { style: { width: u * 11, height: u * 8, borderWidth: 1.2, borderColor: ink, borderRadius: u * 1.6 } }),
|
|
182
|
+
loading ? skel(u * 16, u * 5) : h(View, { style: { borderWidth: 1.5, borderColor: ink, borderRadius: 99, backgroundColor: frozen ? ink : 'transparent', paddingHorizontal: u * 2.4, paddingVertical: u * 0.8 } },
|
|
183
|
+
h(Text, { style: { fontSize: Math.max(9, u * 2.9), fontWeight: '700', letterSpacing: 1, color: frozen ? paper : ink } }, statusLabel))),
|
|
184
|
+
loading || revealing ? skel(u * 80, u * 6) : h(Text, { testID: 'tz-number', numberOfLines: 1, adjustsFontSizeToFit: true, style: { fontSize: Math.max(12, u * 5.9), fontWeight: '600', letterSpacing: 1.5, color: ink, fontVariant: ['tabular-nums'] } }, numberText),
|
|
185
|
+
h(View, { style: { flexDirection: 'row', alignItems: 'flex-end' } },
|
|
186
|
+
h(View, { style: { flex: 1, flexDirection: 'row', gap: u * 3, minWidth: 0 } },
|
|
187
|
+
meta('TITULAIRE', loading ? null : (state.holder || '—'), 5, loading),
|
|
188
|
+
meta('EXPIRE', expiry, 3, false),
|
|
189
|
+
meta('CVC', details ? String(details.cvc) : '•••', 3, false)),
|
|
190
|
+
h(View, { testID: 'tz-brand', style: { width: u * 15.5, height: u * 9.7, marginLeft: u * 3 } },
|
|
191
|
+
state && state.brand === 'visa'
|
|
192
|
+
? h(Text, { style: { color: ink, fontStyle: 'italic', fontWeight: '800', fontSize: u * 6, textAlign: 'right' } }, 'VISA')
|
|
193
|
+
: h(View, { style: { flexDirection: 'row' } },
|
|
194
|
+
h(View, { style: { width: u * 9.7, height: u * 9.7, borderRadius: u * 4.85, backgroundColor: '#EB001B' } }),
|
|
195
|
+
h(View, { style: { width: u * 9.7, height: u * 9.7, borderRadius: u * 4.85, backgroundColor: '#F79E1B', opacity: 0.92, marginLeft: -u * 3.9 } })))),
|
|
196
|
+
busy ? h(View, { testID: 'tz-progress', style: { position: 'absolute', left: 0, bottom: 0, height: 3, width: pulse ? '70%' : '30%', backgroundColor: ink } }) : null);
|
|
197
|
+
|
|
198
|
+
const pinField = (testID, label, value, set, submit) => h(View, { style: { marginBottom: 10 } },
|
|
199
|
+
h(Text, { style: { fontSize: 13, color: soft, marginBottom: 6 } }, label),
|
|
200
|
+
h(TextInput, { testID, accessibilityLabel: label, value, onChangeText: (t) => set(t.replace(/\D/g, '').slice(0, 4)), editable: !busy, secureTextEntry: true, keyboardType: 'number-pad', maxLength: 4, autoCorrect: false, autoComplete: 'off', onSubmitEditing: submit, style: { height: 48, borderWidth: 1.5, borderColor: ink, borderRadius: radius * 0.6, textAlign: 'center', fontSize: 20, letterSpacing: 8, color: ink } }));
|
|
201
|
+
|
|
202
|
+
const creating = state ? !state.pin_set : false;
|
|
203
|
+
const pinPanel = showPin && state ? h(View, { style: { marginTop: 12, padding: 14, borderWidth: 1.5, borderColor: ink, borderRadius: radius } },
|
|
204
|
+
pinField('tz-pin1', creating ? 'Créez le code PIN (4 chiffres)' : 'Code PIN de la carte', pin1, setPin1, creating ? undefined : submitPin),
|
|
205
|
+
creating ? pinField('tz-pin2', 'Confirmez le code PIN', pin2, setPin2, submitPin) : null,
|
|
206
|
+
h(View, { style: { flexDirection: 'row', gap: 8, flexWrap: 'wrap' } },
|
|
207
|
+
button('tz-pin-ok', busy || 'Valider', { primary: true, loadingBtn: !!busy, onPress: submitPin, disabled: !!busy }),
|
|
208
|
+
button('tz-pin-cancel', 'Annuler', { onPress: () => { setShowPin(false); setPin1(''); setPin2(''); setMessage(null); }, disabled: !!busy }))) : null;
|
|
209
|
+
|
|
210
|
+
const actions = state ? [
|
|
211
|
+
state.can_reveal && !details && !showPin ? button('tz-reveal', 'Afficher les détails', { primary: true, onPress: () => { setShowPin(true); setMessage(null); }, disabled: !!busy }) : null,
|
|
212
|
+
details ? button('tz-hide', 'Masquer', { onPress: hide, disabled: !!busy }) : null,
|
|
213
|
+
state.can_freeze ? button('tz-freeze', busy === 'Gel en cours…' ? busy : 'Geler la carte', { loadingBtn: busy === 'Gel en cours…', onPress: () => lifecycle(true), disabled: !!busy }) : null,
|
|
214
|
+
state.can_unfreeze ? button('tz-unfreeze', busy === 'Dégel en cours…' ? busy : 'Dégeler la carte', { loadingBtn: busy === 'Dégel en cours…', onPress: () => lifecycle(false), disabled: !!busy }) : null,
|
|
215
|
+
].filter(Boolean) : [];
|
|
216
|
+
|
|
217
|
+
return h(View, { onLayout: (e) => setWidth(e.nativeEvent.layout.width), style: { width: '100%', alignItems: 'center' } },
|
|
218
|
+
h(View, { style: { width: cardW } },
|
|
219
|
+
face,
|
|
220
|
+
h(View, { style: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 14 } },
|
|
221
|
+
h(Text, { style: { fontSize: 14, color: soft } }, 'Solde disponible'),
|
|
222
|
+
state ? h(Text, { testID: 'tz-balance', style: withFont({ fontSize: 16, fontWeight: '700', color: ink }) }, `$${Number(state.balance).toFixed(2)} ${state.currency}`) : skel(80, 16)),
|
|
223
|
+
secondsLeft > 0 ? h(Text, { style: { fontSize: 12, color: soft, marginTop: 8 } }, `Les détails se masquent dans ${secondsLeft} s`) : null,
|
|
224
|
+
pinPanel,
|
|
225
|
+
actions.length ? h(View, { style: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginTop: 12 } }, ...actions) : null,
|
|
226
|
+
!message && state && state.frozen_by_tranzak ? h(Text, { testID: 'tz-tranzak-freeze', style: { marginTop: 10, fontSize: 13.5, color: soft } }, errorText({ code: 'frozen_by_tranzak' })) : null,
|
|
227
|
+
message ? h(Text, { testID: 'tz-message', accessibilityLiveRegion: 'polite', style: { marginTop: 10, fontSize: 13.5, lineHeight: 19, fontWeight: message.error ? '700' : '400', color: message.error ? ink : soft } }, message.text) : null,
|
|
228
|
+
phase === 'failed' && !state ? h(Pressable, { testID: 'tz-retry', onPress: load, style: { marginTop: 8, padding: 8 } }, h(Text, { style: { color: ink, fontWeight: '700' } }, 'Réessayer')) : null));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export default TranzakCardView;
|
package/src/api.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client de l'API du widget en mode natif. Le secret de session vient de VOTRE serveur
|
|
3
|
+
* (`createNativeSession` de @tranzakpackage/cards-server) : jamais votre clé API.
|
|
4
|
+
*
|
|
5
|
+
* Rien n'est journalisé ni mis en cache : ni le secret, ni le PIN, ni les détails de la carte.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export class CardApiError extends Error {
|
|
9
|
+
constructor(code, { retryAfterSeconds, attemptsLeft } = {}) {
|
|
10
|
+
super(code);
|
|
11
|
+
this.name = 'CardApiError';
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
14
|
+
this.attemptsLeft = attemptsLeft;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function createCardsApi({ apiBase, sessionSecret, fetchImpl = globalThis.fetch, timeoutMs = 20000 }) {
|
|
19
|
+
const base = String(apiBase).replace(/\/+$/, '');
|
|
20
|
+
|
|
21
|
+
/** HTTPS obligatoire (HTTP seulement pour un poste de développement : localhost, 127.0.0.1, 10.0.2.2). */
|
|
22
|
+
function allowedBase() {
|
|
23
|
+
try {
|
|
24
|
+
const u = new URL(base);
|
|
25
|
+
return u.protocol === 'https:' || (u.protocol === 'http:' && ['localhost', '127.0.0.1', '10.0.2.2'].includes(u.hostname));
|
|
26
|
+
} catch { return false; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Une réponse « succès » sans l'objet attendu est une panne du service, pas un plantage. */
|
|
30
|
+
const need = (value) => { if (value === undefined || value === null) throw new CardApiError('service_unavailable'); return value; };
|
|
31
|
+
|
|
32
|
+
async function send(method, path, body) {
|
|
33
|
+
if (!allowedBase()) throw new CardApiError('network');
|
|
34
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
|
|
35
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
36
|
+
let res;
|
|
37
|
+
try {
|
|
38
|
+
res = await fetchImpl(`${base}/${path}`, {
|
|
39
|
+
method,
|
|
40
|
+
headers: { 'X-Widget-Session': sessionSecret, Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
41
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
42
|
+
signal: controller ? controller.signal : undefined,
|
|
43
|
+
});
|
|
44
|
+
} catch (e) {
|
|
45
|
+
throw new CardApiError(e && e.name === 'AbortError' ? 'timeout' : 'network');
|
|
46
|
+
} finally {
|
|
47
|
+
if (timer) clearTimeout(timer);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
let json;
|
|
51
|
+
try { json = await res.json(); } catch { throw new CardApiError('service_unavailable'); }
|
|
52
|
+
if (json && json.success === true) return json;
|
|
53
|
+
throw new CardApiError((json && json.error) || 'error', { retryAfterSeconds: json && json.retry_after, attemptsLeft: json && json.attempts_left });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
state: async () => need((await send('GET', 'state')).state),
|
|
58
|
+
setPin: async (pin) => need((await send('POST', 'pin', { pin })).state),
|
|
59
|
+
/** Numéro complet, CVC, expiration : après le PIN, pour cet appel seulement. */
|
|
60
|
+
reveal: async (pin) => need((await send('POST', 'reveal', { pin })).card),
|
|
61
|
+
freeze: async () => need((await send('POST', 'freeze')).state),
|
|
62
|
+
unfreeze: async () => need((await send('POST', 'unfreeze')).state),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function errorText(e) {
|
|
67
|
+
switch (e.code) {
|
|
68
|
+
case 'session_expired': return 'La session a expiré. Rouvrez la carte.';
|
|
69
|
+
case 'wrong_pin': return e.attemptsLeft != null ? `Code PIN incorrect. Essais restants : ${e.attemptsLeft}.` : 'Code PIN incorrect.';
|
|
70
|
+
case 'pin_locked': return `Trop d’essais. Réessayez dans ${Math.ceil((e.retryAfterSeconds || 900) / 60)} min.`;
|
|
71
|
+
case 'pin_already_set': return 'Un code PIN existe déjà pour cette carte. Saisissez-le pour continuer.';
|
|
72
|
+
case 'pin_not_set': return 'Créez d\u2019abord le code PIN de cette carte.';
|
|
73
|
+
case 'weak_pin': return 'Choisissez un code moins évident (pas 1234, pas 1111).';
|
|
74
|
+
case 'frozen_by_tranzak': return 'Cette carte a été gelée par Tranzak. Contactez le support.';
|
|
75
|
+
case 'card_locked': return 'Cette carte est verrouillée par Tranzak.';
|
|
76
|
+
case 'card_not_funded': return 'Rechargez la carte avant de la dégeler.';
|
|
77
|
+
case 'card_unavailable': return 'Cette carte n’est pas disponible.';
|
|
78
|
+
case 'not_permitted': return 'Action non autorisée.';
|
|
79
|
+
case 'timeout': return 'La connexion est trop lente. Réessayez dans un instant.';
|
|
80
|
+
default: return 'Service momentanément indisponible. Réessayez dans un instant.';
|
|
81
|
+
}
|
|
82
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ComponentType } from 'react';
|
|
2
|
+
|
|
3
|
+
export interface TranzakCardViewProps {
|
|
4
|
+
/** `api_base` returned by your server (native session). */
|
|
5
|
+
apiBase: string;
|
|
6
|
+
/** `session_secret` returned by your server (native session). Never your API key. */
|
|
7
|
+
sessionSecret: string;
|
|
8
|
+
onReady?: () => void;
|
|
9
|
+
onFrozen?: () => void;
|
|
10
|
+
onUnfrozen?: () => void;
|
|
11
|
+
/** A code such as session_expired, pin_locked, frozen_by_tranzak. Never card data. */
|
|
12
|
+
onError?: (code: string) => void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const TranzakCardView: ComponentType<TranzakCardViewProps>;
|
|
16
|
+
export default TranzakCardView;
|
|
17
|
+
|
|
18
|
+
export class CardApiError extends Error { code: string; retryAfterSeconds?: number; attemptsLeft?: number }
|
|
19
|
+
export function createCardsApi(options: { apiBase: string; sessionSecret: string; fetchImpl?: typeof fetch; timeoutMs?: number }): {
|
|
20
|
+
state(): Promise<unknown>; setPin(pin: string): Promise<unknown>; reveal(pin: string): Promise<{ number: string; cvc: string; exp_month: number; exp_year: number }>;
|
|
21
|
+
freeze(): Promise<unknown>; unfreeze(): Promise<unknown>;
|
|
22
|
+
};
|
|
23
|
+
export function errorText(e: CardApiError): string;
|
package/src/index.js
ADDED