@quantaroute/checkout 1.3.2 → 1.4.1

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.
@@ -0,0 +1,227 @@
1
+ import React, { useState, useRef, useCallback, useEffect } from 'react';
2
+ import { verifyOtp, sendOtp } from '../core/checkout-api';
3
+ import type { OtpStepProps } from '../core/types';
4
+
5
+ const OTP_LENGTH = 6;
6
+ const RESEND_COOLDOWN = 30; // seconds
7
+
8
+ /** Mask phone for display: +91 98765 **210 */
9
+ function maskMobile(mobile: string): string {
10
+ const digits = mobile.replace(/\D/g, '');
11
+ if (digits.length < 4) return mobile;
12
+ return `+91 ${digits.slice(2, 7)} **${digits.slice(-3)}`;
13
+ }
14
+
15
+ const OtpStep: React.FC<OtpStepProps> = ({
16
+ mobile,
17
+ onVerified,
18
+ onBack,
19
+ functionBaseUrl,
20
+ merchantId,
21
+ sessionContext,
22
+ }) => {
23
+ const [digits, setDigits] = useState<string[]>(Array(OTP_LENGTH).fill(''));
24
+ const [loading, setLoading] = useState(false);
25
+ const [error, setError] = useState<string | null>(null);
26
+ const [resendCountdown, setResendCountdown] = useState(RESEND_COOLDOWN);
27
+ const [resendLoading, setResendLoading] = useState(false);
28
+ const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
29
+ const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
30
+
31
+ // Start countdown on mount
32
+ useEffect(() => {
33
+ timerRef.current = setInterval(() => {
34
+ setResendCountdown((c) => {
35
+ if (c <= 1) {
36
+ clearInterval(timerRef.current!);
37
+ return 0;
38
+ }
39
+ return c - 1;
40
+ });
41
+ }, 1000);
42
+ return () => { if (timerRef.current) clearInterval(timerRef.current); };
43
+ }, []);
44
+
45
+ const focusBox = (index: number) => {
46
+ inputRefs.current[index]?.focus();
47
+ };
48
+
49
+ const handleDigitChange = useCallback((index: number, value: string) => {
50
+ const char = value.replace(/\D/g, '').slice(-1);
51
+ setError(null);
52
+
53
+ setDigits((prev) => {
54
+ const next = [...prev];
55
+ next[index] = char;
56
+ return next;
57
+ });
58
+
59
+ if (char && index < OTP_LENGTH - 1) {
60
+ focusBox(index + 1);
61
+ }
62
+ }, []);
63
+
64
+ const handleKeyDown = useCallback((index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
65
+ if (e.key === 'Backspace') {
66
+ if (digits[index]) {
67
+ // Clear current box
68
+ setDigits((prev) => { const n = [...prev]; n[index] = ''; return n; });
69
+ } else if (index > 0) {
70
+ // Move back and clear previous
71
+ setDigits((prev) => { const n = [...prev]; n[index - 1] = ''; return n; });
72
+ focusBox(index - 1);
73
+ }
74
+ } else if (e.key === 'ArrowLeft' && index > 0) {
75
+ focusBox(index - 1);
76
+ } else if (e.key === 'ArrowRight' && index < OTP_LENGTH - 1) {
77
+ focusBox(index + 1);
78
+ }
79
+ }, [digits]);
80
+
81
+ // Handle paste into any box
82
+ const handlePaste = useCallback((e: React.ClipboardEvent<HTMLInputElement>) => {
83
+ e.preventDefault();
84
+ const pasted = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, OTP_LENGTH);
85
+ if (!pasted) return;
86
+ const next = Array(OTP_LENGTH).fill('');
87
+ pasted.split('').forEach((ch, i) => { next[i] = ch; });
88
+ setDigits(next);
89
+ setError(null);
90
+ focusBox(Math.min(pasted.length, OTP_LENGTH - 1));
91
+ }, []);
92
+
93
+ const otp = digits.join('');
94
+ const isComplete = otp.length === OTP_LENGTH && !digits.includes('');
95
+
96
+ const handleVerify = useCallback(async () => {
97
+ if (!isComplete) return;
98
+ setLoading(true);
99
+ setError(null);
100
+ try {
101
+ const result = await verifyOtp({ functionBaseUrl, merchantId }, mobile, otp, sessionContext);
102
+ onVerified(result.session_token, result.buyer_id, result.session_id);
103
+ } catch (err: unknown) {
104
+ setError(err instanceof Error ? err.message : 'Verification failed. Please try again.');
105
+ // Clear boxes on wrong OTP so user can retry without backspacing
106
+ setDigits(Array(OTP_LENGTH).fill(''));
107
+ focusBox(0);
108
+ } finally {
109
+ setLoading(false);
110
+ }
111
+ }, [isComplete, otp, mobile, functionBaseUrl, merchantId, onVerified, sessionContext]);
112
+
113
+ // Auto-verify once all 6 digits are filled (great UX for SMS auto-read)
114
+ useEffect(() => {
115
+ if (isComplete && !loading) {
116
+ handleVerify();
117
+ }
118
+ // eslint-disable-next-line react-hooks/exhaustive-deps
119
+ }, [isComplete]);
120
+
121
+ const handleResend = useCallback(async () => {
122
+ if (resendCountdown > 0 || resendLoading) return;
123
+ setResendLoading(true);
124
+ setError(null);
125
+ setDigits(Array(OTP_LENGTH).fill(''));
126
+ try {
127
+ await sendOtp({ functionBaseUrl, merchantId }, mobile);
128
+ // Restart countdown
129
+ setResendCountdown(RESEND_COOLDOWN);
130
+ timerRef.current = setInterval(() => {
131
+ setResendCountdown((c) => {
132
+ if (c <= 1) { clearInterval(timerRef.current!); return 0; }
133
+ return c - 1;
134
+ });
135
+ }, 1000);
136
+ focusBox(0);
137
+ } catch (err: unknown) {
138
+ setError(err instanceof Error ? err.message : 'Failed to resend OTP.');
139
+ } finally {
140
+ setResendLoading(false);
141
+ }
142
+ }, [resendCountdown, resendLoading, functionBaseUrl, merchantId, mobile]);
143
+
144
+ return (
145
+ <div className="qr-auth-step">
146
+ {/* Back */}
147
+ <button type="button" className="qr-back-btn qr-back-btn--auth" onClick={onBack} disabled={loading}>
148
+ <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
149
+ <path d="M19 12H5M12 5l-7 7 7 7" />
150
+ </svg>
151
+ </button>
152
+
153
+ {/* Icon */}
154
+ <div className="qr-auth-step__icon" aria-hidden="true">
155
+ <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
156
+ <circle cx="24" cy="24" r="24" fill="var(--qr-primary-light)" />
157
+ <rect x="13" y="16" width="22" height="16" rx="2" stroke="var(--qr-primary)" strokeWidth="1.8" fill="none" />
158
+ <path d="M13 22h22" stroke="var(--qr-primary)" strokeWidth="1.8" />
159
+ <circle cx="18" cy="29" r="1.5" fill="var(--qr-primary)" />
160
+ <circle cx="24" cy="29" r="1.5" fill="var(--qr-primary)" />
161
+ <circle cx="30" cy="29" r="1.5" fill="var(--qr-primary)" />
162
+ </svg>
163
+ </div>
164
+
165
+ <h3 className="qr-auth-step__title">Enter OTP</h3>
166
+ <p className="qr-auth-step__sub">
167
+ Sent to <strong>{maskMobile(mobile)}</strong>
168
+ </p>
169
+
170
+ {/* OTP boxes */}
171
+ <div className="qr-otp-boxes" role="group" aria-label="Enter one-time password">
172
+ {digits.map((d, i) => (
173
+ <input
174
+ key={i}
175
+ ref={(el) => { inputRefs.current[i] = el; }}
176
+ type="text"
177
+ inputMode="numeric"
178
+ maxLength={1}
179
+ className={`qr-otp-box${d ? ' qr-otp-box--filled' : ''}${error ? ' qr-otp-box--error' : ''}`}
180
+ value={d}
181
+ onChange={(e) => handleDigitChange(i, e.target.value)}
182
+ onKeyDown={(e) => handleKeyDown(i, e)}
183
+ onPaste={handlePaste}
184
+ onFocus={(e) => e.target.select()}
185
+ aria-label={`OTP digit ${i + 1}`}
186
+ disabled={loading}
187
+ autoComplete={i === 0 ? 'one-time-code' : 'off'}
188
+ />
189
+ ))}
190
+ </div>
191
+
192
+ {error && (
193
+ <p className="qr-auth-step__error" role="alert">{error}</p>
194
+ )}
195
+
196
+ {/* Verify button — shows when not auto-verifying */}
197
+ <button
198
+ type="button"
199
+ className="qr-btn qr-btn--primary qr-btn--full"
200
+ onClick={handleVerify}
201
+ disabled={!isComplete || loading}
202
+ >
203
+ {loading ? (
204
+ <span className="qr-spinner qr-spinner--sm" aria-hidden="true" />
205
+ ) : 'Verify OTP'}
206
+ </button>
207
+
208
+ {/* Resend */}
209
+ <p className="qr-auth-step__resend">
210
+ {resendCountdown > 0 ? (
211
+ <span>Resend OTP in {resendCountdown}s</span>
212
+ ) : (
213
+ <button
214
+ type="button"
215
+ className="qr-link-btn"
216
+ onClick={handleResend}
217
+ disabled={resendLoading}
218
+ >
219
+ {resendLoading ? 'Sending…' : 'Resend OTP'}
220
+ </button>
221
+ )}
222
+ </p>
223
+ </div>
224
+ );
225
+ };
226
+
227
+ export default OtpStep;
@@ -0,0 +1,162 @@
1
+ import React, { useEffect, useState } from 'react';
2
+ import {
3
+ createPaymentOrder,
4
+ recordCodPayment,
5
+ verifyPayment,
6
+ } from '../core/checkout-api';
7
+ import type { PaymentStepProps } from '../core/types';
8
+
9
+ declare global {
10
+ interface Window {
11
+ Razorpay?: new (options: Record<string, unknown>) => { open: () => void };
12
+ }
13
+ }
14
+
15
+ const RAZORPAY_SCRIPT = 'https://checkout.razorpay.com/v1/checkout.js';
16
+
17
+ function loadRazorpayScript(): Promise<void> {
18
+ if (window.Razorpay) return Promise.resolve();
19
+ return new Promise((resolve, reject) => {
20
+ const existing = document.querySelector(`script[src="${RAZORPAY_SCRIPT}"]`);
21
+ if (existing) {
22
+ existing.addEventListener('load', () => resolve());
23
+ return;
24
+ }
25
+ const script = document.createElement('script');
26
+ script.src = RAZORPAY_SCRIPT;
27
+ script.async = true;
28
+ script.onload = () => resolve();
29
+ script.onerror = () => reject(new Error('Failed to load Razorpay'));
30
+ document.body.appendChild(script);
31
+ });
32
+ }
33
+
34
+ const PaymentStep: React.FC<PaymentStepProps> = ({
35
+ checkoutConfig,
36
+ sessionToken,
37
+ sessionId,
38
+ amountPaise,
39
+ enableCod = false,
40
+ codAllowed = false,
41
+ theme = 'light',
42
+ onComplete,
43
+ onBack,
44
+ onEvent,
45
+ }) => {
46
+ const [loading, setLoading] = useState(false);
47
+ const [error, setError] = useState<string | null>(null);
48
+ const isDark = theme === 'dark';
49
+
50
+ useEffect(() => {
51
+ onEvent?.('payment_step_viewed');
52
+ }, [onEvent]);
53
+
54
+ const handlePrepaid = async () => {
55
+ setLoading(true);
56
+ setError(null);
57
+ try {
58
+ await loadRazorpayScript();
59
+ const order = await createPaymentOrder(checkoutConfig, sessionToken, amountPaise);
60
+
61
+ await new Promise<void>((resolve, reject) => {
62
+ if (!window.Razorpay) {
63
+ reject(new Error('Razorpay unavailable'));
64
+ return;
65
+ }
66
+ const rzp = new window.Razorpay({
67
+ key: order.razorpay_key_id,
68
+ amount: order.amount_paise,
69
+ currency: order.currency,
70
+ order_id: order.razorpay_order_id,
71
+ name: 'Checkout',
72
+ handler: async (response: {
73
+ razorpay_payment_id: string;
74
+ razorpay_order_id: string;
75
+ razorpay_signature: string;
76
+ }) => {
77
+ try {
78
+ const result = await verifyPayment(checkoutConfig, sessionToken, {
79
+ razorpay_order_id: response.razorpay_order_id,
80
+ razorpay_payment_id: response.razorpay_payment_id,
81
+ razorpay_signature: response.razorpay_signature,
82
+ payment_method: 'prepaid',
83
+ });
84
+ onEvent?.('payment_method_selected', result.payment_method);
85
+ onComplete(result.payment_method);
86
+ resolve();
87
+ } catch (e) {
88
+ reject(e);
89
+ }
90
+ },
91
+ modal: {
92
+ ondismiss: () => reject(new Error('Payment cancelled')),
93
+ },
94
+ });
95
+ rzp.open();
96
+ });
97
+ } catch (e) {
98
+ setError(e instanceof Error ? e.message : 'Payment failed');
99
+ } finally {
100
+ setLoading(false);
101
+ }
102
+ };
103
+
104
+ const handleCod = async () => {
105
+ setLoading(true);
106
+ setError(null);
107
+ try {
108
+ const result = await recordCodPayment(checkoutConfig, sessionToken);
109
+ onEvent?.('payment_method_selected', result.payment_method);
110
+ onComplete(result.payment_method);
111
+ } catch (e) {
112
+ setError(e instanceof Error ? e.message : 'Failed to select COD');
113
+ } finally {
114
+ setLoading(false);
115
+ }
116
+ };
117
+
118
+ const amountDisplay = `₹${(amountPaise / 100).toLocaleString('en-IN')}`;
119
+
120
+ return (
121
+ <div className={`qr-payment-step${isDark ? ' qr-payment-step--dark' : ''}`}>
122
+ {onBack ? (
123
+ <button type="button" className="qr-back-btn qr-back-btn--auth" onClick={onBack} disabled={loading}>
124
+ ← Back
125
+ </button>
126
+ ) : null}
127
+ <h3 className="qr-auth-step__title">Choose payment</h3>
128
+ <p className="qr-auth-step__sub">
129
+ Order total: <strong>{amountDisplay}</strong>
130
+ </p>
131
+
132
+ {error ? <p className="qr-auth-step__error" role="alert">{error}</p> : null}
133
+
134
+ <button
135
+ type="button"
136
+ className="qr-btn qr-btn--primary qr-btn--full"
137
+ onClick={handlePrepaid}
138
+ disabled={loading}
139
+ >
140
+ {loading ? 'Processing…' : `Pay ${amountDisplay} online`}
141
+ </button>
142
+
143
+ {enableCod && codAllowed ? (
144
+ <button
145
+ type="button"
146
+ className="qr-btn qr-btn--ghost qr-btn--full"
147
+ onClick={handleCod}
148
+ disabled={loading}
149
+ style={{ marginTop: 8 }}
150
+ >
151
+ Cash on Delivery
152
+ </button>
153
+ ) : null}
154
+
155
+ {sessionId ? (
156
+ <p className="qr-payment-step__meta">Session {sessionId.slice(0, 8)}…</p>
157
+ ) : null}
158
+ </div>
159
+ );
160
+ };
161
+
162
+ export default PaymentStep;
@@ -0,0 +1,124 @@
1
+ import React, { useState, useRef, useCallback } from 'react';
2
+ import { sendOtp } from '../core/checkout-api';
3
+ import type { PhoneStepProps } from '../core/types';
4
+
5
+ /** Strip everything except digits, enforce 10-digit Indian mobile */
6
+ function normaliseMobile(raw: string): string {
7
+ const digits = raw.replace(/\D/g, '').slice(0, 10);
8
+ return digits;
9
+ }
10
+
11
+ const PhoneStep: React.FC<PhoneStepProps> = ({
12
+ onOtpSent,
13
+ onSkip,
14
+ functionBaseUrl,
15
+ merchantId,
16
+ }) => {
17
+ const [mobile, setMobile] = useState('');
18
+ const [loading, setLoading] = useState(false);
19
+ const [error, setError] = useState<string | null>(null);
20
+ const inputRef = useRef<HTMLInputElement>(null);
21
+
22
+ const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
23
+ setMobile(normaliseMobile(e.target.value));
24
+ setError(null);
25
+ }, []);
26
+
27
+ const handleSubmit = useCallback(async (e: React.FormEvent) => {
28
+ e.preventDefault();
29
+ if (mobile.length !== 10) {
30
+ setError('Enter a valid 10-digit mobile number.');
31
+ inputRef.current?.focus();
32
+ return;
33
+ }
34
+ setLoading(true);
35
+ setError(null);
36
+ try {
37
+ await sendOtp({ functionBaseUrl, merchantId }, `+91${mobile}`);
38
+ onOtpSent(`+91${mobile}`);
39
+ } catch (err: unknown) {
40
+ setError(err instanceof Error ? err.message : 'Failed to send OTP. Please try again.');
41
+ } finally {
42
+ setLoading(false);
43
+ }
44
+ }, [mobile, functionBaseUrl, merchantId, onOtpSent]);
45
+
46
+ return (
47
+ <div className="qr-auth-step">
48
+ {/* Icon */}
49
+ <div className="qr-auth-step__icon" aria-hidden="true">
50
+ <svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
51
+ <circle cx="24" cy="24" r="24" fill="var(--qr-primary-light)" />
52
+ <path
53
+ d="M16 14h4l2 5-2.5 1.5a11 11 0 005 5L26 23l5 2v4c0 1.1-.9 2-2 2A18 18 0 0114 16c0-1.1.9-2 2-2z"
54
+ stroke="var(--qr-primary)"
55
+ strokeWidth="1.8"
56
+ strokeLinecap="round"
57
+ strokeLinejoin="round"
58
+ fill="none"
59
+ />
60
+ </svg>
61
+ </div>
62
+
63
+ <h3 className="qr-auth-step__title">Faster checkout</h3>
64
+ <p className="qr-auth-step__sub">
65
+ Enter your mobile to load saved addresses
66
+ </p>
67
+
68
+ <form onSubmit={handleSubmit} noValidate>
69
+ <div className={`qr-phone-field${error ? ' qr-phone-field--error' : ''}`}>
70
+ <span className="qr-phone-field__prefix" aria-hidden="true">+91</span>
71
+ <input
72
+ ref={inputRef}
73
+ type="tel"
74
+ inputMode="numeric"
75
+ className="qr-phone-field__input"
76
+ placeholder="98765 43210"
77
+ value={mobile}
78
+ onChange={handleChange}
79
+ maxLength={10}
80
+ autoComplete="tel-national"
81
+ aria-label="Mobile number"
82
+ aria-describedby={error ? 'qr-phone-error' : undefined}
83
+ aria-invalid={!!error}
84
+ disabled={loading}
85
+ />
86
+ </div>
87
+
88
+ {error && (
89
+ <p id="qr-phone-error" className="qr-auth-step__error" role="alert">
90
+ {error}
91
+ </p>
92
+ )}
93
+
94
+ <button
95
+ type="submit"
96
+ className="qr-btn qr-btn--primary qr-btn--full"
97
+ disabled={loading || mobile.length !== 10}
98
+ >
99
+ {loading ? (
100
+ <span className="qr-spinner qr-spinner--sm" aria-hidden="true" />
101
+ ) : (
102
+ <>
103
+ Send OTP
104
+ <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
105
+ <path d="M5 12h14M12 5l7 7-7 7" />
106
+ </svg>
107
+ </>
108
+ )}
109
+ </button>
110
+ </form>
111
+
112
+ <button
113
+ type="button"
114
+ className="qr-auth-step__skip"
115
+ onClick={onSkip}
116
+ disabled={loading}
117
+ >
118
+ Skip, enter address manually
119
+ </button>
120
+ </div>
121
+ );
122
+ };
123
+
124
+ export default PhoneStep;
@@ -0,0 +1,31 @@
1
+ import React from 'react';
2
+ import type { PrepaidNudgeProps } from '../core/types';
3
+
4
+ /**
5
+ * C5 prepaid nudge — shown when COD is eligible to encourage prepaid checkout.
6
+ */
7
+ const PrepaidNudge: React.FC<PrepaidNudgeProps> = ({ copy, ctaUrl, theme = 'light' }) => {
8
+ const isDark = theme === 'dark';
9
+
10
+ return (
11
+ <div
12
+ className={`qr-prepaid-nudge${isDark ? ' qr-prepaid-nudge--dark' : ''}`}
13
+ role="complementary"
14
+ aria-label="Prepaid offer"
15
+ >
16
+ <p className="qr-prepaid-nudge__copy">{copy}</p>
17
+ {ctaUrl ? (
18
+ <a
19
+ href={ctaUrl}
20
+ className="qr-btn qr-btn--primary qr-btn--sm qr-prepaid-nudge__cta"
21
+ target="_blank"
22
+ rel="noopener noreferrer"
23
+ >
24
+ Pay online instead
25
+ </a>
26
+ ) : null}
27
+ </div>
28
+ );
29
+ };
30
+
31
+ export default PrepaidNudge;